LLM API Cost Estimation and Model Selection: A Practical Guide
A practical guide to estimating large language model API costs beyond per-million-token pricing. Learn how to build a cost model from request volume and token distribution, profile four common workload types, evaluate performance across measurable dimensions, apply five engineering cost-optimization techniques, and follow a staged rollout plan with a risk checklist.
1. Why “Price per Million Tokens” Is Not Enough
When integrating LLM capabilities into a business system, the first thing a team usually sees is a price line: so many dollars per million input tokens, so many per million output tokens. Take a flagship model’s public pricing as an example: $10 per million input tokens and $50 per million output tokens, while the previous generation’s main model was priced at roughly two-fifths of that, making the flagship about 2.5 times more expensive overall.
That number alone tells you nothing. What actually determines the bill is the product of three variables: request volume, the input/output token distribution of each request, and whether mechanisms such as caching and batching are being hit. A system doing long-document summarization with 100,000 calls per day and a code-completion system with 10 million calls per day have completely different cost structures even on the same model. So the first step in model selection is not comparing unit prices, but building your own cost model.
2. Converting Unit Price into Cost per Request
Let the input price be p_in (per million tokens), the output price p_out, the number of input tokens per request L_in, and the number of output tokens L_out. The cost per request is:
cost_per_call = (L_in / 1e6) * p_in + (L_out / 1e6) * p_out
Multiply by the call volume N and an overhead factor k to get the monthly cost (k covers retries, timeout replays, canary dual-runs, and is typically 1.1–1.3 in practice):
monthly = cost_per_call * N * k
One key takeaway: when the output price is 5 times the input price, output length has a far greater marginal impact on the bill than input. Cutting L_out from 800 to 400 usually saves more than cutting L_in from 8000 to 4000. This is why “making the model say less” is usually more cost-effective than “giving the model less context.”
3. Cost Profiles of Four Typical Workloads
- Long-context understanding (document review, contract comparison, log root-cause analysis):
L_incan reach tens of thousands whileL_outis only a few hundred. Cost is almost entirely driven by the input side, so the focus is retrieval-based context trimming, hierarchical calls for segmented summarization, and input cache reuse. - Generation-intensive (marketing copy, report writing, code generation):
L_outoften exceeds 1000, and the output side dominates the bill. The focus is structured output constraints, segmented generation with incremental validation, and avoiding “generate something too long and then rewrite the whole thing.” - High-concurrency short interactions (intelligent customer service, intent recognition): few tokens per call but a huge
N, so unit-price differences are amplified by volume. Here the previous generation’s 2.5x price gap translates directly into 2.5x monthly spend, making this the most selection-sensitive scenario. - Offline batch processing (data labeling, bulk cleaning): latency-insensitive, so an asynchronous batch channel can be used, usually in exchange for a better unit cost. This is the first place to look for cost optimization.
4. Performance: Don’t Just Look at Benchmark Scores
To decide whether a model is worth a premium, build a baseline across four measurable dimensions:
- Instruction-following stability: repeat the same prompt 20 times and check whether the format compliance rate stays stable. Every 1% drop in format compliance raises downstream parsing and retry costs.
- Effective long-context utilization: place key information at the beginning, middle, and end of a very long context, observe how answer accuracy decays, and gauge the gap between the “nominal context length” and the “usable context length.”
- Inference latency distribution: focus on P95/P99 rather than the average. End-to-end latency = queueing + time to first token + generation time, and longer outputs mean higher latency.
- Cost per task: measure by “completing one business task” rather than by token. If a stronger model compresses three rounds of interaction into one, its 2.5x unit price may be offset by a 60% drop in call volume.
A sketch of the evaluation loop:
def evaluate(candidates, dataset, budget):report = {}for name, client in candidates.items():total_cost, passed, latencies = 0.0, 0, []for case in dataset:resp, cost, dt = client.run(case.prompt, budget=budget)total_cost += costpassed += int(resp.format_ok and resp.answer_ok)latencies.append(dt)report[name] = {"accuracy": passed / len(dataset),"cost_per_task": total_cost / len(dataset),"p95_latency": sorted(latencies)[int(len(latencies) * 0.95)],}return report
5. Five Engineering Techniques for Cost Optimization
- Prefix caching: put stable system prompts, tool descriptions, and domain knowledge at the very front of the request and keep them byte-for-byte identical; on a cache hit, input-side billing drops significantly. Do not write timestamps or random IDs into the prefix.
- Semantic caching: build a vector index for frequent similar questions and return the historical answer directly when the similarity is above the threshold. Suited to customer service and FAQ workloads.
- Tiered model routing: route simple steps such as intent classification and format validation to a small model, and escalate to a large model only for complex reasoning. This can bring overall cost down to a fraction of using a single large model.
- Output constraints: use explicit schema definitions to limit output length and structure, reducing wasted tokens and retries caused by parsing failures.
- Observability: log input/output tokens, cache hit rate, and retry counts for every call, and configure monitoring alerts and budget thresholds so cost governance has data to rely on.
6. Rollout Plan and Risk Checklist
Proceed in three steps: offline evaluation → small-traffic canary → full cutover. First, measure accuracy and cost per task for each candidate on a fixed dataset; then validate behavior under the real distribution with 5%–10% of traffic; finally switch over completely. Keep a rollback switch throughout to avoid lock-in to a single vendor.
Risks to confirm in advance include: whether unit prices and billing definitions match the official documentation and are reviewed periodically; whether context trimming drops critical constraints; the data-isolation and compliance requirements of caching mechanisms; and quota and rate-limiting policies under high concurrency. If you use Baidu AI Cloud products, you can build the evaluation and governance system above on top of its general capabilities such as model services, object storage, message queues, logging, and monitoring alerts, so that cost, performance, and compliance are all measurable and auditable.
