Large Language Model API Pricing Explained and Cost Optimization Practices
This article breaks down how large language model API billing actually works and why the lowest published per-token price does not always produce the lowest bill. It abstracts mainstream pricing into three models—fixed per-token, tiered by request context length, and cache-enhanced—and compares them on the same long-context workload. It also provides a reusable cost estimation script, an engineering optimization checklist, and a model selection checklist for balancing quality, latency, and cost.
1. Background: Why the Lowest Unit Price Is Not the Lowest Bill
When teams move a workload from prototype to production, they often run into a counterintuitive result: a model whose published price per million tokens is clearly lower still ends up with a higher monthly bill than expected. The reason is straightforward—the actual API cost is not a function of unit price, but a function of the combination of billing dimensions.
At least five dimensions affect the final bill:
- Input/output price gap: Most services price output tokens significantly higher than input tokens, so long-form generation workloads are dominated by the output side of the bill.
- Tiered pricing (based on per-request context length): The larger the input size of a single request, the higher the price tier it falls into.
- Caching: This includes two billing items, cache writes and cache hits, with the hit portion usually settled at a lower price.
- Billing granularity and rounding rules: Whether billing accumulates per token or is bundled per request, the number of long-tail small requests can significantly amplify the error.
- Failure and retry costs: Retries caused by timeouts, rate limiting, or content filtering often result in duplicate billing.
So evaluating cost requires returning to a unified measurement standard: given a set of real business workloads, calculate the total cost, rather than comparing numbers on a price sheet.
2. Abstracting the Three Mainstream Billing Models
Setting aside specific vendors, the billing methods on the market can be abstracted into three categories.
2.1 Fixed Unit Price Model
Input and output each have a single price, independent of request length. The model can be written as:
cost = input_tokens / 1e6 * P_in + output_tokens / 1e6 * P_out
The advantage is predictable cost that is easy to budget for; the downside is that it is unfriendly to short requests and offers no scale incentive for long contexts.
2.2 Tiered Pricing Model
The unit price varies with the input token range of a single request, with common boundaries such as 32K, 128K, and 252K. The calculation logic is to first assign the request to a tier, then apply that tier’s unit price:
def tiered_cost(input_tokens, output_tokens, tiers):# tiers: [(upper, p_in, p_out), ...]for upper, p_in, p_out in tiers:if input_tokens <= upper:return input_tokens / 1e6 * p_in + output_tokens / 1e6 * p_outreturn None # exceeds the highest tier
There is an easily overlooked engineering trap here: the tier is determined by the single request, not by the full-day cumulative total. Splitting a 200K context into 10 requests of 20K each may drop the whole workload into a lower tier and significantly reduce cost—but at the expense of multi-turn context continuity, which the business side must weigh.
2.3 Cache-Enhanced Model
Caching is introduced on top of the fixed unit price:
cost = (uncached_in * P_in)+ (cached_write * P_write)+ (cached_hit * P_hit) # P_hit is usually far lower than P_in+ (output * P_out)
The benefit of caching depends heavily on prefix stability: if the system prompt, tool definitions, or knowledge base snippets change on every call, the hit rate approaches zero and the writes actually add overhead.
3. Horizontal Comparison Under a Unified Scenario
Set a typical long-context workload as the comparison baseline:
| Billing item | Scale |
|---|---|
| Uncached input | 509.8K |
| Output | 8.125K |
| Cache write | 467.3K |
Option A: Tiered pricing (input 7 CNY/M, output 28 CNY/M, falls into the highest tier)
Input: 509.8K × 7 / 1e6 ≈ 3.5686 CNYOutput: 8.125K × 28 / 1e6 ≈ 0.2275 CNYCache write: merged into input, not billed separatelyTotal ≈ 3.80 CNY
Option B: Fixed unit price (assume input 4 CNY/M, output 16 CNY/M, cache hit at 20% of the input price)
Uncached input: 509.8K × 4 / 1e6 ≈ 2.0392 CNYCache write: 467.3K × 4 / 1e6 ≈ 1.8692 CNYCache hit: 0 (no hit in this case)Output: 8.125K × 16 / 1e6 ≈ 0.1300 CNYTotal ≈ 4.04 CNY
Option C: High cache hit rate (80% hit rate, hit price at 20% of the input price)
Uncached input: 101.96K × 4 / 1e6 ≈ 0.4078 CNYCache write: 467.3K × 4 / 1e6 ≈ 1.8692 CNYCache hit: 374.5K × 0.8 / 1e6 ≈ 0.1198 CNYOutput: 8.125K × 16 / 1e6 ≈ 0.1300 CNYTotal ≈ 2.53 CNY
There are three conclusions. First, in a single long-context request without caching, the tier assignment effect of tiered pricing may actually be more expensive. Second, a cache write is a one-time investment; it only pays off after amortization when the same prefix is reused enough times. Third, although the output share is small (less than 7% in this case), it quickly becomes the dominant item in scenarios with large generation lengths, so you cannot focus only on the input price.
4. A Reusable Cost Estimation Method
It is recommended to turn estimation into an executable script and include it in CI, running it whenever any prompt or model version changes:
def estimate(load, pricing, cache_hit_rate=0.0):in_t, out_t = load["input"], load["output"]hit = in_t * cache_hit_ratemiss = in_t - hittotal = (miss * pricing["in"]+ hit * pricing["hit"]+ load["cache_write"] * pricing["write"]+ out_t * pricing["out"]) / 1e6return round(total, 4)
A few things to note in practice: token counts should be based on the usage field returned by the service, not on local tokenizer estimates; different models use different tokenizers, and the token count for the same text has systematic deviations.
5. Engineering Cost Optimization Checklist
- Stable prefix: Placing the system prompt, tool schema, and fixed knowledge snippets at the front in a fixed order is the most effective way to improve the cache hit rate.
- Context trimming: For retrieval-augmented scenarios, apply reranking and truncation instead of stuffing entire documents into the context; context length is positively correlated with both cost and latency.
- Output constraints: Use structured output and explicit length limits to reduce redundant generation; the output-side unit price is usually several times the input price.
- Request merging and batching: Merge requests when business latency allows, reducing duplicate prefixes and scheduling overhead.
- Tiered routing: Send simple tasks to lightweight models and complex reasoning to high-capability models, using quality thresholds rather than manual intuition to decide the split.
- Observability: Build dashboards for token usage and cost by business line and by endpoint, and configure budget alerts and rate limiting to prevent abnormal loop calls from inflating the bill.
- Failure handling: Apply exponential backoff for timeouts and rate limits rather than immediate retries, to prevent duplicate billing.
6. Model Selection Checklist
- Measure the real workload’s input/output ratio and context length distribution, rather than using averages.
- Assess prefix reusability and estimate the cache hit rate and amortization period.
- Run the same workload through candidate options with a unified script, comparing total cost rather than unit price.
- Put quality evaluation and cost in the same table for a Pareto selection, avoiding single-objective optimization.
- Keep a switchable abstraction layer so that model replacement does not affect business code, reducing long-term lock-in risk.
If an enterprise wants to complete the load testing and dashboard work described above within its own data and compliance boundaries, it can use general cloud product capabilities from Baidu AI Cloud, such as container platforms, log services, and monitoring and alerting, to build a unified invocation gateway and cost observability system. This consolidates billing standards, budget policies, and routing rules into a single place for management, achieving a verifiable balance among quality, latency, and cost.
