LLM API Costs Explained: From Token Billing to Model Selection
This article explains how large language model API costs are calculated, starting with token-based billing. It breaks down the four main cost components: regular input tokens, cached input tokens, output tokens, and context-length pricing tiers. It also covers why output tokens often drive the bill, how to estimate costs from real usage data, and how to weigh capability, cost, and latency when choosing a model. Practical ways to reduce spending and a pre-launch checklist are included.
1. Why Pricing Is Based on Tokens
LLM API usage is billed by token. A token is the smallest unit a model uses to process text. An English word, a Chinese character, or a punctuation mark may map to one or more tokens, and the exact splitting depends on each provider’s tokenizer. As a result, the same text can produce different token counts on different models. When estimating cost, use the token counts reported by the provider. Do not use character or word counts as a substitute.
Token-based billing reflects the fact that inference cost scales with the amount of data processed. Longer inputs mean the model must process more context. Longer outputs mean the model must generate more tokens, one at a time. These two parts make up most of an API bill.
2. The Four Components of Cost
The cost of a single API call usually combines the following components.
- Regular input tokens: Prompt text that does not hit the cache, including the prompt, conversation history, and retrieved documents. This is the baseline billing item.
- Cached input tokens: If a provider supports prefix caching and the beginning of a request matches an earlier request, that portion may be billed at a lower unit price. The conditions for cache hits, the cache lifetime, and the discount rate are set by the provider. Check the relevant documentation to confirm them.
- Output tokens: The model’s generated response, structured data, or tool call arguments. Output tokens are usually priced significantly higher than input tokens.
- Context-length tiers: Some providers charge different unit prices based on the length of the context in a single request. For long-context requests, the unit price may be higher. When estimating cost, compare the short-context and long-context price tables separately.
Before estimating, confirm whether the provider’s price list separates these four categories, and record the unit price for each.
3. Why Output Tokens Are Often the Key Factor
Many teams focus only on input tokens when estimating cost. This is a common mistake. Large models generate text one token at a time, and each new token requires a full forward pass. Output is therefore usually more computationally intensive than input, which is processed in batches. Provider pricing reflects this. Output prices are typically several times higher than input prices.
In generation tasks, the bill can be driven mainly by output even when inputs are long. Summarization, report generation, and code generation often produce long outputs, which shifts the cost structure toward output. When budgeting, pay closer attention to the distribution of output lengths than to average input length.
4. Cost Estimation Method
The following generic function calculates the cost of a single request or a batch of requests. The prices in the example are illustrative. Replace them with the prices published by your provider before use.
function estimate_cost(input_tokens, cached_tokens, output_tokens, price):// price unit: CNY per million tokensuncached = input_tokens - cached_tokenscost_input = uncached * price.input / 1_000_000cost_cache = cached_tokens * price.cache / 1_000_000cost_output = output_tokens * price.output / 1_000_000return cost_input + cost_cache + cost_outputprice = { input: 2.0, cache: 0.2, output: 8.0 } // Assumed prices, for demonstration onlycost = estimate_cost(4000, 3000, 800, price)// Result: 0.009 CNY
In this example, a single request has 4,000 input tokens, of which 3,000 hit the cache, and 800 output tokens. The output accounts for about 71% of the total cost. At these assumed prices, reducing output length saves far more than compressing input.
A more reliable approach is to collect the actual input, cached, and output token counts from your production logs. Aggregate them by day and by feature module to get the average cost and percentile costs for each type of request. This gives a closer picture of the real bill than estimates based on single sample calls.
5. Three Dimensions of Model Selection
Cost is only one factor when choosing a model. A sound selection framework should consider three factors together.
Capability: The model’s accuracy on your target tasks, its instruction-following ability, its reasoning depth, and its performance in multiple languages. If a model lacks capability, a low unit price may still lead to higher total cost because of rework, manual review, or errors.
Cost: The cost of a single request multiplied by the expected call volume. In high-volume scenarios, small differences in unit price add up quickly.
Latency: Time to first token and overall generation speed. User-facing real-time interactions are sensitive to latency. Offline batch processing places more weight on throughput and unit price.
In practice, start by running a small set of representative samples through the candidate models. Record accuracy, average token counts, and response time. Then compare all three factors in one table. This approach produces conclusions based on your own data rather than on marketing materials.
6. Engineering Practices for Reducing Cost
Control output length: Set a reasonable maximum output token limit for each request, and state in the prompt that responses should be concise and structured. For tasks that only need a classification label or JSON fields, constrain the output format directly so the model does not generate extra explanation.
Improve cache hit rates: Place fixed system instructions, role definitions, and examples at the start of the request, and put variable user input after them. Cache hits are only possible when the prefix stays stable. Avoid inserting timestamps or request IDs into the fixed prefix.
Trim prompts: Remove repeated instructions and irrelevant conversation history. For long documents, retrieve or summarize first, and include only the relevant passages in the context.
Route tasks by difficulty: Sort requests into difficulty tiers. Send simple classification and extraction tasks to a low-cost smaller model, and call a high-capability model only for complex reasoning. You can build the routing rules by training a simple classifier on manually labeled samples, or use static routing based on request type.
Batch and run asynchronously: For non-real-time tasks, merge requests and run them at off-peak times. This reduces scheduling overhead and makes it easier to control concurrency and rate limits.
Budget and monitor: Set daily budgets and alert thresholds for each feature module. Record the token count and cost of every call. When something goes wrong, such as a prompt template that causes output to spike, you can detect it early and roll back the change.
function route(request):if request.type in ["classify", "extract"]:return small_modelif request.estimated_reasoning_depth > threshold:return large_modelreturn medium_model
7. Pre-Launch Checklist
- Confirm the input, cached input, output, and context-length tier prices in the provider’s price list, and record the effective date.
- Use real business samples to measure average and high-percentile input and output token counts.
- Complete capability evaluations on the candidate models, and record accuracy and failure cases.
- Calculate daily and monthly costs based on expected call volume, and keep a safety margin.
- Set output length limits, timeouts, and retry counts to prevent abnormal requests from causing runaway costs.
- Set up cost monitoring and alerts, and review the cost per unit of work on a regular basis.
Cost estimation is an ongoing task. Changes in business scale, prompt iterations, and provider price changes all affect the shape of the bill. Track cost metrics on your regular operations dashboard, alongside quality metrics.
