Pick the model that costs least

Pick the model that costs least

Perplexity LLM Interview Question

Perplexity sends every request to a language model, and the largest model is rarely the one the request needs. Models differ in two ways that matter here: how much text they can hold at once, and what they charge for it. The rule that keeps the bill down is to send each request to the cheapest model that can still hold it.

Write a function cheapest_model(prompt_tokens, max_output, models) that returns the name of the cheapest model able to run the request. The prompt is the text you are sending, counted in tokens, and the output is the most you will let the model write back. Each model is a dictionary holding its "name", its "context" window in tokens, and its "input" and "output" prices per thousand tokens. A model can run the request only when its context window holds the prompt and the output together. The cost is the prompt at the input price plus the output at the output price. Return None when no model is large enough. If two cost the same, return whichever comes first in the list.

Asked of

  • AI Engineer
  • ML Engineer
  • Data Scientist

Example 1

Input

prompt_tokens = 1000, max_output = 500, models = [{"name": "mini", "context": 8000, "input": 0.15, "output": 0.6}, {"name": "standard", "context": 32000, "input": 0.5, "output": 1.5}, {"name": "large", "context": 128000, "input": 2.5, "output": 10}]

Output

"mini"

Example 2

Input

prompt_tokens = 20000, max_output = 2000, models = [{"name": "mini", "context": 8000, "input": 0.15, "output": 0.6}, {"name": "standard", "context": 32000, "input": 0.5, "output": 1.5}, {"name": "large", "context": 128000, "input": 2.5, "output": 10}]

Output

"standard"

Example 3

Input

prompt_tokens = 200000, max_output = 1000, models = [{"name": "mini", "context": 8000, "input": 0.15, "output": 0.6}, {"name": "standard", "context": 32000, "input": 0.5, "output": 1.5}, {"name": "large", "context": 128000, "input": 2.5, "output": 10}]

Output

None

Explanation

In the first example every model can hold a short request, so the cheapest of them wins it. In the second the prompt is too long for the small model, and the choice is between the two that remain. In the third nothing is large enough to hold the request at all.

Submit also runs 4 hidden test cases that check edge cases.

Similar questions