LLM API Cost Estimator

easy
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 2. Everything before it counts as cleared.

LLM APIs charge per million tokens, with different prices for input and output, and a discount for input tokens served from the prompt cache.

Implement estimate_cost(calls, prices):

  • prices maps a model name to {"input": $, "output": $, "cached_input": $}, each per 1M tokens.
  • Each call is a dict with "model", "input_tokens", "output_tokens" and optionally "cached_tokens" (default 0). Cached tokens are part of input_tokens but billed at the cached rate instead of the normal one.
  • Return a dict with "total" (the cost in dollars, rounded to 6 decimal places) and "by_model" (cost per model, also rounded to 6 places).
  • Raise KeyError for a model that isn't in prices.

Example: 1,000,000 input tokens, 400,000 of them cached, plus 100,000 output tokens, at 3input/3 input / 0.30 cached / 15output:600k×15 output: 600k × 3 + 400k × 0.30+100k×0.30 + 100k × 15 = 1.80+1.80 + 0.12 + 1.50=∗∗1.50 = **3.42**.

#llm#apis#cost2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
LLM API Cost Estimator · TechGradify