Rethinking LLM Selection: Measuring Inference Efficiency by Cost per Task
This article explains why per-token pricing is a weak basis for choosing a large language model. It introduces four metrics for comparing models by the cost of completing a task: cost per task, task success rate, effective cost, and output efficiency. It also covers building a reproducible evaluation set, tiered model selection, prompt cache hit rates, and ongoing cost monitoring.
1. Why Unit Prices Do Not Reflect Total Cost
Large language model services usually charge per million tokens, with separate unit prices for input, cached input, and output. Many teams compare only these three figures when choosing a model. They overlook what actually determines the bill: how many tokens a task consumes in total, and whether the task succeeds on the first attempt.
Consider the same task run on two models. Model A has a higher output price, but if it reaches the correct result with fewer output tokens, its final cost may be lower. Conversely, a model with a cheaper unit price may require multiple retries, produce verbose output, or call tools frequently, so its total spend may not be lower. The basic unit for model selection should therefore be the cost of completing one task, not the price of one token.
This effect is especially clear for complex tasks. Long, multi-step tasks repeatedly read context, call tools, and revise intermediate results. Input and output token counts can multiply several times over. Looking at unit prices alone makes actual spending hard to estimate.
2. Four Core Metrics
When evaluating a model, track at least the following four metrics.
1. Cost per task
Cost per task is the total charge for all billable tokens used to complete one task. When calculating it, price cache-hit input tokens and cache-miss input tokens separately, and count every retry toward the total.
2. Task success rate
Success rate is the share of model outputs that pass the acceptance criteria. The business team should define these criteria in advance. Examples include code that passes all unit tests, extracted results that match human annotations, and reports that contain all required sections. Without clear acceptance criteria, success rates cannot be compared.
3. Effective cost
Effective cost equals cost per task divided by success rate. It answers the question: on average, how much must be spent to get one usable result? A model with a low success rate can have a higher effective cost, even when its unit price is low.
4. Output efficiency
Output efficiency is the number of output tokens required to reach a given quality level. Some models with strong reasoning capabilities reach answers through more concise reasoning paths and produce significantly fewer output tokens. These differences affect both cost and response latency, so they should be recorded separately.
Beyond these metrics, latency, stability, and API compatibility should also be part of the evaluation. For online services, time to first token and total completion time often affect user experience more than the cost of a single call.
3. Building a Reproducible Evaluation Set
The credibility of evaluation results depends on how the evaluation set is designed. Follow these practices.
Sample across difficulty levels. The evaluation set should include easy, medium, and hard tasks, and report results for each tier separately. If only easy tasks are used, the advantages of high-end models will not show. If only hard tasks are used, the cost in everyday scenarios will be overestimated.
Fix the evaluation conditions. Identical prompts, temperature settings, and context length limits are needed for a fair comparison. Sampling parameters should be fixed, and each task should run multiple times, with the mean and variance recorded.
Record failed samples in full. Classify failure causes, such as formatting errors, factual errors, exceeding the context limit, or tool call failures. The distribution of failure types often guides improvement more usefully than the overall success rate.
Handle excluded samples with care. Some evaluations remove tasks that used a fallback path or a degraded mode. Exclusion itself can change the ranking. Reports must state how many samples were excluded and why, and give results both with and without those samples. If excluded samples make up a large share, the conclusions deserve less confidence.
4. Cost Calculation Example
The code below shows how to calculate cost per task and effective cost. The prices and usage figures are hypothetical. They illustrate the calculation method only and do not represent any real service’s pricing.
from dataclasses import dataclass@dataclassclass Pricing:input_per_m: float # Price per million uncached input tokens (USD)cached_per_m: float # Price per million cached input tokens (USD)output_per_m: float # Price per million output tokens (USD)def task_cost(p: Pricing, input_tokens: int, cached_tokens: int,output_tokens: int) -> float:"""Calculate the cost of a single task. cached_tokens is the cached part of input_tokens."""if cached_tokens > input_tokens:raise ValueError("cached_tokens cannot be greater than input_tokens")fresh_tokens = input_tokens - cached_tokenstotal = (fresh_tokens * p.input_per_m+ cached_tokens * p.cached_per_m+ output_tokens * p.output_per_m)return total / 1_000_000def effective_cost(cost_per_task: float, success_rate: float) -> float:"""Calculate the effective cost per successful task."""if not 0 < success_rate <= 1:raise ValueError("success_rate must be in the range (0, 1]")return cost_per_task / success_rateif __name__ == "__main__":# Assumed data: Model X has a higher unit price but shorter output,# and Model Y has a lower unit price but longer outputmodel_x = Pricing(input_per_m=8.0, cached_per_m=0.4, output_per_m=40.0)model_y = Pricing(input_per_m=2.0, cached_per_m=0.1, output_per_m=10.0)cost_x = task_cost(model_x, input_tokens=20_000, cached_tokens=5_000,output_tokens=1_000)cost_y = task_cost(model_y, input_tokens=20_000, cached_tokens=5_000,output_tokens=12_000)print(f"Model X cost per task: {cost_x:.4f} USD, effective cost: "f"{effective_cost(cost_x, 0.95):.4f} USD")print(f"Model Y cost per task: {cost_y:.4f} USD, effective cost: "f"{effective_cost(cost_y, 0.75):.4f} USD")
The output shows that Model Y has a slightly lower cost per task, but its success rate is lower. As a result, its effective cost per successful task is higher. This is why looking only at unit prices, or only at cost per task, can lead to wrong conclusions.
5. Tiered Model Selection Strategy
In production, a single model rarely handles all requests. A more common approach is to tier models by task difficulty.
Flagship models suit complex reasoning, comprehensive analysis of long documents, and multi-step planning. Failures on these tasks are costly, so quality should take priority.
Mid-tier models suit high-frequency tasks such as everyday Q&A, code completion, and document rewriting. They balance quality and cost, and they typically handle most of the traffic.
Lightweight models suit highly structured tasks such as classification, field extraction, and keyword recognition. These tasks need little reasoning depth, so a lightweight model can significantly reduce cost.
The key to tiering is the routing rules. Routing can be based on task type, input length, user tier, or the output of an upstream classifier. Routing rules should be validated regularly against the evaluation set. This prevents a high-priced model from being overused when the task distribution changes.
6. Improving Cache Hit Rates
Cache billing requires the request prefix to stay identical across requests. System prompts, tool definitions, and fixed reference documents should go at the beginning of a request, and dynamic content should go at the end. This maximizes prefix reuse.
In practice, monitor the cache hit rate with the following calculation:
def cache_hit_ratio(input_tokens: int, cached_tokens: int) -> float:if input_tokens == 0:return 0.0return cached_tokens / input_tokens
If the hit rate stays low for long periods, there are usually three causes: timestamps or random IDs in the system prompt, an unstable order in the tool list, or conversation history that gets reordered. Fixing these issues often saves more cost than switching models.
7. Considerations for Deployment
Re-evaluate regularly. Model version updates, price changes, and context length changes can all alter the optimal choice. Re-run the same evaluation set every quarter, or after each major model release.
Use gradual rollout. When switching models, first route a small share of traffic to the new model. Compare success rate, latency, and cost, and only then increase the share step by step. Keep the ability to roll back quickly during the switch.
Set up cost monitoring. Split cost data by feature module, tenant, or task type, and set usage threshold alerts. Abnormal cost spikes often indicate prompt regressions, retry storms, or routing configuration errors. This data can be fed into logging services and monitoring and alerting systems.
Protect data. Evaluation sets and production logs may contain user data. Anonymize that data before collection, and define retention periods and access permissions clearly.
8. Summary
Evaluating LLM cost should start from the task, not the unit price. The core steps are: define four metrics (cost per task, success rate, effective cost, and output efficiency); build a tiered, reproducible evaluation set; assign models by task difficulty; and control long-term spending through cache optimization and ongoing monitoring.
Once this method becomes a standard process, teams can compare options against the same yardstick, even as model versions change quickly. They can also link each part of their spending to business results.
