LLM API Selection: Real Costs Beyond Per-Token Pricing

    Choosing an LLM API requires more than comparing price per million tokens. This article breaks down billing components, output token growth, retries, cache hit rates, and task success rates, then shows how to evaluate models by cost per task and cost per successful task. It also provides benchmark code, engineering practices for reducing spend, and a selection checklist for keeping LLM costs under control as models and prices change.

    1. Why Unit Price Alone Misleads Cost Decisions

    When selecting an LLM API, many teams start by comparing the price per million tokens. That comparison is useful, but incomplete. Unit price describes the billing rule; actual spend depends on three factors: how many tokens each call consumes, how many calls are needed to complete a business task, and how much extra overhead comes from failures and retries.

    For example, Model A may have an output unit price half that of Model B, but if it produces twice as many output tokens for the same task, the cost per task is nearly the same. If Model A also needs more turns to produce a usable result, its actual cost may be higher.

    A sound approach is therefore to break cost into “unit price × usage × number of calls” and evaluate each factor separately.

    2. Break Down the Billing Structure

    Mainstream LLM APIs usually bill several token categories separately.

    1. Standard input tokens: user prompts, system instructions, context documents, and other input that does not hit the cache.
    2. Cached input tokens: the portion of a prompt prefix that is cached by the service and matched on a subsequent request. The unit price is usually significantly lower than that of standard input.
    3. Output tokens: model-generated answers, code, structured data, and other output. The unit price is usually higher than input, and in many scenarios this is the main source of cost.

    Some platforms also bill reasoning tokens separately or set a minimum billing unit. Before integration, check the relevant documentation to confirm the billing basis and avoid rough estimates based on character count or request count.

    2.1 Calculating the Cost of a Single Call

    The example below uses hypothetical unit prices only to demonstrate the calculation method. It does not represent the price of any real product.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. input_per_m: float # Standard input, currency units per million tokens
    5. cached_per_m: float # Cached input, currency units per million tokens
    6. output_per_m: float # Output, currency units per million tokens
    7. @dataclass
    8. class Usage:
    9. input_tokens: int # Total input tokens for this request
    10. cached_tokens: int # Number of input tokens that hit the cache
    11. output_tokens: int # Number of output tokens
    12. def call_cost(price: Pricing, usage: Usage) -> float:
    13. if usage.cached_tokens > usage.input_tokens:
    14. raise ValueError("Cached tokens cannot exceed total input tokens")
    15. uncached = usage.input_tokens - usage.cached_tokens
    16. return (
    17. uncached * price.input_per_m
    18. + usage.cached_tokens * price.cached_per_m
    19. + usage.output_tokens * price.output_per_m
    20. ) / 1_000_000
    21. price = Pricing(input_per_m=1.0, cached_per_m=0.2, output_per_m=4.0)
    22. usage = Usage(input_tokens=5000, cached_tokens=3000, output_tokens=1000)
    23. print(f"Cost per call: {call_cost(price, usage):.4f} currency units")

    In this example, there are 2,000 standard input tokens, 3,000 cached input tokens, and 1,000 output tokens, for a total of about 0.0066 currency units. The value of caching is clear here: without a cache hit, the same input would cost roughly twice as much.

    2.2 Input and Output Share Determines the Optimization Direction

    After calculating the cost per call, identify which component accounts for the largest share. If input dominates, the optimization focus is usually shortening context, improving cache hit rates, and removing irrelevant documents. If output dominates, focus on answer length, structured output formats, and unnecessary explanatory text.

    3. Why Output Token Inflation Can Erase Unit Price Advantages

    An unchanged unit price does not mean an unchanged cost. The number of output tokens for the same task may increase because of model version changes, prompt design, or reasoning depth.

    Suppose the output unit price is 4 currency units per million tokens, a task produces 1,000 output tokens, and the output cost is 0.004 currency units. If a new version increases output by 20% to 1,200 tokens, the output cost becomes 0.0048 currency units, also a 20% increase. In scenarios where output accounts for most of the total cost, this increase flows directly into overall spend.

    This phenomenon is often overlooked because teams tend to monitor only whether the unit price has changed, not how many tokens an average task consumes. In production, record the following metrics together:

    • Average input tokens and output tokens per task;
    • Average number of calls per task, including tool calls and retries;
    • Cache hit rate;
    • Task success rate, used to calculate cost per successful task.

    The last item is especially important. A model with a higher unit price but a higher success rate may have an advantage in cost per successful task.

    4. Use Cost per Task Instead of Cost per Token

    When evaluating models, compare them by business task. Specifically, select a representative set of tasks, run each candidate model under the same conditions, and measure quality, cost, and latency.

    4.1 Evaluation Dimensions

    • Quality: Use human labeling or automated scoring to determine whether the output meets requirements. For coding tasks, use unit test pass rates; for information extraction tasks, use field accuracy.
    • Cost: Measure the total spend per task, including all calls and retries.
    • Latency: Record time to first token and overall completion time. For interactive applications, time to first token often affects experience more than total duration.
    • Stability: Run the same input multiple times and observe the range of variation in results.

    4.2 Benchmark Framework Example

    1. import statistics
    2. from typing import Callable
    3. def evaluate_model(
    4. run_task: Callable[[dict], dict],
    5. tasks: list[dict],
    6. judge: Callable[[dict, dict], bool],
    7. cost_fn: Callable[[dict], float],
    8. ) -> dict:
    9. results = []
    10. for task in tasks:
    11. output = run_task(task)
    12. results.append({
    13. "passed": judge(task, output),
    14. "cost": cost_fn(output),
    15. "latency": output["latency_s"],
    16. })
    17. passed = [r for r in results if r["passed"]]
    18. total_cost = sum(r["cost"] for r in results)
    19. return {
    20. "pass_rate": len(passed) / len(results),
    21. "avg_cost_per_task": total_cost / len(results),
    22. # Cost per successful task is a core metric for comparing model value
    23. "cost_per_passed_task": total_cost / max(len(passed), 1),
    24. "median_latency_s": statistics.median(r["latency"] for r in results),
    25. }

    When using this framework, keep several points in mind. First, the task set should cover the difficulty distribution of real business workloads; do not select only simple examples. Second, the judge function should be automated as much as possible and periodically sampled for human review. Third, fix the prompt version, temperature parameters, and context content for each test; otherwise, the results are not comparable.

    5. Capability Gains and Cost

    Model capability improvements usually have two effects. On one hand, they may reduce failures and rework, lowering cost per successful task. On the other hand, they may increase reasoning depth per call, raising the number of output tokens. The net effect must be confirmed through actual testing and cannot be inferred from capability scores alone.

    During selection, focus on the types of capability relevant to the business:

    • Code generation and modification: Can the model understand existing code structure and provide changes that compile and pass tests?
    • Security analysis: Can it identify common vulnerability patterns, provide remediation advice, and offer actionable hardening measures in defensive scenarios?
    • Multi-step agent tasks: Can it maintain goal consistency across long workflows, call tools correctly, and self-correct after errors?

    The more these capabilities depend on multi-turn reasoning, the more attention should be paid to changes in output tokens and call counts. For long-horizon tasks, a small increase in per-turn cost may be offset by fewer turns, or it may be amplified. End-to-end task cost must be the basis for judgment.

    6. Engineering Practices for Reducing Cost

    After a model is selected, there is still substantial room for optimization at the engineering level.

    6.1 Improve Cache Hit Rates

    Caching is usually based on prompt prefix matching. Place stable content (system instructions, tool definitions, fixed documents) at the front of the request and variable content (user input, real-time data) at the back to significantly improve hit rates. Avoid inserting timestamps, random IDs, or other fields that change on every request into the prefix.

    6.2 Control Output Length

    • Specify the answer format in the prompt, for example by requiring only JSON fields to be returned;
    • For tasks that do not need explanation, prohibit the model from outputting its reasoning process;
    • Set a reasonable maximum output token parameter to prevent abnormally long outputs;
    • For structured results, prefer constrained decoding or output schema validation to reduce retries.

    6.3 Tiered Routing

    Not every request needs the strongest model. A smaller model can handle simple requests first, escalating to a more capable model only when confidence is low or the task is complex. This routing strategy requires supporting evaluation data; otherwise, it may reduce cost while hurting quality.

    6.4 Monitoring and Budget Alerts

    Connect cost metrics to the monitoring system and break them down by feature module, user group, or tenant. Set daily budgets and per-task cost thresholds, and trigger alerts when they are exceeded. This helps detect cost spikes caused by prompt changes, abnormal inputs, or looping calls early.

    7. Selection Checklist

    1. Define business tasks clearly and prepare a representative set of test samples;
    2. Record input, cached input, and output unit prices for each candidate model;
    3. Run tests under the same conditions and measure pass rate, cost per task, cost per successful task, and latency;
    4. Check changes in output token counts and call counts, not just unit price;
    5. Evaluate the caching strategy and confirm whether the prompt prefix structure supports cache hits;
    6. Define tiered routing or fallback plans, and set cost monitoring and alerts;
    7. Re-evaluate periodically, because model versions, prices, and billing rules may all change.

    8. Conclusion

    LLM API cost is determined by unit price, usage, and number of calls. Even when unit price stays the same, growth in output token counts can still raise actual spend. A reliable selection method is to compare models by business task, measuring quality, cost per task, cost per successful task, and latency, then make decisions based on those results. At the same time, cache design, output control, tiered routing, and cost monitoring help teams keep costs under control as capabilities continue to change.