Understanding LLM API Pricing and Cost Optimization: A Practical Guide
This article breaks down how large language model API billing works and shows how to control costs in production. It explains token-based pricing, the price gap between input and output tokens, three-state context caching, and high-speed tier premiums. It also provides a reusable cost estimation function, engineering practices for improving cache hit rates, a model routing framework by task complexity, common pitfalls, and a deployment checklist. Readers will learn to model text length, reuse structure, capability tier, and latency requirements together to make explainable and reproducible trade-offs between quality and cost.
1. Why Token-Based Billing Needs a Second Look
When enterprise AI applications move into production, model invocation costs often shift from a negligible edge expense to a core variable that determines whether a project is viable. Many teams focus only on output quality during the prototype stage, then discover at scale that the billing curve rises far more steeply than business volume. Controlling cost requires understanding the underlying structure of the billing mechanism, not simply comparing unit prices.
LLM billing is not settled per request; it is settled by the number of tokens the model actually processes. A token is the smallest processing unit after text is split. A Chinese character, a fragment of an English word, or a punctuation mark may each correspond to one or more tokens. Cost is therefore strongly correlated with actual text length, not with the number of business records.
More importantly, the cost structure on the input side differs completely from that on the output side. Input tokens correspond to the model’s understanding and encoding of context, while output tokens correspond to the token-by-token generation process, which carries significantly higher computational overhead. As a result, the output unit price is typically several times the input unit price. Any cost optimization plan that focuses only on the input side will miss the main savings opportunity.
2. Breaking Down the Cost Model Across Four Dimensions
A mature cost model includes at least four dimensions, none of which can be omitted.
2.1 Base Input Cost
The base input price determines the marginal cost of how much context you feed the model. At the industry median level, input pricing for mid-tier models generally falls in the range of a dozen or so yuan per million tokens, while flagship models are commonly around twenty yuan. Note that input cost is easily underestimated, because in scenarios such as retrieval augmentation, multi-turn dialogue, and long-document summarization, input tokens are often more than ten times the output tokens.
2.2 Output Cost
The output price is usually four to six times the input price. For common tiers, an input price of 13 yuan with an output price of 68 yuan, or an input price of 20 yuan with an output price of 100 yuan, both fit this ratio. Therefore, in architecture design, any technique that compresses output length—structured output, field trimming, segmented generation—delivers proportional returns.
2.3 Context Caching Cost
Context caching is the most important cost optimization mechanism in recent years. It reduces “repeatedly passed identical prefixes” from full-price billing to discounted billing. A typical implementation involves three price points:
- Cache hit: the cached prefix portion is billed at a very low price, commonly around one-tenth of the input price;
- Cache write (short-lived): billed close to the original input price, suitable for minute-level reuse;
- Cache write (long-lived): roughly twice the short-lived rate, suitable for hour-level reuse.
There is an easily overlooked judgment here: cache writing itself has a cost. If a prefix is reused only once, enabling caching is actually more expensive. The economics of caching hold only when reuse is frequent enough—typically at least two to three reuses are needed to amortize the write overhead.
2.4 High-Speed Tier Premium
To meet low-latency business needs, providers usually offer a high-speed version whose pricing is twice that of the standard version. This premium does not buy performance linearly; it buys certainty in response time. Whether it is worth paying depends on how sensitive the business is to time-to-first-token and end-to-end latency.
3. Quantitative Estimation: A Reusable Method
The following is an illustrative cost estimation logic that helps teams quickly compare different combinations during selection:
def estimate_cost(input_tokens, output_tokens,in_price, out_price,cache_hit_ratio=0.0, cache_write_tokens=0,cache_hit_price=None, cache_write_price=None):hit = input_tokens * cache_hit_ratiofresh = input_tokens - hitcost = fresh * in_price + output_tokens * out_pricecost += cache_write_tokens * (cache_write_price or in_price)cost += hit * (cache_hit_price or in_price)return cost / 1_000_000 # unit: yuan
Take “100,000 input tokens, 20,000 output tokens, 70% cache hit ratio” as an example. With a tier of 13 yuan input, 68 yuan output, and 1.3 yuan cache hit, the hit portion saves about 90% of input cost; the same workload on the previous-generation tier of 20 yuan input and 100 yuan output would cost about 50% more in total. This explains a common phenomenon: even if a new-generation model’s unit price does not look low, cache discounts and an overall price reduction can make the actual bill better.
4. Engineering Cache Hit Rate Optimization
Whether caching takes effect depends on whether the prefix is byte-for-byte identical. In practice, the causes of a collapsing hit rate are highly concentrated:
- Dynamic variables such as timestamps, random IDs, and user nicknames are concatenated at the very front of the system prompt;
- Prompt templates are adjusted frequently, changing the prefix fingerprint;
- Multiple tenants share one template but insert a tenant identifier, breaking the common prefix;
- Tool definitions and function schema ordering are unstable.
The corresponding refactoring principle is clear: put stable content first and volatile content last. The recommended layered structure is as follows:
[Stable layer] Role settings, output specifications, tool definitions, domain knowledge[Semi-stable layer] Session summaries, retrieved document fragments[Volatile layer] Current time, user input, temporary identifiers
As long as the stable layer remains byte-level consistent, caching can keep hitting. Engineering teams should also establish cache hit rate monitoring metrics and incorporate them into daily observability, rather than tracing back after the bill becomes abnormal.
5. A Model Tiering Framework for Selection
Another main line of cost optimization is tiered routing, using models of different capability levels to handle requests of different complexity:
- High-complexity tasks (complex reasoning, long-chain tool calls) go to the flagship tier;
- Medium tasks (summarization, classification, extraction) go to the standard tier;
- Low-complexity tasks (format conversion, keyword extraction) can use smaller models;
- Only latency-sensitive links with sufficient budget enable the high-speed tier.
In general practice on cloud platforms such as Baidu AI Cloud, this tiering is usually implemented together with logging services and monitoring alerts: first sample logs to label request difficulty, then gradually adjust routing ratios, using observable data to drive decisions and avoid tuning by intuition.
6. Common Pitfalls and Risk Notes
First, do not look only at the input unit price. The multiplier effect on the output side determines the real cost center in long-text generation scenarios. Second, do not enable caching unconditionally. In low-reuse scenarios, write fees will eat into the benefits. Third, do not put dynamic content first. This is the most common root cause of hit rate loss. Fourth, do not ignore context length expansion. Without summary compression, input tokens in multi-turn dialogue grow roughly quadratically with the number of turns. Fifth, do not treat price tiers as fixed. Billing strategies change with version iterations, so unit prices should be configurable in the architecture rather than hard-coded.
7. Deployment Checklist
- Have you modeled cost separately for the three states of input, output, and cache?
- Have you tracked the cache hit rate and set alert thresholds?
- Have you completed prompt layering so that the stable prefix meets the target proportion?
- Have you established model routing tiered by difficulty?
- Have you applied summarization and truncation strategies for long contexts?
- Have you made unit prices and routing ratios configurable to support gradual rollout and rollback?
In summary, controlling LLM invocation costs essentially means putting four variables—text length, reuse structure, capability tier, and latency requirements—into a unified model for reasoning. Only by understanding the causes of the input-output price gap, three-state cache pricing, and high-speed tier premiums can you make explainable and reproducible trade-offs between quality and cost.
