LLM API Cost Accounting: From Unit Prices to Real Bills
Comparing LLM API list prices alone can be misleading, because real bills depend on the input/output mix, cache reuse, and time-of-day pricing. This article breaks down common billing dimensions, shows how to estimate cost per request and daily cost with a Python example, and explains how cache hit rate, output length, and scheduling affect spend. It also introduces cost per successful task as a more complete evaluation metric and provides a pre-launch checklist.
1. Why Unit-Price Comparisons Do Not Determine Model Selection
Model providers usually price by the million tokens and split the price across multiple dimensions. Two models’ unit-price tables may look easy to compare side by side, but the actual bill depends on three things: the input/output structure of business requests, whether the cache can be reused, and when the request is sent.
For example, a model may have an input unit price that is half as expensive, but because it produces longer output and requires more retries, the final cost per task may still be higher. Before selecting a model, you need to build a cost model that converts unit prices into “how much each business request costs” or “how much it costs to complete one task.”
2. Common Billing Dimensions
Most usage-based LLM APIs include the following billing dimensions.
2.1 Input Tokens (Cache Miss)
This is the newly computed input content in each request, including the user question, newly added context, retrieved document chunks, and so on. It is usually a major component of the bill.
2.2 Input Tokens (Cache Hit)
When the server can identify that the request prefix matches a previous request, that prefix can be billed at the cache price. The cache price is usually much lower than the regular input price and is often only a few percent of it. Exact hit conditions, cache validity period, and minimum prefix length should be confirmed in the provider’s official documentation.
2.3 Output Tokens
Output unit prices are usually significantly higher than input unit prices. The longer the generated content, the faster the cost grows. For scenarios that require step-by-step reasoning or long-form output, output length is often the largest cost variable.
2.4 Time-of-Day Differences
Some services distinguish off-peak hours from peak hours, with higher unit prices during peak hours. If the business has clear traffic peaks that cannot be shifted, include this difference in the budget.
3. Building a Cost Estimation Model
Combining the dimensions above, the cost per request can be written as:
Cost per request = (cache-miss input tokens × cache-miss unit price + cache-hit input tokens × cache-hit unit price + output tokens × output unit price) ÷ 1,000,000
Time-of-day differences can be handled with a weighted unit price:
Weighted unit price = off-peak share × off-peak unit price + peak share × peak unit price
The following code demonstrates how to estimate cost per request and daily cost. The unit prices are illustrative assumptions for demonstration and should be replaced with the numbers in the provider’s official price list in actual use.
# Unit: CNY per million tokens; the values below are illustrative assumptionsPRICE_PER_M = {"input_miss": 1.00,"input_hit": 0.02,"output": 4.00,}def estimate_cost(input_tokens, cache_hit_ratio, output_tokens, prices=PRICE_PER_M):"""Estimate the cost of a single request (CNY)."""hit_tokens = input_tokens * cache_hit_ratiomiss_tokens = input_tokens - hit_tokenstotal = (miss_tokens * prices["input_miss"]+ hit_tokens * prices["input_hit"]+ output_tokens * prices["output"])return total / 1_000_000per_request = estimate_cost(input_tokens=2000, cache_hit_ratio=0.6, output_tokens=500)daily_requests = 100_000print(f"Cost per request: {per_request:.6f} CNY")print(f"Daily cost ({daily_requests} requests): {per_request * daily_requests:.2f} CNY")
Under these assumptions—2,000 input tokens per request, a 60% cache hit rate, and 500 output tokens—the cost per request is approximately CNY 0.002824, and 100,000 requests per day cost approximately CNY 282.40.
This result illustrates a common phenomenon: under the illustrative unit prices, the output portion accounts for about 70% of the per-request cost, far higher than the input portion. When optimizing cost, first identify the largest cost dimension instead of focusing only on the input unit price.
4. How Cache Hit Rate Affects Cost
Cache benefits depend on how stable the request prefix is. The following practices can help improve the hit rate.
Put fixed content first. Invariant content such as system prompts, tool definitions, and fixed format instructions should be placed at the beginning of the request and kept consistent across requests. Variable content, such as the user’s current question, should be placed at the end.
Avoid meaningless prefix changes. For example, inserting a timestamp or request ID into the system prompt makes the prefix different every time, so the cache cannot hit.
Reuse retrieval results. In retrieval-augmented generation (RAG) scenarios, if the same set of documents is referenced multiple times, keep the concatenation order stable to reduce repeated computation.
Cache hit rate can be calculated from logs:
Hit rate = input tokens with cache hit ÷ total input tokens
It is recommended to measure it separately by endpoint and by business line. A global average can easily hide endpoints with very low hit rates.
5. Controlling Output Length
Output cost control mainly relies on the following three approaches.
- Constrain the output format explicitly. Require JSON or fixed fields to avoid long explanatory text from the model.
- Set a reasonable maximum output length. Set an upper limit based on business needs to prevent abnormal requests from producing excessively long outputs.
- Streamline instructions in the prompt. Long role settings and repetitive explanations increase input cost and may also encourage the model to output more content.
Note that over-compressing output may affect answer quality. After setting limits, monitor whether task completion rate drops based on evaluation results.
6. Scheduling Strategy for Peak Hours
If the business has deferrable tasks, such as offline summarization, batch labeling, or data cleaning, consider scheduling them during off-peak hours. Common implementation methods include:
- Place tasks with low real-time requirements into a queue and consume them with scheduled jobs during off-peak hours;
- Set rate limits for real-time requests to prevent instantaneous peaks from raising overall cost;
- Use exponential backoff for failed requests to avoid duplicate calls in a short period amplifying costs.
Scheduling strategy requires a trade-off between cost and latency. Deferring tasks to off-peak hours can reduce cost but increases user wait time, making it suitable for background scenarios where users do not perceive the delay.
7. Beyond Unit Price: Cost per Successful Task
The cheapest model is not necessarily the most cost-effective. If its task pass rate is lower and it requires more retries or manual correction, total cost may actually be higher.
You can measure this with cost per successful task:
Cost per successful task = total cost ÷ number of tasks that pass evaluation
Suppose Model A has a unit price of CNY 1 and a task pass rate of 60%; Model B has a unit price of CNY 1.5 and a pass rate of 90%. Their costs per successful task are:
- Model A: 1 ÷ 0.6 ≈ CNY 1.67
- Model B: 1.5 ÷ 0.9 ≈ CNY 1.67
In this example, the two are tied. In actual evaluation, also consider latency, context window length, stability, availability, and data compliance requirements.
The basic steps for building an evaluation set are as follows:
- Extract representative samples from real business traffic, covering common scenarios and edge cases;
- Define automatically checkable pass criteria for each sample, such as field completeness, format correctness, and whether key information is captured;
- Run the evaluation set on each candidate model and record pass rate, token usage, and response time;
- Use the formula above to calculate cost per successful task for each model, and make a comprehensive decision together with metrics such as latency.
8. Implementation Checklist
Before launch, check cost control against the following checklist.
- Token usage for input, output, and cache hits has been measured separately by endpoint;
- Billing rules for each dimension in the official price list have been confirmed, including cache conditions and peak/off-peak divisions;
- The fixed part of the system prompt is at the beginning of the request and contains no dynamic fields;
- A maximum output length has been set for each endpoint;
- Deferrable tasks are scheduled separately from real-time tasks;
- Before launch, cost per successful task has been calculated with the evaluation set, rather than only comparing unit prices;
- A daily budget alert has been set to trigger throttling or degradation when the threshold is exceeded.
Cost control is an ongoing process. After business volume, prompts, and model versions change, rerun the estimation and evaluation.
