Evaluating LLM API Costs: Key Metrics Beyond Unit Price
Simply comparing unit prices of large language models is insufficient for assessing true usage costs. This article explains how to evaluate LLM API costs by analyzing input, output, and cached tokens. It covers the calculation of per-task costs, the impact of output expansion and retries, strategies for jointly assessing model capability and cost, and best engineering practices for cost optimization and monitoring.
1. Unit Price Does Not Equal Actual Cost
LLM services typically charge per million tokens, distinguishing between input, output, and cache hits. Many teams compare only pricing tables during model selection, which often leads to unreliable conclusions. The reason is that the number of tokens consumed by different models for the same task varies. A model with a lower unit price but verbose outputs might result in a higher final bill than a more expensive model that provides concise answers.
Therefore, cost evaluation requires looking at both unit price and usage together. Unit price is the pricing signal, usage is the behavioral result, and the product of the two represents the actual expenditure.
2. Basic Cost Components
2.1 Input Tokens
Input includes system instructions, conversation history, retrieved document chunks, and user queries. The longer the context, the more input tokens are consumed. Common sources of bloat include repeatedly injecting full history records, unfiltered retrieval results, and verbose system instructions sent with every request.
2.2 Output Tokens
The unit price for output tokens is usually higher than for input. It is directly affected by response length, the visibility of the reasoning process, and formatting requirements. For tasks without output length constraints, the variance in output tokens can be significant.
2.3 Cache Hits
When multiple requests share a common prefix, the server may charge based on a cache hit rate, which is lower than the standard input price. Therefore, stable system instructions and fixed document prefixes should be placed at the beginning of the request to maximize the hit rate. Cache benefits depend on the degree of prefix reuse, and specific hit rules should be verified in the provider’s official documentation.
3. Calculating Per-Task Cost
Per-task cost reflects actual spending better than unit price. The calculation formula is as follows:
Per-Task Cost = (Uncached Input Tokens × Input Unit Price + Cached Input Tokens × Cache Unit Price + Output Tokens × Output Unit Price) ÷ 1,000,000
The corresponding code example is as follows:
from dataclasses import dataclass@dataclassclass Pricing:input_per_m: float # Price per million uncached input tokenscached_per_m: float # Price per million cached input tokensoutput_per_m: float # Price per million output tokensdef task_cost(pricing: Pricing, uncached_in: int, cached_in: int, output: int) -> float:return (uncached_in * pricing.input_per_m+ cached_in * pricing.cached_per_m+ output * pricing.output_per_m) / 1_000_000
Let’s demonstrate the calculation with a hypothetical example. Assume a task inputs 20,000 tokens, of which 15,000 tokens hit the cache, and outputs 2,000 tokens. Model A has an input unit price of 1.0, a cache unit price of 0.2, and an output unit price of 4.0 (in currency units per million tokens). These numbers are for demonstration only:
Per-Task Cost = (5,000 × 1.0 + 15,000 × 0.2 + 2,000 × 4.0) ÷ 1,000,000 = 0.016
Assume Model B has an input unit price of 0.8, the same cache unit price of 0.2, and an output unit price of 6.0. Completing the same task requires only 1,500 output tokens:
Per-Task Cost = (5,000 × 0.8 + 15,000 × 0.2 + 1,500 × 6.0) ÷ 1,000,000 = 0.016
The costs are identical. This example illustrates that a lower input unit price does not equal a lower total cost; output efficiency is equally critical.
3.1 Including Failures and Retries
In production environments, tasks may be retried due to timeouts, formatting errors, or unacceptable results. A more reasonable metric is the cost per successful task, calculated as total spend divided by the number of successfully completed tasks. Ignoring retries will underestimate the true cost.
4. The Impact of Output Bloat
After version iterations, the same model might increase its output tokens due to more thorough reasoning or complete answers. Even if the unit price remains unchanged, the per-task cost will rise. Using Model A above as an example, if the output increases from 2,000 tokens to 2,400 tokens (a 20% increase), the per-task cost becomes:
(5,000 × 1.0 + 15,000 × 0.2 + 2,400 × 4.0) ÷ 1,000,000 = 0.0176
The cost increases by about 10%. The impact of output growth on total cost depends on the output’s proportion of the total cost. The higher the output proportion, the more important it is to control output length.
Common mitigation strategies include:
- Explicitly specifying response length and output format in the prompt;
- Setting a reasonable maximum output length limit and detecting truncated results;
- Requesting structured output to reduce irrelevant explanatory text;
- Using shorter output templates for simple tasks.
5. Joint Evaluation of Capability and Cost
Looking at a single capability metric or a single price is insufficient to support decision-making. A more practical approach is to combine capability scores with per-task cost, such as comparing the number of tasks completed under the same budget or the evaluation score per unit cost.
When evaluating, note the following:
- Evaluation datasets should closely reflect business scenarios; general benchmark scores are only for reference.
- The same evaluation should run under identical prompts, sampling parameters, and context conditions.
- Cost statistics should be based on real request logs, not estimates.
- First-time success rates must be recorded, as low success rates will inflate the effective cost.
6. Engineering Best Practices
6.1 Establish Cost Monitoring
Log input tokens, cache hits, output tokens, and latency at the request layer, and aggregate them by task type, model version, and functional module. You can utilize general logging services and monitoring alerting capabilities to set threshold alerts for per-task costs, promptly identifying abnormal growth.
6.2 Optimize Context
- Summarize and compress conversation history, retaining only the parts relevant to the current task.
- Truncate retrieval results by relevance to avoid injecting entire documents.
- Place stable instructions at the beginning of the request to improve cache hit rates.
6.3 Tiered Routing
Assign simple tasks to lower-cost models and upgrade complex tasks to more capable models. Routing rules should be validated based on historical data rather than intuition.
6.4 Canary Rollouts
Before switching model versions, run a comparison experiment on a small portion of traffic, comparing success rates, latency, and per-task cost. After confirming no significant regressions, gradually expand the rollout scope.
7. Selection Checklist
- Have you calculated the per-task cost based on real business tasks?
- Have you separately tracked the usage of input, cache hits, and output?
- Have you accounted for the extra cost brought by failed retries?
- Have you evaluated changes in output length after version iterations?
- Have you completed a capability comparison under identical conditions?
- Have you set up cost monitoring and alerting?
Conclusion
Competition among LLM services is shifting from purely comparing capabilities to a combined assessment of capability and cost. Developers should evaluate price, usage, and success rates in the same table and support decisions with reproducible data.
