LLM API Cost Estimation and Model Selection: A Practical Guide
This guide explains why a low per-token price does not always produce a low bill, and how engineering teams can estimate and control large language model API costs. It breaks the cost model into three variables—input tokens, cached tokens, and output tokens—provides a unified cost formula with sample Python code, maps capability tiers to common use cases, and lists frequent mistakes along with a practical optimization checklist for building cost governance into the development workflow.
1. Background: Why a Low Unit Price Does Not Mean a Low Bill
As generative AI moves into production, model API costs have shifted from an experiment expense to a fixed line item in engineering budgets. Many teams still compare only the input price per million tokens, yet real bills often end up several times higher than expected.
The reason is straightforward: the cost of a single request is made up of three parts—input tokens, cached tokens, and output tokens—and their unit prices usually differ by an order of magnitude.
The source material shows that a general-purpose model family typically forms a capability gradient internally: a high-capability tier for complex reasoning and specialized tasks, a mid-tier that balances capability and cost, and a low tier for cost-sensitive, high-concurrency scenarios. After a price adjustment, the tier once treated as a cheap alternative no longer has a decisive advantage. The selection logic must therefore shift from “find the cheapest model” to “find the combination with the lowest total cost that still meets quality requirements.”
This article does not evaluate any specific vendor or product. Instead, it abstracts a general framework for cost estimation and model selection that applies to any LLM service and can be recalculated quickly when prices change.
2. Three Variables in the Cost Model: Input, Cache, and Output
2.1 Input Tokens: The Underestimated Fixed Overhead
Input tokens include the system prompt, conversation history, document chunks retrieved through RAG, and the user’s current question. In practice, long system prompts and replaying the full history on every request are the most common sources of waste. If each request carries several thousand tokens of context, input cost becomes the main expense even when the output is short.
2.2 Cached Tokens: The Overlooked Discount Lever
Most mainstream services offer context caching, which bills repeated prompt prefixes at a significant discount. The ratio given in the material is broadly applicable: a cache hit is usually priced at about one tenth of the normal input price. This means a stable system prompt, fixed tool descriptions, and repeated knowledge base chunks can all be turned into meaningful savings through caching.
One caveat: cache hits depend on prefix consistency. Inserting a timestamp, a random identifier, or any changing content at the front of the system prompt invalidates the cache for the entire prefix. Put volatile content at the end instead.
2.3 Output Tokens: The Real Amplifier of the Bill
A key pattern in the material is that output tokens for models in the same family cost roughly six times the normal input price. This multiplier is not an exception but an industry-wide pattern, rooted in the nature of autoregressive generation: the output stage cannot be parallelized, so compute per token is more expensive.
The practical conclusion is that output length carries far more weight in total cost than input length. A request that generates 2,000 output tokens can cost more than one that takes 20,000 input tokens and produces only 200 output tokens.
3. A Unified Formula and Sample Code
Let in be the number of input tokens, cache the number of cache-hit tokens, and out the number of output tokens, with unit prices p_in, p_cache, and p_out (per million tokens, in yuan or USD). The cost of a single request is:
cost = (in - cache) / 1e6 * p_in+ cache / 1e6 * p_cache+ out / 1e6 * p_out
Note that in includes the cached portion, so the normally billed input volume is in - cache.
A sample Python implementation that can be dropped into a budgeting script or a load-testing tool:
def estimate_cost(in_tokens, cache_tokens, out_tokens,p_in, p_cache, p_out):"""Estimate the cost of a single request using per-million-token prices"""billable_in = max(in_tokens - cache_tokens, 0)return (billable_in * p_in+ cache_tokens * p_cache+ out_tokens * p_out) / 1_000_000# Example: a long system prompt hits the cache, output is relatively longcost = estimate_cost(in_tokens=12000, cache_tokens=10000, out_tokens=1500,p_in=2.0, p_cache=0.2, p_out=12.0)print(f"Estimated cost per request: {cost:.5f}")
Plugging in the daily call volume N and average token counts gives a monthly budget:
monthly = cost_avg * N * 30
It is worth wiring this script into CI so that any prompt change or tier switch automatically reports the cost delta, avoiding the hidden risk of “change one line in the prompt, double the bill.”
4. Tiering: Mapping Capability Gradients to Scenarios
The three-tier structure in the material is representative of the industry and can be abstracted as follows:
| Tier | Typical positioning | Suitable scenarios | Cost profile |
|---|---|---|---|
| High-capability tier | Complex specialized tasks | Long-document reasoning, code refactoring, math and logic derivation | Highest unit price; call volume should be strictly controlled |
| Balanced tier | Compromise between capability and cost | Routine Q&A, structured extraction, medium-complexity writing | Best value range; a good default tier |
| Lightweight tier | Cost-sensitive and high concurrency | Classification, tagging, rewriting, routing decisions, batch summarization | Lowest unit price; suited to heavy traffic |
The practical recommendation is to build a routing layer: handle intent recognition and simple requests with the lightweight tier first, and escalate to the balanced or high-capability tier only when confidence is low or task complexity exceeds a threshold. Tiered invocation like this usually lowers average cost significantly without sacrificing quality where it matters.
5. Common Mistakes and an Optimization Checklist
Mistake 1: Looking only at the input price. Ignoring the sixfold output multiplier leads to budgets that are far too low.
Mistake 2: Putting volatile content at the very front of the prompt. This breaks prefix caching and voids the discount.
Mistake 3: Replaying the full conversation history. Use rolling summaries plus retention of key chunks instead.
Mistake 4: Using the high-capability tier for bulk simple tasks. Use the lightweight tier with rule-based validation instead.
Mistake 5: Lacking cost observability. Bring token usage, cache hit rate, and output length distribution into logging and alerting, and set budget threshold alerts.
The corresponding optimization actions:
- Compress the system prompt, keeping stable content first and volatile content last;
- Enable caching for high-frequency repeated prefixes and monitor the cache hit rate;
- Cap the maximum output length, and switch long-output tasks to segmented generation;
- Establish model routing and fallback policies that assign tiers by complexity;
- Use the unified formula for monthly budgeting, and re-run the estimate automatically whenever the prompt changes;
- For batch offline jobs, use asynchronous queues and off-peak scheduling, with object storage holding intermediate results.
6. Engineering Practice: Making Cost Governance a Process
Cost governance is not a one-off optimization but a continuous process with four stages. First, collection: log input, cached, and output token counts along with the tier on the call path. Second, accounting: convert to monetary amounts with the unified formula and aggregate by business dimension. Third, attribution: identify high-consumption scenarios and abnormally long outputs. Fourth, governance: apply prompt restructuring, caching policies, routing and fallback, and output constraints one by one.
In general practice on cloud platforms such as Baidu AI Cloud, these stages are typically carried by common capabilities like log services, monitoring and alerting, message queues, and object storage, so teams can build their own dashboards without depending on any single vendor’s proprietary interfaces.
7. Conclusion
A price adjustment changes the ranking but not the cost structure. What really determines the bill is three engineering variables: output length, cache hit rate, and tier selection. Master the unified formula and build tiered routing plus observability, and budgets stay under control through price swings—leaving you with the option that genuinely fits your workload.
