How to Calculate the True Cost per Task When LLM API Unit Prices Stay the Same
When LLM API unit prices remain unchanged, real task costs can still rise because output length, retries, caching, and success rates may change. This article explains how to move from cost per million tokens to cost per business task, provides a practical calculation model and Python estimator, reviews common causes of output-token inflation, and offers an evaluation framework and engineering practices for model selection and cost control.
1. Why Stable Unit Prices Do Not Guarantee Stable Costs
Model providers typically price input tokens and output tokens separately, with unit prices expressed per million tokens. Many teams see that the unit price has not changed and assume that future costs are under control. That judgment is only half right.
Actual spending is determined by two factors: the unit price and the number of tokens consumed to complete a business task. If a new model version needs more output tokens for the same task, or needs more rounds to complete the task, the cost per task will rise even if the unit price remains exactly the same.
Therefore, when evaluating model costs, the focus should shift from “how much per million tokens” to “how much per completed task.” The latter is the cost metric that business stakeholders can actually perceive.
2. A Cost Model for a Single Task
From an engineering perspective, the cost of a single model call can be divided into three parts:
- Uncached input token cost:
uncached input tokens × input unit price - Cached input token cost:
cached input tokens × cached input unit price - Output token cost:
output tokens × output unit price
Adding these three parts gives the cost of a single call. A business task usually contains multiple calls, such as planning first, then execution, and finally validation. Therefore, the task cost is the sum of all call costs.
This model has two prerequisites that need to be made explicit. First, cache hits require the prefix content to remain stable; changes to the prompt structure will invalidate the cache. Second, different providers have different billing rules for caching. The official documentation should be treated as the source of truth, and unit prices should be passed into the code as configuration items rather than hard-coded in the logic.
3. How Success Rate Affects Expected Cost
Many teams only measure the cost of a single call while ignoring the overhead caused by failed retries. Assume that the cost of each attempt is C, the task success rate is p, and failed attempts are retried independently until success. The expected cost to complete a task is then:
Expected cost = C / p
For example, if the cost per attempt is fixed and the success rate rises from 80% to 90%, the expected cost drops by about 11%. This shows that even if a model has a higher unit price, the overall cost may still be lower as long as it significantly improves the first-pass success rate. Conversely, a model with a lower unit price that often requires retries or manual fallback may have a higher actual cost.
Success-rate statistics need to be based on the same evaluation set, and they must distinguish between “correct format” and “correct result.” Otherwise, the statistics will be overly optimistic.
4. Common Causes of Output-Token Inflation
Increases in output tokens usually come from the following categories:
- Longer reasoning processes. Some models generate more intermediate reasoning content before output, and this content is also billed.
- More detailed answers. On complex tasks such as programming and security analysis, models tend to provide more complete explanations. Any content beyond actual business needs directly increases cost.
- Unclear format requirements. If the prompt does not constrain the output structure, the model may output extra explanatory text or repeated content.
- Tool return content being fed back verbatim. Placing large logs or file contents directly back into the context increases both input cost and subsequent output cost.
The way to locate the problem is to compare input tokens, output tokens, and call counts for the same task across different model versions, grouped by task type, and identify the stages with the most obvious inflation.
5. Example: Calculating Cost per Task
The following code provides a general cost estimation function. The unit prices are hypothetical values for calculation purposes and do not represent the actual pricing of any product. Replace them with current official pricing when using the code.
from dataclasses import dataclass@dataclassclass Pricing:input_per_m: float # price per million uncached input tokenscached_input_per_m: float # price per million cached input tokensoutput_per_m: float # price per million output tokens@dataclassclass CallUsage:input_tokens: int # total input tokens for this call, including cached tokenscached_tokens: int # number of input tokens that hit the cacheoutput_tokens: int # number of output tokens for this calldef call_cost(pricing: Pricing, usage: CallUsage) -> float:if usage.cached_tokens > usage.input_tokens:raise ValueError("Cached tokens cannot exceed total input tokens")fresh = usage.input_tokens - usage.cached_tokensreturn (fresh * pricing.input_per_m+ usage.cached_tokens * pricing.cached_input_per_m+ usage.output_tokens * pricing.output_per_m) / 1_000_000def expected_task_cost(per_attempt_cost: float, success_rate: float) -> float:if not 0 < success_rate <= 1:raise ValueError("Success rate must be in the range (0, 1]")return per_attempt_cost / success_rate# Hypothetical prices for demonstrating the calculation onlypricing = Pricing(input_per_m=1.0, cached_input_per_m=0.2, output_per_m=4.0)old = CallUsage(input_tokens=3000, cached_tokens=0, output_tokens=1500)new = CallUsage(input_tokens=3000, cached_tokens=0, output_tokens=1800)old_cost = call_cost(pricing, old)new_cost = call_cost(pricing, new)print(f"Old version cost per call: {old_cost:.6f}")print(f"New version cost per call: {new_cost:.6f}")print(f"Cost change per call: {(new_cost / old_cost - 1):.1%}")print(f"Old version expected task cost (80% success rate): {expected_task_cost(old_cost, 0.80):.6f}")print(f"New version expected task cost (92% success rate): {expected_task_cost(new_cost, 0.92):.6f}")
In the hypothetical example above, the new version’s output tokens increase by 20%, and the cost per call rises by about 13%. However, if the success rate improves from 80% to 92%, the expected task cost actually decreases. This example shows that looking only at the unit price or only at the cost per call is not enough to judge which option is better. Usage and success rate must be calculated together.
6. A Framework for Model Selection
For model selection, it is recommended to use a unified evaluation table that includes at least the following dimensions:
| Dimension | Description | Data source |
|---|---|---|
| Task quality | Accuracy or pass rate on the internal evaluation set | Internal evaluation set |
| Cost per task | Average spending grouped by task type | Call logs and billing details |
| Output-token usage | Distribution of output length for the same task | Call logs |
| Expected cost | Cost per call divided by success rate | Calculated from the three items above |
| Latency | Time to first token and overall completion time | Load test results |
| Stability | Proportion of timeouts, rate limits, and format errors | Production monitoring |
Composite scores from public leaderboards can serve as an initial screening reference, but their relevance to a specific business is limited. The final decision should be based on an internal evaluation set, because business tasks differ from public benchmarks in input distribution, length, and fault-tolerance requirements.
7. Engineering Practices to Reduce Task Cost
After a model has been selected, costs can be further reduced at the engineering level:
- Constrain output length: Set a reasonable maximum output token limit based on the task type, and specify the output format clearly in the prompt, for example by requiring only structured fields to be returned.
- Stabilize the prompt prefix: Place unchanged content such as system instructions and specification documents at the beginning of the request to improve cache hit rates.
- Use tiered routing: Use cheaper models for low-difficulty tasks such as format conversion and simple classification, and reserve high-capability models for complex tasks.
- Trim tool return content: Keep only key fields from tool output and avoid placing entire logs into the context verbatim.
- Reduce unnecessary rounds: Lower back-and-forth follow-up questions and retry counts through more complete task descriptions and pre-validation.
- Batch offline tasks: Combine requests for tasks that do not need real-time responses to reduce call overhead and queuing costs.
Each change should be compared before and after. Looking only at average unit price or cost per call can easily hide the implicit cost of quality degradation.
8. Implementation Recommendations
The following steps are recommended:
- Prepare an evaluation set that covers the main business scenarios, with clear judgment criteria for each sample.
- Record input tokens, cache hits, output tokens, task type, and final result for every call.
- Use the same evaluation set to compare candidate models offline, and calculate quality metrics, cost per task, and expected cost.
- Select a small amount of real traffic for a canary validation and observe actual changes in production success rate and cost.
- Set budget alerts and notify the responsible owner when cost per task or average output tokens exceed thresholds.
As model capabilities continue to improve, cost structures also change. At the same level of intelligence, a solution that can reliably complete business tasks at a lower task cost is often more valuable in practice. Cost accounting should therefore become a standard part of model selection and engineering governance, rather than work that is added only after launch.
