LLM API Cost Calculation and Model Selection: A Practical Guide
Choosing an LLM API by lowest per-token price often leads to unexpectedly high bills. This guide explains how input, cached input, and output tokens are priced, how to build a per-request cost model, and how to cut costs through context design, prompt prefix stability, output constraints, and task-based model tiering. It also covers hidden total cost of ownership factors and a five-step selection process based on real traffic testing.
1. Why the Lowest Unit Price Is Rarely the Lowest Bill
Once generative AI applications move into production, the central question in model selection shifts from “does it work” to “what does each unit of quality cost.” Many teams compare a single number during initial integration: the input price per million tokens. Yet the actual bill often differs from expectations by several multiples, and the reason is simple — billing is never based on a single dimension.
Mainstream LLM APIs typically split tokens into three separately priced categories: regular input, cached input, and output. Prices usually form a tiered structure, with cached input the cheapest and output the most expensive. More importantly, output unit price is often several times the input unit price, with a common industry range of 3x to 6x. A model that looks cheap can therefore see its total cost overtake competitors quickly if it tends to produce long outputs.
So the first step in selection is not reading the price list, but building your own cost model:
Cost per request =input tokens × input unit price+ cached input tokens × cached input unit price+ output tokens × output unit price
Applying this formula to your business yields numbers you can actually decide with, such as cost per thousand requests or cost per user per day.
2. What the Three Token Types Mean and Where to Optimize
1. Regular Input: Tied to Context Design
Input cost depends on how much content you put into the context. System prompts, tool definitions, retrieved document fragments, and multi-turn conversation history all add up. The most common waste in practice is “stuffing everything in” — placing an entire knowledge base or full history into the context. A safer approach is to cap the number of retrieved items, summarize and compress history, and manage stable system prompts separately from variable user input.
2. Cached Input: A Structural Discount from Stability
When the request prefix stays identical, the platform can reuse already-computed intermediate results, and these tokens are usually billed at a small fraction of the input unit price, commonly around one tenth. This rule has direct implications for architecture: put unchanging content at the very front of the prompt and changing content at the end.
[Fixed] system role + output format constraints + tool declarations + domain knowledge[Variable] current user question + dynamic retrieval results
Once the prefix is disturbed, the cache cannot be hit and cost rises silently. Prompt templates should therefore be version controlled, and any change should be assessed for the cost fluctuation caused by cache invalidation.
3. Output: The Cost Amplifier
Output tokens carry the highest unit price, and their length is determined by model generation behavior, making them the least controllable. Practical ways to converge them include: explicitly constraining output structure (fixed fields, limited item counts), asking for the conclusion before the supporting evidence, splitting long-text tasks into segmented generation, and using a smaller model tier for non-critical scenarios. Engineering teams should also set an output length cap to avoid abnormally long responses.
3. Scenario Tiering: Aligning Model Tiers with Task Value
Price gradients usually correspond to capability gradients. The rational approach is to tier by task value rather than using one tier across the entire product.
| Task tier | Typical tasks | Selection approach |
|---|---|---|
| High-value complex tasks | Complex reasoning, long tool-call chains, code refactoring | Strongest tier, tolerate higher unit price |
| Routine production tasks | Summarization, classification, structured extraction, Q&A | Middle tier, balance capability and cost |
| High-volume lightweight tasks | Tagging, format conversion, intent recognition | Lightest tier, cost first |
An often overlooked fact is that the lightest tier, paired with clear instructions and a few examples, is often good enough for tasks like structured extraction and classification. Moving this traffic down from higher tiers is usually the fastest win in cost optimization.
4. Total Cost of Ownership: Four Hidden Expenses Beyond Unit Price
- Retry and failure cost: timeouts, rate limiting, and content blocking all trigger repeated billing, so look at effective success rate rather than the listed price.
- Migration and adaptation cost: platforms differ in API protocols, structured output methods, and tool-calling conventions; an internal gateway abstraction layer can significantly reduce the cost of switching.
- Observability cost: without token metering tagged by business dimension, you cannot locate the source of cost anomalies. It is advisable to record the three token types (input, cached input, output) and latency uniformly at the gateway.
- Governance cost: quota allocation, rate-limiting policies, key management, and auditing are all long-term investments.
5. A Selection Process You Can Actually Run
- Build an evaluation set: sample from real traffic, covering long-tail and edge cases, and avoid relying only on ideal examples.
- Run dual-track evaluation: first compare quality offline, then validate latency and stability with a small traffic canary.
- Load-test cost: replay real input and output length distributions to compute cost per thousand requests, instead of estimating from averages.
- Define routing policies: split traffic dynamically by task complexity and budget, and keep a fallback path.
- Review periodically: both prices and model capabilities change, so put cost metrics on a regular dashboard and recalibrate quarterly.
6. Practical Notes for Baidu AI Cloud
When building such applications on Baidu AI Cloud, the same methodology applies: first build the engineering foundation with general-purpose capabilities — for example, use object storage to keep evaluation sets and prompt versions, use a message queue to smooth out rate limiting by absorbing peaks, use a container platform to host the model gateway and routing logic, and use logging and monitoring with alerting to build a token-level cost dashboard. On the model side, integrate through a unified abstraction layer so that switching tiers and running canary releases become configuration changes rather than code changes.
7. Conclusion
Price adjustments themselves are not frightening; what is frightening is relying on a single unit-price metric for selection. Break cost into three segments — input, cached input, and output; match model tiers to task value; replace estimation with real-traffic load testing; and keep calibrating with an observability system. This method holds under any pricing cycle and is the most reliable path to controlling long-term AI application cost.
