How to Calculate LLM API Costs Accurately After a Price Increase
Comparing per-token prices is misleading because a real API bill depends on three token types, workload patterns, and hidden costs. This article breaks down how standard input tokens, cached input tokens, and output tokens are priced, provides a formula and estimation method for typical scenarios, and outlines practical strategies such as prefix stabilization, output compression, tiered routing, and observability to keep monthly LLM spending under control.
1. Why Per-Unit Price Comparisons Lead to Wrong Estimates
When a large language model service announces a price increase, the most common reaction among developers is to build a side-by-side comparison of unit prices. The problem with this approach is that it reduces API usage to a single number, while an actual bill is determined by several dimensions at once.
A single request generates at least three billing items: standard input tokens, cached input tokens, and output tokens. Their unit prices are usually not on the same scale. Output is often significantly more expensive than standard input, while cached input is noticeably cheaper. As a result, looking only at the price per million input tokens will almost certainly over- or underestimate real spending.
More importantly, providers structure pricing for the same capability differently. Some price output at several times the input rate, some offer deeper cache discounts, and some tier pricing by context length. Comparing unit prices without considering your workload profile often produces conclusions that do not transfer to your own use case.
2. How the Three Token Types Are Billed
Standard Input Tokens
These are prompt tokens that are not cached and must fully participate in inference. They include the system prompt, conversation history, retrieved documents, and the user’s current question. In long-context applications, this is the part that expands most easily.
Cached Input Tokens
When multiple requests share the same prefix content, such as a fixed system prompt, lengthy knowledge snippets, or code repository context, the server can reuse previously computed intermediate results and bill that portion at a discounted rate. Caching typically requires the prefix to match exactly and is subject to time-to-live and minimum-length constraints. Refer to the official documentation of the service you use for the exact rules.
Output Tokens
This is the content generated by the model. Its unit price is usually several times that of standard input, and the generation process cannot be cached or reused. This means output length has a far greater leverage effect on your bill than input.
The cost of a single call can be expressed with an abstract formula:
Cost = Lin * Pin + Lcache * Pcache + Lout * PoutWhere:Lin input tokens that miss the cacheLcache input tokens that hit the cacheLout output tokensPin/Pcache/Pout unit prices for the three types
3. Estimating Costs for Typical Scenarios
Assume a Q&A application has the following workload profile: a system prompt and knowledge base prefix of about 6,000 tokens, user questions and retrieved snippets of about 1,000 tokens, model answers of about 800 tokens, and 100,000 calls per day.
Step one is to assess cache feasibility. If the prefix is stable and calls are frequent, most of the 6,000 tokens can become cache hits. If the knowledge snippets differ on every request, caching is nearly useless and everything is billed as standard input.
Step two is to plug the numbers into the formula to get the cost per call, multiply by the call volume for the daily cost, and then extrapolate to a 30-day month.
Step three is a sensitivity analysis. Increase output length by 50% and drop the cache hit rate from 80% to 30%, then observe how much the total swings. Most teams find that output length and cache hit rate are the two main variables in the bill, while the ranking of input unit prices has a relatively limited impact.
Illustrative code (it only expresses the calculation logic and does not involve any specific API):
def estimate_cost(l_in, l_cache, l_out, p_in, p_cache, p_out, calls=1, days=1):per_call = l_in * p_in + l_cache * p_cache + l_out * p_outreturn per_call * calls * days
4. Hidden Costs That Are Easy to Overlook
- Failed retries: retries triggered by timeouts and rate limits bill the input portion again.
- Context bloat: in multi-turn conversations, history is repeatedly counted as input if it is not trimmed.
- Uncontrolled output: without a maximum generation length limit, abnormal output can significantly inflate the bill.
- Different tokenization rules: providers tokenize differently, so the same text can be counted as a different number of tokens.
- Cache misses: even a one-character difference in the prefix can make the entire prefix unusable.
5. General Cost Optimization Strategies
- Stabilize the prefix and isolate variables. Put the fixed system prompt and instructions at the very front, and move timestamps, random identifiers, and user-specific content to the end to improve cache reuse.
- Compress output. Reduce redundant generation through explicit format constraints, length limits, and structured output requirements. This is the most direct optimization gain.
- Tiered routing. Classify requests by complexity, send simple tasks to lower-cost tiers, and escalate only complex reasoning to higher-capability tiers, avoiding overkill.
- Context governance. Summarize or apply sliding-window trimming to conversation history, and rerank and truncate retrieval results to control input size.
- Observability first. Add logging and monitoring with alerts, track token consumption by business dimension, and set budget thresholds and anomaly alerts so cost becomes visible in real time instead of only at month end.
- Capacity and elasticity. Use container platforms and message queues to smooth out traffic spikes, and move retry and queuing logic upstream to reduce wasteful duplicate calls.
6. Model Selection: From a Price Table to a Workload Profile
In response to a price change, the rational move is not to hunt for the cheapest model, but to first draw a workload profile for your business: average input length, output length distribution, cacheable prefix ratio, daily call volume, latency requirements, and task complexity distribution. Once the profile is clear, plug the candidate tiers into the formula above one by one and compare total monthly cost and task success rate rather than unit price rankings.
In practice with large model services on Baidu AI Cloud, the same three-step approach is recommended: break down the scenario, calculate the full cost, and monitor continuously. First clarify the input and output structure, then price the three token types separately, and finally use monitoring data to adjust the budget and routing strategy in reverse. This way, even if upstream prices change, you can quickly assess the impact and adjust the architecture instead of passively accepting the bill.
