LLM API Cost Accounting: How to Track Three Types of Tokens
A practical guide to estimating large language model API costs by separating regular input, cached input, and output tokens. It explains the technical reasons behind their different prices, compares reusable and one-time processing workloads, provides a cost estimation formula and code example, and outlines engineering strategies for reducing spend.
1. Why Token Billing Requires Separate Cost Tracking
Most large language model APIs charge based on token usage. However, many developers still estimate costs using a simplified formula: total tokens multiplied by a single price. This approach can be seriously inaccurate in two common situations: when the same long document is processed repeatedly, and when every request includes a large amount of entirely new context.
The reason is that modern LLM services often divide usage into three billing categories, each with a different price and computational cost:
- Input tokens: Content submitted to the model, including system prompts, conversation history, and retrieved materials.
- Cached input tokens: Input tokens that belong to a repeated prefix and can be reused from a previous request. These are typically billed at a much lower rate than standard input tokens.
- Output tokens: Content generated by the model. These usually have the highest unit price.
A typical pricing relationship is that output tokens cost significantly more than regular input tokens, while cached input tokens cost far less than regular input tokens. The difference between the three rates can be an order of magnitude.
Because the pricing structure is not uniform, using a single average token price will almost always produce an inaccurate estimate of the actual bill.
2. The Technical Reasons Behind the Three Rates
Why output tokens cost the most. Autoregressive generation proceeds one token at a time. Each newly generated token requires a forward inference pass, so the computational cost accumulates linearly with the output length. Input tokens, by contrast, can be encoded in parallel during a forward pass, resulting in a lower cost per token. This is why output pricing is often several times higher than input pricing.
Why cached input tokens are cheaper. When multiple requests share the same prefix—for example, a fixed system prompt or the same reference document—the service can reuse intermediate states that were computed previously, such as the KV cache. This avoids encoding the shared prefix again. The saved compute is reflected in a lower cached-input price.
This also explains why placing stable content at the beginning of the prompt and variable content at the end can significantly reduce costs. Caching is generally possible only when the prefix is exactly the same.
3. Comparing the Cost Structure of Two Workloads
The difference becomes clear when comparing repeated processing of the same material with requests that contain new material every time.
Scenario A: Reusable-context workloads. Consider repeatedly asking questions about the same contract or codebase. The first request pays the regular input price for the full context. In later requests, the repeated prefix may hit the cache and be billed at the cached-input rate. The more requests are made, the greater the cost-spreading effect of caching.
Scenario B: One-time reading workloads. Consider sending a new article for summarization with every request. Since the input changes each time, it cannot benefit from the existing cache. Every request is billed at the full regular input rate, and costs increase linearly with the number of calls.
The conclusion is straightforward: the same total number of tokens can cost only one full-price processing cycle in a reusable-context workload, but require repeated full-price processing in a one-time workload. These two patterns should therefore be modeled separately when preparing a budget.
4. A Practical Cost Estimation Formula
Track the cost of each request as three separate components:
Per-request cost = regular input tokens × input price+ cached input tokens × cached price+ output tokens × output priceTotal batch cost = Σ(per-request cost)
Example pseudocode:
def estimate_cost(requests, price):# price: dictionary, with rates per million tokenstotal = 0.0for r in requests:total += r["input_tokens"] / 1_000_000 * price["input"]total += r["cached_tokens"] / 1_000_000 * price["cached"]total += r["output_tokens"] / 1_000_000 * price["output"]return total
The key point is that cached_tokens should not be an arbitrary assumption. It should be estimated from the actual reuse rate of the workload.
For reusable-context tasks, the model can assume one initial full-price request followed by a high cache-hit rate. For one-time workloads, set cached_tokens = 0.
5. Engineering Strategies for Reducing Costs
1. Put stable content at the beginning of the prompt. Place system prompts, tool definitions, and long-term reference materials at the front of the context so they are more likely to be cached. Put the user’s current question at the end.
2. Limit output length. Output tokens are usually the most expensive. Clear formatting requirements, maximum length limits, and structured responses—for example, requiring the model to return only specific JSON fields—can often reduce costs more effectively than optimizing input tokens.
3. Trim context as needed. Do not insert an entire document into every request without evaluating whether it is necessary. Use retrieval to include only the passages relevant to the current question. This reduces input costs and can also improve response quality.
4. Use tiered model selection. Use lightweight capabilities for simple tasks and reserve more advanced models for complex tasks. Avoid using the most expensive model for work that does not require it.
5. Monitor usage continuously. Use logging and monitoring systems to collect actual usage for the three token categories separately. Periodically calculate the marginal cost per business operation and use measured data—not intuition—to validate the cost model.
6. Practical Considerations for Production Integrations
Before deploying an LLM integration at scale, run a small batch of real requests and compare the actual proportions of the three token categories with the estimates in your model.
Many cost discrepancies come from overly optimistic assumptions about cache-hit rates or from underestimating how historical context grows in multi-turn conversations. If the integration uses a cloud platform, such as Baidu AI Cloud’s general AI inference and LLM services, also monitor concurrency limits and the hidden token usage caused by timeouts and retries. Failed requests that are retried may still incur token charges.
Treating token usage as “three separate accounts” rather than one blended average is the first step toward effective LLM cost control. By tracking regular input, cached input, and output separately—and modeling reusable and one-time workloads independently—you can create budgets that more closely match actual bills while making future optimization opportunities easier to identify.
