A Practical Guide to LLM API Cost Estimation and Model Selection
This guide explains how to properly estimate and compare LLM API costs. Instead of relying on a single "blended price" ranking, it breaks down pricing into three token categories (cache-hit input, cache-miss input, and output), provides reproducible formulas and Python code, shows how to derive usage ratios from production logs, and covers sensitivity analysis and engineering practices for ongoing cost governance.
A Practical Guide to LLM API Cost Estimation and Model Selection
1. Why a Simple “Unit Price Ranking” Is Misleading
When selecting a model service, many teams start by collecting each model’s input price, output price, or cache-read price, then compute a “blended unit price” under some assumed ratio and rank the results. This approach has some value, but it can easily mislead. The reason is that LLM call costs are not a single price — they are determined jointly by three types of tokens: cache-miss input, cache-hit input, and output. Token structures vary enormously across workloads, so the same set of prices can yield completely opposite conclusions under different business scenarios.
For example, long-document Q&A, code completion, customer-service summarization, batch information extraction, and multi-turn dialogue all differ dramatically in input length, cache reuse rate, and output length. A generation-heavy task with a high output ratio is more sensitive to the output unit price; a batch task with many repeated prompts may benefit significantly from cache hits. If you only compare a “blended unit price” without a clearly stated basis, readers cannot tell whether it applies to their own workloads.
A more professional approach is: first standardize the pricing basis, then collect ratios from real business logs, and finally compute per-unit business cost with a reproducible formula. The original idea of “use the read price for cache hits, the input price for cache misses, and the output price for outputs” essentially separates the three token types for metering. That idea is worth keeping, but it needs to be completed with formulas, data collection, sensitivity analysis, and engineering governance.
2. Breaking Down the Three Pricing Categories
In a pricing system that supports context caching, a single request can typically be split into three token types:
- Cache-hit input tokens: the portion of the request that matches an existing cached prefix, usually billed at the cache-read unit price. Whether caching is supported, how hits occur, cache lifecycle, and billing rules should be verified against the service terms and your actual bills.
- Cache-miss input tokens: the input portion that does not hit the cache, billed at the regular input unit price. This typically includes the system prompt, user question, context materials, and so on.
- Output tokens: the content generated by the model, billed at the output unit price. The output price is usually higher than the input price, but the gap varies widely across services and should not be generalized.
Let the total input tokens of a request be (I), of which the cache-hit portion is (I_h) and the miss portion is (I_m), with (I_m = I - I_h); let the output tokens be (O). Let the cache-read unit price be (p_r), the input price (p_i), and the output price (p_o), all expressed as “price per million tokens.” The cost of a single request is:
[
C = \frac{I_h}{10^6}p_r + \frac{I_m}{10^6}p_i + \frac{O}{10^6}p_o
]
Defining the cache-hit ratio (a = I_h / I), the miss ratio (b = 1-a), and the output-to-input ratio (r = O/I), we get:
[
C = \frac{I}{10^6}\left(a p_r + b p_i + r p_o\right)
]
The “blended unit price” must have an explicit basis. We recommend defining it as: total cost per million input tokens, including output cost:
[
P_{per_input} = a p_r + (1-a)p_i + r p_o
]
If the team cares more about “cost per million total tokens,” use:
[
P_{per_total} = \frac{C}{(I+O)/10^6}
]
The two bases must not be mixed. The former suits budget estimation by input volume; the latter suits comparing resource efficiency by total throughput. If an article or comparison table does not state its basis, the numbers are not comparable no matter how precise they look.
3. Where the Ratios Come From: Use Logs, Not Guesswork
The key variables in cost estimation are not the prices but the business ratios. We recommend collecting the following fields from call logs: scene identifier, request timestamp, input token count, cache-hit token count, cache-miss token count, output token count, success flag, retry count, and pricing version. Then aggregate by business line, scene, time period, and tenant.
Do not rely on averages alone when aggregating. Token distributions typically have long tails, and a small number of very long requests can dominate total cost. Report the mean, P50, P90, P95, and share of total volume, and compute “effective cost” metrics such as cost per successful task, cost per thousand requests, or cost per ten thousand generated words. Pseudo-SQL example:
SELECTscene,SUM(cached_input_tokens) / NULLIF(SUM(input_tokens), 0) AS cache_hit_ratio,SUM(output_tokens) / NULLIF(SUM(input_tokens), 0) AS output_input_ratio,SUM(cached_input_tokens) AS cached_tokens,SUM(input_tokens - cached_input_tokens) AS uncached_tokens,SUM(output_tokens) AS output_tokens,COUNT(*) AS request_countFROM llm_call_logWHERE dt BETWEEN :start_date AND :end_dateGROUP BY scene;
Keep metering consistent during collection: are cache-hit tokens already included in the input token count? Do output tokens include the reasoning process? Are retried requests double-counted? Are failed requests billed? These details directly affect the estimate. We recommend keeping both “raw metering fields” and “normalized fields” in the logs so that results remain traceable when the basis changes later.
4. A Reproducible Cost Calculation Example
Below is a vendor-agnostic calculation example. The price parameters are for formula demonstration only and do not represent any real quote; replace them with confirmed pricing data in practice.
from dataclasses import dataclass@dataclassclass Price:read_per_million: float # cache-read unit priceinput_per_million: float # cache-miss input unit priceoutput_per_million: float # output unit pricedef request_cost(input_tokens, cached_tokens, output_tokens, price: Price):if cached_tokens > input_tokens:raise ValueError("cached_tokens must not exceed input_tokens")uncached_tokens = input_tokens - cached_tokensreturn (cached_tokens / 1_000_000 * price.read_per_million+ uncached_tokens / 1_000_000 * price.input_per_million+ output_tokens / 1_000_000 * price.output_per_million)def aggregate_cost(rows, price: Price):total_cost = 0.0total_input = 0total_output = 0total_cached = 0for r in rows:total_cost += request_cost(r["input_tokens"], r["cached_tokens"], r["output_tokens"], price)total_input += r["input_tokens"]total_output += r["output_tokens"]total_cached += r["cached_tokens"]return {"total_cost": total_cost,"cost_per_million_input": total_cost / (total_input / 1_000_000) if total_input else 0,"cost_per_million_total": total_cost / ((total_input + total_output) / 1_000_000) if (total_input + total_output) else 0,"cache_hit_ratio": total_cached / total_input if total_input else 0,"output_input_ratio": total_output / total_input if total_input else 0,}
The value of this function is auditability: every request’s cost can be replayed, the aggregation basis is explicit, and pricing versions can be swapped. During selection, you can feed the same batch of business logs into each candidate service to obtain “cost under the same workload structure,” rather than directly comparing blended unit prices computed under different assumed ratios.
5. Sensitivity Analysis Matters More Than a Single Ranking
Because the cache-hit ratio and output ratio fluctuate, we recommend a two-dimensional sensitivity analysis: cache-hit ratio on one axis, output-to-input ratio on the other, observing how blended cost changes. If a candidate service is expensive at low hit ratios but clearly advantageous at high ones, you must evaluate whether your business can stably achieve a high hit ratio. Cache hits typically depend on prompt-prefix stability, session reuse strategy, and context organization — you cannot assume a given ratio will be reached naturally.
A selection matrix can cover four dimensions: cost, quality, latency, and stability. Use the formulas above for cost; use business evaluation sets and manual spot checks for quality; look at P95 rather than the mean for latency; and examine error rate, timeout rate, and rate-limiting behavior for stability. Enterprise users should also consider compliance, data management, billing explainability, and budget alerting. The same principle applies when selecting model services on platforms such as Baidu AI Cloud: standardize the metering basis first, then compare using real business logs, rather than relying on the unit prices shown on marketing pages.
6. Engineering Governance: Turning Cost Optimization into Design
Cost estimation is not a finance exercise — it is an engineering exercise. First, design cache-friendly prompt structures: place stable system prompts, fixed rules, and shared knowledge at the prefix, and minimize unnecessary variation. Second, control output length through structured output constraints, maximum output token limits, and summarization or segmented generation. Third, build tiered routing: send simple tasks to low-cost configurations and complex tasks to high-quality configurations, routing by task type, input length, and historical success rate. Fourth, monitor cache-hit ratio, output-to-input ratio, cost per successful task, retry rate, and budget consumption, with per-scene alerts. Fifth, retain pricing versions and price-change records so that bill fluctuations can be attributed.
7. Conclusion
“Computing a blended unit price from ratios” is a valid starting point for evaluating model service costs, but three things must be added: an explicit blended-price basis, ratios collected from real logs, and sensitivity analysis on the key ratios. Developers should meter cache-hit, cache-miss, and output tokens separately, then close the loop with reproducible code and continuous monitoring. Only by turning cost estimation from a static ranking table into an explainable, replayable, and governable engineering system can selection decisions be truly reliable.
