Price an API request with cached input tokens
LLM APIs bill input and output tokens separately, per million tokens, and many give a discount on input tokens served from a prompt cache. Getting this arithmetic right is the first step of any cost dashboard.
Write request_cost(input_tokens, cached_tokens, output_tokens, price_in, price_cached, price_out). cached_tokens is the part of input_tokens that hit the cache (0 <= cached_tokens <= input_tokens). Prices are in dollars per million tokens. Uncached input pays price_in, cached input pays price_cached, output pays price_out. Return the cost in dollars as a float.
def request_cost(input_tokens, cached_tokens, output_tokens, price_in, price_cached, price_out)Example
request_cost(1000000, 400000, 200000, 3.0, 0.3, 15.0) = 0.6 * 3 + 0.4 * 0.3 + 0.2 * 15 = 4.92.
Understand the idea
LLM APIs price tokens per million, with different rates for input and output. Many also give a discount when part of the input was served from a prompt cache. The cached tokens are a part of the input, not extra, so they move from the full input price to the cheaper cached price. Worked example: 2,000,000 input tokens of which 1,500,000 are cached, 500,000 output tokens, prices 2.0 input, 0.5 cached, 8.0 output (dollars per million). Uncached input = 0.5 million * 2.0 = 1.00. Cached = 1.5 * 0.5 = 0.75. Output = 0.5 * 8.0 = 4.00. Total = 5.75 dollars. Rule: cost = (input - cached) / 1e6 * price_in + cached / 1e6 * price_cached + output / 1e6 * price_out. Charging all input at full price and then adding cached tokens again double counts them. This arithmetic sits under every LLM cost dashboard, budget alert and per-customer billing report.