How to Calculate the True Per-Task Cost After an LLM Capability Upgrade
When evaluating an LLM upgrade, many teams only compare per-token API prices and assume costs stay flat if the price list does. This article explains why that assumption fails, breaks down the typical token billing structure (input, cached input, and output tokens), and provides formulas and sample Python code for computing per-task cost. It also introduces "cost per successful task" as a fairer comparison metric and offers practical engineering techniques—evaluation baselines, output-length control, context optimization, tiered routing, and budget monitoring—to keep LLM spending under control as models evolve.
1. Same Unit Price Does Not Mean Same Cost
For large language model services, API pricing is usually expressed per million tokens. When a model is upgraded, many teams only compare the price table: if the new version’s unit price is unchanged, they assume the cost is unchanged. This judgment ignores a key variable—how many tokens are actually consumed to accomplish the same task.
The unit price is a number on the price sheet; the cost is the amount your business actually pays. The relationship between them can be summarized as:
Total cost = unit price × actual tokens consumed
Whenever actual consumption changes, total cost changes too, even if the unit price stays the same. Therefore, evaluating the economics of a model upgrade requires looking at three metrics together: unit price, per-task token consumption, and task success rate.
2. Breaking Down a Typical API Billing Structure
Most LLM APIs bill for the following token categories, each often priced quite differently.
2.1 Input Tokens
Input tokens include the system prompt, conversation history, retrieved reference material, tool definitions, and the user’s current question. The input portion is usually long—especially in multi-turn conversations or agent scenarios—because each turn resends the previous context to the model, causing the input size to grow turn by turn.
2.2 Cached Input Tokens
When the server detects that a request’s prefix matches a recent request, it can reuse previously computed intermediate results, and this portion of the input is billed at a lower price. This mechanism is commonly known as prompt caching. Its benefit depends on two factors: the length of the stable prefix and the cache hit rate.
The engineering takeaway is straightforward: place invariant content—system prompts, tool descriptions, fixed templates—at the front of the request, and put variable user input at the end. This can significantly improve cache hit rates.
2.3 Output Tokens
Output tokens cover everything the model generates: the final answer, reasoning traces (if billed as output), structured content, and tool-call arguments. In most price tables, output is priced higher than input, so changes in output tokens tend to have a larger impact on total cost.
3. How to Calculate Per-Task Cost
Per-task cost refers to the total API fees spent completing one full business task, not the cost of a single request. A task may involve multiple model calls, several tool invocations, and retries after failures.
3.1 The Basic Formula
Per-task cost can be calculated as follows:
Per-task cost = Σ (input tokens × input price + cached input tokens × cached price + output tokens × output price) ÷ 1,000,000
The summation covers every call in the task, including failed and retried calls.
3.2 Sample Code
The following code shows how to compute the cost of a single call. The prices are example parameters, not real quotes from any specific provider; replace them with your own provider’s actual pricing.
def estimate_call_cost(input_tokens: int,output_tokens: int,price_in: float,price_out: float,cached_tokens: int = 0,price_cached: float | None = None,) -> float:"""Calculate the cost of a single model call.Prices are per million tokens (in the same currency unit)."""if price_cached is None:price_cached = price_infresh_input = input_tokens - cached_tokenscost = (fresh_input * price_in+ cached_tokens * price_cached+ output_tokens * price_out)return cost / 1_000_000def estimate_task_cost(calls: list[dict], **prices) -> float:"""Sum the cost of all calls in a task, including failed and retried calls."""return sum(estimate_call_cost(**call, **prices) for call in calls)
In practice, log the input tokens, output tokens, and cache-hit tokens for every call, then aggregate by task ID to obtain the true distribution of per-task cost. Beyond the average, also track percentiles such as P50 and P95, because a small number of long tasks often accounts for most of the spend.
3.3 The Compounding Effect in Agent Scenarios
Agent-style tasks typically require multiple rounds of planning, tool invocation, result reading, and further reasoning. Each round’s input contains all previous context, and the output may include intermediate reasoning and tool arguments. As a result, each additional step usually grows cost faster than linearly.
For example, if a task runs 10 rounds and the context grows from 2,000 tokens to about 12,000 tokens, the total input will far exceed 10× the single-round input. This is why long-running agent tasks demand careful context management.
4. Why Total Cost Can Rise Even When the Unit Price Does Not
In a model upgrade, the following situations can raise total cost even with unchanged unit prices.
4.1 Output Token Growth
A new model version may provide more complete reasoning, more code comments, or more detailed step-by-step explanations. For complex tasks, this often reflects improved capability, but it directly increases output tokens. If output tokens per task grow by 20% while the output price stays the same, the output portion of the bill grows by roughly 20% too.
4.2 Longer Tool-Call Arguments
In tool-calling scenarios, the model generates structured arguments. If the new version adds more fields or more detailed descriptions to improve accuracy, the argument length grows accordingly.
4.3 Retry and Failure Costs
If the new version has a higher first-attempt success rate, retries decrease and cost may actually fall. Conversely, if the task success rate drops, failed calls still incur fees—and often the entire task must be re-run. Cost analysis must therefore always be considered alongside the task success rate.
4.4 A Worked Example
The following numbers are illustrative and do not represent any real model’s behavior.
Assume a task has 20,000 input tokens, an input price of 1.0 per million tokens, and an output price of 4.0 per million tokens.
- Old version: 10,000 output tokens. Cost = 20,000 × 1.0 ÷ 10^6 + 10,000 × 4.0 ÷ 10^6 = 0.02 + 0.04 = 0.06.
- New version: input unchanged, output increases to 12,000 tokens. Cost = 0.02 + 0.048 = 0.068.
With identical unit prices, per-task cost rises by about 13%. If the new version lifts the success rate from 80% to 95%, and a failed task must be re-executed once at the cost of a successful one, then the effective costs of both versions must be adjusted by their success rates—and the conclusion may be completely different. The core metric for deciding whether an upgrade is worthwhile should be “cost per successful task.”
5. Comparing Models by Cost per Successful Task
Comparing single-call prices or a single benchmark score alone cannot answer “which model is more cost-effective.” A more reasonable approach is to use:
Cost per successful task = average per-task cost ÷ task success rate
This metric reflects the combined influence of unit price, consumption, and reliability.
When making horizontal comparisons, also keep the following in mind:
- Use the same set of task samples to ensure a fair comparison.
- Define acceptance criteria in advance—for example, whether code passes tests or whether answers meet format requirements.
- Record averages and percentiles so that a few extremely long tasks don’t mask the overall trend.
- Consider latency. Longer outputs mean longer waits, which affects both interactive experience and concurrency.
6. Practical Engineering Recommendations for Cost Optimization
Model selection is only the first step; sustained cost control depends on engineering practices. Here are some general, actionable approaches.
6.1 Build an Evaluation Set and a Cost Baseline
Select representative tasks to form a fixed evaluation set, and record each task’s input tokens, output tokens, number of calls, and final success. Re-run the evaluation set against the baseline after every model upgrade or prompt adjustment.
6.2 Control Output Length
- Specify the expected format and length of answers in the prompt to avoid irrelevant explanations.
- For structured output, prefer fixed fields to reduce redundant text.
- Set a reasonable maximum output length to prevent abnormal inflation in individual requests.
6.3 Optimize Context
- Summarize and compress conversation history, keeping only information relevant to the current task.
- Place stable system instructions and tool definitions in the request prefix to improve cache hit rates.
- Filter and deduplicate retrieval results to avoid sending large amounts of irrelevant text to the model.
6.4 Tiered Routing
Not every task needs the most powerful model. Tasks can be routed by difficulty: simple classification, extraction, and format conversion go to lower-cost models, while complex reasoning and code generation go to more capable ones. Routing rules can start from task type and be refined over time based on failure records.
6.5 Set Budgets and Monitoring
- Track cost by task type, business line, and user, with daily, weekly, and monthly budget thresholds.
- Alert on requests whose per-task cost exceeds P95, and investigate possible infinite loops or runaway context.
- Set an upper limit on abnormal retry counts.
7. From Capability Competition to Efficiency Competition
As model capabilities keep improving, differences in price and efficiency among models at similar capability levels will matter more and more. When several models perform comparably on the same class of tasks, the one that completes them with fewer tokens and a lower failure rate is the more competitive one.
For developers and enterprises, this means model selection criteria should cover the following dimensions:
- Capability: success rate on real business tasks, not a single leaderboard score.
- Cost: cost per successful task, not the unit price.
- Stability: the variance of output length and whether failure modes are predictable.
- Engineering fit: how easily the model supports caching, routing, rate limiting, and monitoring.
In summary, judging whether an LLM API is cost-effective requires shifting focus from unit price back to the task itself. Break tasks down, log consumption, compute cost per successful task, and continuously monitor output inflation and success-rate changes—only then can you make stable, verifiable decisions in an environment of rapid model iteration.
