LLM API Selection and Cost Optimization: Don't Fixate on Per-Token Pricing
Comparing per-million-token prices alone leads to wrong conclusions when optimizing LLM API costs. This article explains how to build a per-call cost model, introduces a cost-per-quality metric, and covers five practical cost optimization strategies: tiered routing, context engineering, output control, batch processing, and quality guardrails.
1. A Low Unit Price Doesn’t Mean a Low Bill
When developers discuss LLM services, “expensive” is one of the most common complaints. But when optimizing LLM API costs, comparing only the per-million-token unit price can easily lead to the wrong conclusion. Your bill is determined by the number of calls, input and output lengths per call, the model tier, cache hit rates, and failed retries.
A common phenomenon is that unit prices drop while bills rise. As models become more capable, developers tend to stuff in longer contexts, enable reasoning modes, and request more complete outputs. The increase in total tokens consumed per call can offset the savings from lower unit prices. Therefore, in LLM API selection, you should first look at the total cost of completing a task, then the unit price.
API billing structures typically include the following components:
- Input tokens: billed based on the length of the prompt carried by the request.
- Output tokens: usually priced higher than input tokens and a major cost component.
- Cached tokens: repeated long prefixes that hit the cache may be billed at a lower rate. Rules vary significantly across providers.
- Model tiers: the price gap between lightweight, standard, and professional versions can be substantial.
Specific prices change with providers and over time. This article does not list specific prices; when selecting a model, refer to each provider’s official pricing page and record the date you checked it.
2. Building a Per-Call Cost Model
2.1 The Per-Call Cost Formula
Per-call cost can be estimated with the following formula:
Per-call cost = input tokens × input unit price+ output tokens × output unit price+ cached tokens × cache unit price
Retries and failed requests also incur charges. If a task requires an average of 1.2 calls, this overhead should be included in the calculation.
Take a retrieval-augmented generation (RAG) scenario as an example. Retrieved chunks total about 6,000 tokens, the system prompt about 1,500 tokens, and the user question about 100 tokens, for a combined input of roughly 7,600 tokens. The model output is about 800 tokens. Assume the output unit price is 3x the input unit price, and denote the input unit price as p:
- Input cost: 7600p
- Output cost: 800 × 3p = 2400p
- Output share: 2400 ÷ (7600 + 2400) ≈ 24%
If the output unit price is 4x the input price, the output cost is 3200p, or roughly 30% of the total. So with this set of parameters, output accounts for about 24%–30% of total cost, not more than 40%.
The output share is determined jointly by output length, the price ratio, and input length. With the input scale above and a 3x price ratio, output would need to reach about 1,700 tokens before its share hits 40%. Teams should compute this with their own real data instead of borrowing someone else’s ratios.
2.2 Task-Level Cost-Effectiveness Metrics
Per-call cost alone cannot reflect quality differences. Teams can introduce a “cost per unit of quality” metric. The code below implements two functions:
def estimate_cost(pricing, input_tokens, output_tokens, cached_tokens=0):"""Estimate the cost of a single call based on model pricing (in yuan).pricing: dict containing input_price, output_price, and cache_price, in yuan per token."""return (input_tokens * pricing["input_price"]+ output_tokens * pricing["output_price"]+ cached_tokens * pricing["cache_price"])def cost_per_quality(avg_cost_per_task, quality_score):"""avg_cost_per_task: average cost to complete one task (in yuan), including retries and failed calls.quality_score: average score on a fixed business evaluation set, ranging from 0 to 1."""if quality_score <= 0:return float("inf")return avg_cost_per_task / quality_score
The quality score methodology must be fixed. The sample size, scoring criteria, and version of the evaluation set must stay consistent across comparisons. If evaluation samples have leaked into prompts or training data, scores will be inflated and comparisons unreliable.
In certain scenarios, running the same task 10 times with a lightweight model—each time validated—may approach the quality of a single run with a flagship model. Whether this comparison holds depends on whether the lightweight model, plus retries and validation, meets business quality requirements. This needs to be verified on the evaluation set.
It is recommended to record the following fields for each task and aggregate them by task:
- Input tokens, output tokens, and cached tokens
- Retry count and tokens consumed by failed requests
- Reasoning tokens (for reasoning models)
- P99 latency
3. Five Cost Optimization Strategies
3.1 Tiered Routing
Route requests by difficulty: send simple tasks to lightweight models and complex tasks to flagship models. The flow is as follows:
User request → intent/difficulty classifier → simple task → lightweight model→ complex task → flagship model
Tasks like format conversion, information extraction, and simple Q&A usually don’t need a flagship model. The classifier itself also incurs costs, so choose a low-cost small model for it.
Whether tiered routing actually reduces your bill depends on your own request difficulty distribution. It’s recommended to first use a week of real traffic to measure the share of each task type, then validate the post-routing quality and cost through a canary experiment. Don’t assume a savings percentage before measuring.
The table below provides a comparison framework that teams can adjust to their own business:
| Task Type | Recommended Model Tier | Quality Guardrail | Cost Items to Monitor |
|---|---|---|---|
| Format conversion, field extraction | Lightweight | Rule-based validation, e.g., JSON parsing and field completeness | Input/output tokens, retries from failed validation |
| Simple Q&A, short summaries | Lightweight | Sampled manual review at a fixed ratio | Output tokens, manual review hours |
| Multi-step reasoning, code generation | Flagship | Unit tests or automated evaluation | Reasoning tokens, total per-task cost |
| Long document analysis | Standard or flagship | Key information coverage checks | Input tokens, cache hit rate |
3.2 Context Engineering: Control Length and Leverage Caching
- Streamline system prompts: regularly audit prompt length and remove redundant role definitions and repetitive examples.
- Leverage prefix caching: place stable content (system instructions, knowledge base skeleton) at the front of the prompt. Cache hit conditions and discount rates depend on provider rules; consult the official documentation.
- Trim conversation history: use sliding windows or summary compression for multi-turn conversations to avoid unbounded concatenation.
The recommended prompt structure is:
[Stable system instructions (cacheable)] → [Fixed knowledge base summary] → [Dynamic context] → [User input]
Most caching mechanisms require the prefix to match verbatim. Dynamic content must be placed after stable content; otherwise the cache won’t be hit.
3.3 Output Control
Output tokens are usually priced higher. Controlling output length is often more direct than compressing input:
- Specify the output format explicitly, e.g., use a JSON schema or set a word limit.
- For structured extraction tasks, avoid letting the model elaborate freely.
- Set max_tokens appropriately and combine it with streaming output, aborting generation early when the result is confirmed invalid.
Setting max_tokens too low will truncate output, so you need to track the truncation rate to confirm it doesn’t affect results.
3.4 Batch and Asynchronous Processing
Non-real-time tasks such as offline annotation, content production, and log analysis can use the batch APIs offered by providers. Some providers offer discounts for batch calls, but the discount rate, applicable models, latency requirements, and concurrency limits vary. Batch jobs typically have a completion window and are unsuitable for scenarios where users wait online. Actual savings should be based on official pricing and your own batch testing.
3.5 Quality Guardrails
Low-cost strategies require quality guardrails. Common practices are as follows:
