Engineering

How do I calculate the cost of an LLM request?

Short answer

Multiply input tokens by the model's input rate, add output tokens times its output rate, and divide by one million, because providers price per million tokens. Read the token counts from the usage field in each response, store one row per attempt with a run id, and sum by run. Output tokens usually cost several times more than input tokens, so the output column drives the bill.

#The formula, with a worked example

cost = (input_tokens * input_rate + output_tokens * output_rate) / 1,000,000
Gemini 2.5 Flash-Lite: $0.10 in, $0.40 out per 1M tokens
2,000 input tokens and 300 output tokens:
(2000 * 0.10 + 300 * 0.40) / 1,000,000
= (200 + 120) / 1,000,000
= $0.00032

Rates are the published Gemini 2.5 Flash-Lite rates quoted in LLM Model Routing to Keep Inference Costs Predictable, accessed 2026-08-16. Check the provider's pricing page for current numbers.

#What to log

  • One row per attempt, not per run, so a fallback or retry is visible and not hidden.
  • Columns: run id, account id, task, model, input tokens, output tokens, cached tokens if the provider reports them, computed cost, timestamp.
  • Store the rate you used at the time, because prices change and old rows should stay true.
  • Total by run id to get cost per job, then look at the most expensive runs, not the average.

Cached input is priced separately by some providers, and audio or batch modes can differ, so keep the rate in a table, not scattered through the code.

Sources

  1. Google, Gemini API Pricing (ai.google.dev)Accessed 2026-08-16. Gemini 2.5 Flash and Flash-Lite paid tier rates per 1M tokens.

Read the full write-up

More questions

What is an LLM gateway, and do I need one?

An LLM gateway is a single layer in your own stack that every model call passes through. Call sites name a task, such as classify or summarise,...

Read the answer

How do I stop an LLM agent from running up costs?

Put hard limits around every run, not just around the model. Cap the number of steps, set max output tokens on every call, give each run a dollar...

Read the answer

Have a question that is not answered here?

Ask me directly