Evaluating LLM API Costs: Billing Breakdown and Testing Methods
Evaluating the true cost of Large Language Model (LLM) APIs requires more than just comparing unit prices. This article breaks down LLM API billing structures, including input, output, and cached token costs, and highlights hidden expenses such as inference rounds and retries. It provides a practical A/B testing framework for model selection, explains how to optimize cache hit rates, and outlines engineering best practices to balance cost and quality effectively.
1. Unit Price Does Not Equal Actual Cost
LLM services are typically billed by token, with input and output priced separately (output is usually more expensive than input). Some services also offer a cache hit price, where the cached portion of the input is charged at a lower rate. Other providers use time-based dynamic pricing, meaning the same model might cost differently depending on the time of day.
Therefore, simply comparing a single metric like “cost per million input tokens” cannot accurately predict the actual expense of running a business task over a week. What you really need to compare is the average cost to complete a specific task. Teams should base their assessments on usage data from bills and API call logs, rather than the unit prices advertised on marketing pages.
2. Breaking Down the True Cost of a Single API Call
The cost of a single API call can be broken down into three parts: uncached input cost, cached input cost, and output cost. The formula is as follows:
Single Call Cost = Uncached Input Tokens × Input Price + Cached Input Tokens × Cached Price + Output Tokens × Output Price
In pseudocode, this looks like:
function estimate_cost(usage, price):uncached_input = usage.input_tokens - usage.cached_tokenscost = uncached_input * price.inputcost += usage.cached_tokens * price.cached_inputcost += usage.output_tokens * price.outputreturn cost
For example, assume a model charges $1 per million input tokens and $4 per million output tokens (these numbers are for demonstration only and do not represent actual prices). A task consumes 2,000 input tokens and 800 output tokens. The cost would be 2000 / 1,000,000 × 1 + 800 / 1,000,000 × 4 = 0.002 + 0.0032 = $0.0052.
This calculation illustrates two points. First, the proportion of output tokens significantly impacts the total cost; tasks generating long text should pay special attention to the output price. Second, as long as you capture the usage fields from each call, you can calculate the exact cost without relying on estimations.
3. Hidden Costs from Inference Rounds
Some models perform multiple rounds of reasoning, self-verification, or multiple attempts before answering, which increases both the output token count and the number of API calls. In such cases, a lower unit price might be offset by a larger output volume.
Consider a scenario: Model A’s output price is 70% of Model B’s, but its average output volume for the same batch of tasks is twice that of B. Model A’s output cost would then be 0.7 × 2 = 1.4 times that of B. Despite having a lower unit price, the total cost is higher.
Another easily overlooked factor is retries. Re-calling the API after a failure results in duplicate charges. If a model has a high format error rate, even if its unit price is low, the accumulated retry costs will add up. Therefore, a more reasonable metric is the average cost per successful task:
Cost Per Successful Task = Total Cost / Number of Passed Tasks
This metric reflects unit price, output length, retry rate, and pass rate simultaneously, making it much closer to actual business costs than simply comparing unit prices.
4. Cache Hit Rate Determines the Actual Price
Many services support prefix caching. System prompts, fixed examples, and tool definitions can hit the cache if placed at the beginning of the request and kept unchanged. Variable user inputs should be placed at the end.
The cache hit rate heavily impacts cost. Suppose a system prompt has 3,000 tokens, and each request includes an additional 500 tokens of variable content. If the hit rate is close to 100%, most of the input will be billed at the cache price. However, if the prompt is slightly modified each time, causing the hit rate to drop significantly, the input cost will rise noticeably.
Teams should track the hit rate from the returned usage fields rather than estimating by feel. Additionally, consult each provider’s documentation to confirm cache TTL (Time To Live), minimum cache length, and concurrency rules, as these details vary by service.
5. Using A/B Testing for Model Selection
You cannot determine which model saves more money just by looking at bills and unit prices; you need to design controlled experiments. Here is a practical set of steps:
Step 1: Define evaluation metrics. Core metrics include cost per successful task, task pass rate, latency (focusing on P95 is recommended), failure rate, and rate limit occurrences. The pass rate needs to be defined by the business and can be determined via rule validation or manual spot-checks.
Step 2: Stable routing. Hash traffic by task ID to ensure the same task always enters the same group, with a controllable group ratio. Pseudocode:
function route(task_id):bucket = hash(task_id) mod 100if bucket < 50:return model_Areturn model_Bfunction record(task_id, model, usage, passed, latency):cost = estimate_cost(usage, price_table[model])log(task_id, model, cost, passed, latency)
Step 3: Control variables. Both groups should use the same prompts, same temperature, and same max output length parameters, replacing only the model. When parameters are inconsistent, the comparison results cannot be attributed to the model itself.
Step 4: Cover a full cycle. The test should last at least 7 days to cover weekdays, weekends, as well as peak and off-peak hours. The sample size must also be large enough. If the pass rates of the two groups differ by only a few percentage points, a significance test is required; otherwise, the conclusion might just be random noise.
Step 5: Aggregate results. Calculate for each model:
Cost Per Successful Task = Total Cost / Number of Passed Tasks
If a model has a lower unit price but a significantly lower pass rate, its cost per successful task might be higher. In this case, you should factor the quality loss as additional manual review costs or business losses before making a decision.
6. Evaluate Quality and Cost Together
Saving money only makes sense when quality meets the standards. It is recommended to build a fixed evaluation set containing 100 to 300 real business samples, covering both common and edge cases. Before switching models, run them through the evaluation set and record the pass rate and typical errors.
Automated evaluation can check format, field integrity, and key facts. For semantic tasks, periodic manual spot-checks are also necessary. Combining both methods prevents missing quality degradation when only looking at automated metrics.
7. Implementing Model Selection in Engineering
- Put model names, price tables, and routing rules into configuration files so that switching models does not require modifying business code.
- Track costs daily and set budget alerts. When the daily cost exceeds a threshold, the system should automatically alert or downgrade to a fallback model.
- Offline batch tasks can be scheduled during off-peak pricing hours. This relies on confirming that dynamic pricing exists in your billing and that the tasks do not have strict time constraints.
- Keep a fallback model to handle rate limits, timeouts, or service failures. The fallback strategy itself should also be factored into the cost evaluation.
- Model versions and prices change. It is recommended to re-run a round of A/B testing every quarter or after a provider adjusts its pricing.
8. Common Pitfalls
- Pitfall 1: Comparing only the unit price per million tokens. The unit price does not include output length, cache hits, and retries, leading to inaccurate conclusions.
- Pitfall 2: Ignoring caching. When the prompt structure is unstable, the cache might not hit at all, making the cost higher than expected.
- Pitfall 3: Testing too short or with too small a sample. A few days of data might only reflect a specific time period. You need sufficient sample sizes and significance testing to judge if the results are reliable.
- Pitfall 4: Mixing different prompts or parameters in comparison. Differences obtained this way cannot be attributed to the model itself.
- Pitfall 5: Looking only at cost, not quality. If a cheaper model has a lower pass rate, the final cost per successful task may actually be higher.
To reach a reliable model selection conclusion, you must compare billing rules, cache behavior, output length, and quality metrics within the same framework.
