A Better Way to Choose Large Language Models: Measure Cost per Task

    Comparing LLMs by token price alone can be misleading. This article explains how to calculate true cost per task, evaluate quality against cost, build tiered routing, create an internal benchmark, and monitor production performance so teams can choose models based on measurable business value.

    1. Why Model Selection Should Focus on Cost per Task

    Model services are billed by token, with prices typically listed per million tokens. Many teams compare models by looking only at these price tables, but this approach has clear limitations. The same model may consume very different numbers of tokens across tasks. Output length, context size, and the number of calls required can all change the final bill. A low-priced model may not actually be cheaper if it requires repeated retries or produces unnecessarily long responses.

    A more useful metric is cost per task: the total cost required to complete one business task. It consists of three components:

    • Input token cost
    • Cached input token cost
    • Output token cost

    These costs must be considered together with task success rate to determine whether a model is genuinely cost-effective.

    A common industry practice is tiered pricing based on model capability. Higher-capability tiers cost more and are suitable for tasks with long reasoning chains or strict professional requirements. General-purpose tiers are less expensive and work well for high-volume tasks such as structured extraction, summarization, and classification. Tiered pricing is not a new technology; it reflects the trade-off between capability and cost. The engineering challenge is to apply that trade-off to actual task routing.

    2. Breaking Down the Pricing Model

    Assume that a request contains T_in total input tokens, of which T_cache are served from cache, and produces T_out output tokens. Let P_in, P_cache, and P_out be the prices for the three token categories, each expressed per million tokens.

    The cost of one call is:

    1. Cost = [(T_in − T_cache) × P_in + T_cache × P_cache + T_out × P_out] ÷ 1,000,000

    T_cache is a subset of T_in and must not be counted twice. The following implementation applies this formula:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. input_per_m: float # Price per million uncached input tokens
    5. cached_per_m: float # Price per million cached input tokens
    6. output_per_m: float # Price per million output tokens
    7. def task_cost(p: Pricing, input_tokens: int, cached_tokens: int, output_tokens: int) -> float:
    8. """Calculate the cost of one call. cached_tokens is a subset of input_tokens."""
    9. uncached = max(input_tokens - cached_tokens, 0)
    10. total = (
    11. uncached * p.input_per_m
    12. + cached_tokens * p.cached_per_m
    13. + output_tokens * p.output_per_m
    14. )
    15. return total / 1_000_000

    Consider the following fictional prices, used only to demonstrate the calculation and not to represent any real product. Tier A costs 5 for input tokens, 0.5 for cached input tokens, and 25 for output tokens. Tier B costs 1, 0.1, and 5, respectively.

    Suppose a task uses 3,000 input tokens, including 2,000 cached tokens, and generates 800 output tokens.

    • Tier A: 1,000 × 5 = 5,000 for uncached input; 2,000 × 0.5 = 1,000 for cached input; and 800 × 25 = 20,000 for output. The total is 26,000, or 0.026.
    • Tier B: 1,000 × 1 = 1,000 for uncached input; 2,000 × 0.1 = 200 for cached input; and 800 × 5 = 4,000 for output. The total is 5,200, or 0.0052.

    In this example, the cost per task for Tier A is approximately five times that of Tier B. If Tier B has a sufficiently high success rate, it is the more economical choice. However, if Tier B fails much more often on complex tasks, the hidden costs of retries and manual correction may eliminate its price advantage. Quality data must therefore be evaluated alongside price.

    Two additional points are important:

    1. Output tokens are often more expensive than input tokens. Controlling output length—for example, by requiring structured fields and avoiding redundant explanations—may be more effective than compressing the input.
    2. Cache hit rates depend on stable request prefixes. Placing system instructions, fixed templates, and examples at the beginning of the request and keeping them unchanged can improve cache utilization.

    3. How to Interpret Benchmark Results Correctly

    Public benchmark scores are useful references, but using them directly for model selection can be risky. Consider the following factors.

    Are the evaluation methods consistent? Different organizations use different datasets, prompt templates, tool permissions, and retry limits. The same model may receive significantly different scores in different evaluations. Comparisons should be made only between results produced under the same methodology.

    Are quality and cost reported together? When scores are similar, cost per task may still differ by several times. Model selection should consider the quality-cost Pareto frontier: the options that provide the highest quality at a given cost, or the lowest cost at a given quality level. Solutions outside this frontier generally have little justification for adoption.

    Does the benchmark match your domain? Rankings on general benchmarks do not necessarily predict performance on your own workloads. A model that leads on mathematics or scientific tasks may not perform best for code generation or legal text processing. Your own task data should be the primary reference.

    Are individual results stable? LLM outputs are stochastic, so scores may vary significantly between runs. Run each test case multiple times and record the mean and standard deviation. Do not make a model-switching decision based on a single exceptional result.

    4. Building a Tiered Routing Architecture

    When a business handles both simple and complex tasks, tiered routing is often the most practical approach. The basic flow is:

    1. A lightweight classifier categorizes the request.
    2. Simple requests are sent to a low-cost tier.
    3. A quality-checking module evaluates the result.
    4. Requests that fail the quality check, or are classified as complex, are upgraded to a higher-capability tier.
    1. from typing import Callable, Tuple
    2. def route(
    3. task: str,
    4. classify: Callable[[str], str],
    5. call_small: Callable[[str], str],
    6. call_large: Callable[[str], str],
    7. check_quality: Callable[[str, str], float],
    8. threshold: float = 0.8,
    9. ) -> Tuple[str, str]:
    10. """Return (result, tier actually used)."""
    11. level = classify(task) # Returns "simple" or "complex"
    12. if level == "simple":
    13. draft = call_small(task)
    14. if check_quality(task, draft) >= threshold:
    15. return draft, "small"
    16. # Upgrade complex tasks or low-quality drafts to the higher-capability tier
    17. return call_large(task), "large"

    Several design issues require attention:

    • Classifier cost and misclassification. Classification consumes resources as well. Rules should handle obvious cases, such as fixed-format extraction tasks, while ambiguous requests can be sent to a model-based classifier. Classifying a complex task as simple may reduce quality, while classifying a simple task as complex wastes money. Both types of errors should be tracked through logs.
    • Quality-check reliability. Use rules whenever possible for checks such as JSON validity, field completeness, and length limits. Semantic evaluation can be performed by another model, but model-based judges may have preference bias, such as favoring longer answers. Regular manual sampling is needed for calibration.
    • Upgrade cost limits. Set a maximum number of calls and a budget limit per request to prevent abnormal requests from being upgraded repeatedly and causing uncontrolled costs.

    5. Building an Internal Evaluation Set

    An internal evaluation set is the most reliable basis for model selection. The process includes the following steps:

    1. Collect real samples. Extract representative requests from production logs, covering both high-frequency scenarios and edge cases. The sample size should support statistical analysis; each major scenario should ideally include at least several dozen examples.
    2. Define scoring criteria. Specify what constitutes a passing result for each task type. Use programmatic checks whenever possible, such as verifying field completeness, confirming that code passes unit tests, or comparing numerical results with expected answers.
    3. Fix the evaluation environment. Keep prompts, temperature settings, tool configurations, and input samples consistent across comparisons. Change only the model being evaluated.
    4. Run multiple trials and record costs. Execute each case multiple times and record input, cached, and output token counts to calculate cost per task.

    The following is a simplified evaluation script:

    1. import statistics
    2. from typing import Callable, Dict, List
    3. def evaluate(
    4. model_fn: Callable[[str], str],
    5. cases: List[Dict[str, str]],
    6. scorer: Callable[[str, str], float],
    7. runs: int = 3,
    8. ) -> Dict[str, float]:
    9. per_case_means = []
    10. for case in cases:
    11. scores = [scorer(model_fn(case["input"]), case["expected"]) for _ in range(runs)]
    12. per_case_means.append(statistics.mean(scores))
    13. return {
    14. "mean_score": statistics.mean(per_case_means),
    15. "stdev_across_cases": statistics.stdev(per_case_means) if len(per_case_means) > 1 else 0.0,
    16. }

    After obtaining quality scores and cost-per-task measurements for each tier, plot them on a quality-cost chart to identify the Pareto frontier. When comparing two options, verify that the score difference exceeds the range of random variation. Otherwise, the evidence may not justify switching models.

    6. Engineering Considerations for Production

    Observability. Record the model tier, input and output token counts, cached token count, latency, whether an upgrade occurred, and the quality score for every call. Aggregate these metrics in a logging or monitoring system. Cost thresholds can trigger alerts, such as a notification when daily spending exceeds a defined proportion of the budget.

    Reliability and fallback. Higher-capability tiers may experience timeouts or rate limits. The routing layer should define timeouts and fall back to another available tier when a call fails. It should also return a clear status to the caller instead of failing silently.

    Data security. Sensitive content sent to a model should be redacted, including identification numbers, phone numbers, and secrets. Raw sensitive data should not be retained in logs either. Workloads involving personal or regulated data should undergo a compliance review first.

    Version changes. Model prices, capabilities, and output formats may change between versions. Before switching versions, rerun the internal evaluation set and maintain a rollback plan.

    1. Inventory current business task types and identify high-volume and high-value tasks.
    2. Use the formula above to estimate the current cost per task for each category and locate the most expensive stages.
    3. Build an internal evaluation set with at least several dozen samples and define passing criteria for every scenario.
    4. Evaluate candidate tiers multiple times, plot quality against cost, and select the options on the Pareto frontier.
    5. Introduce tiered routing for simple, high-volume tasks, with quality thresholds and upgrade limits.
    6. Continue tracking cost and quality after deployment, and repeat the evaluation whenever the model version changes.

    The goal of model selection is to minimize cost per task while maintaining acceptable quality. With consistent evaluation methods and data from real workloads, teams can make verifiable decisions even as model prices and capabilities continue to change.