LLM API Selection: Calculating Cost per Task Beyond Unit Prices

    This article explains why comparing per-token unit prices alone can lead to the wrong choice of LLM API. It covers how to break down billing for uncached input, cached input, and output tokens, how to calculate cost per task and cost per successful task with retries and multi-step calls included, and how output length affects the bill. It also describes engineering methods for controlling output length, a metric table for weighing capability against cost, and practical steps to take before launch.

    1. Why Unit Prices Alone Lead to Wrong Cost Estimates

    Most APIs charge per million tokens and separate pricing into three categories: uncached input, cached input, and output. When selecting a model, many teams compare only these unit prices and conclude which option is cheaper. This approach has two blind spots.

    First, the number of tokens needed to complete the same task is not fixed. For the same request, different models may generate responses of very different lengths, and the intermediate output produced during reasoning may also vary. Output tokens usually have the highest unit price, so a small change in output volume can noticeably increase the bill.

    Second, a model with a lower unit price is not necessarily cheaper. If a model requires more call rounds, more retries, or a longer context to produce a usable result, the total cost increases accordingly.

    A more useful metric is cost per task, which is the sum of all costs incurred to complete one full business task. If you only want to consider successful tasks, use cost per successful task: total cost divided by the number of tasks that pass acceptance.

    2. Breaking Down the Billing Structure

    The cost of a single call can be calculated as follows:

    Cost = uncached input tokens × uncached input price + cached tokens × cached input price + output tokens × output price

    The three billing items each have distinct characteristics:

    • Uncached input tokens: These include prompts, conversation history, and retrieved document snippets. The longer the context, the larger the share of this category.
    • Cached tokens: When the prefix of a request matches recent requests, the server can reuse previously computed parts and bill them at a lower price. The actual cache hit rate depends on whether the prefix is stable. Placing fixed system instructions and tool definitions at the beginning of a request, and dynamic content at the end, helps improve the cache hit rate.
    • Output tokens: Their unit price is usually higher than the input price, and they are directly affected by generation length.

    Cache rules and discount levels vary widely between providers. Refer to the official pricing pages and billing documentation for each provider, and record the date on which you checked the prices.

    3. Calculating Cost per Task in Code

    The example below implements single-call billing and task-level statistics separately. input_tokens is the total number of input tokens in a request, and cached_tokens is the portion served from the cache.

    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. @dataclass
    8. class CallUsage:
    9. input_tokens: int # Total input tokens in this request
    10. cached_tokens: int # Number of input tokens served from the cache
    11. output_tokens: int # Output tokens generated in this call
    12. def call_cost(usage: CallUsage, price: Pricing) -> float:
    13. uncached = usage.input_tokens - usage.cached_tokens
    14. total = (
    15. uncached * price.input_per_m
    16. + usage.cached_tokens * price.cached_per_m
    17. + usage.output_tokens * price.output_per_m
    18. )
    19. return total / 1_000_000
    20. def cost_per_success(
    21. tasks: list[tuple[list[CallUsage], bool]],
    22. price: Pricing,
    23. ) -> float:
    24. """Each item in tasks is (all call records for the task, whether the task passed acceptance)."""
    25. total = 0.0
    26. successes = 0
    27. for calls, passed in tasks:
    28. total += sum(call_cost(c, price) for c in calls)
    29. successes += int(passed)
    30. if successes == 0:
    31. raise ValueError("No tasks passed acceptance, so cost per successful task cannot be calculated")
    32. return total / successes

    The key point of this code is that retries and multi-step calls are counted toward the same task. Counting only the cost of individual calls underestimates the real cost.

    4. Why Output Length Deserves Separate Attention

    Assume two options have the same unit prices, but Option B generates about 20% more output tokens per task. The following numbers only illustrate the calculation method. They do not represent any actual prices.

    • Option A: 20,000 input tokens and 10,000 output tokens per task. The input price is CNY 1 per million tokens, and the output price is CNY 4 per million tokens. The output cost is CNY 0.04, and the total cost is CNY 0.06.
    • Option B: Output increases by 20%, to 12,000 tokens. The output cost becomes CNY 0.048, and the total cost becomes CNY 0.068.

    The unit prices did not change, but the cost per task increased by about 13%. Output length is an independent variable that affects the bill, so it should be monitored separately during model selection.

    5. Engineering Methods for Controlling Output Length

    1. Constrain the output format: Require the model to return only specified fields, such as a JSON structure, to avoid long explanatory text.
    2. Limit intermediate output: Set upper limits on the intermediate conclusions you need to keep, and return only the necessary results to downstream components.
    3. Retrieve before generating: For long documents, run retrieval or summarization first, and include only the relevant snippets in the context to reduce irrelevant input.
    4. Set an output cap: Use max_tokens as a safeguard, and monitor the truncation rate. Truncation often leads to retries, which increase costs.
    1. MAX_OUTPUT_TOKENS = 1024
    2. def ask(client, prompt: str):
    3. # client is a general-purpose call wrapper built in the project; the interface depends on the actual implementation
    4. response = client.generate(prompt=prompt, max_tokens=MAX_OUTPUT_TOKENS)
    5. if response.truncated:
    6. log_event("output_truncated", prompt_head=prompt[:80])
    7. return response

    6. Balancing Capability and Cost

    Improvements in model capability usually mean a higher task pass rate, but they may also come with longer outputs. Judging whether an upgrade is worthwhile requires looking at both quality and cost.

    Metric Meaning Use
    Cost per call Unit price multiplied by usage Daily budget monitoring
    Average output tokens Generation length per task Detecting output inflation
    Task pass rate Share of tasks that pass acceptance Checking whether quality meets the target
    Cost per successful task Total cost divided by the number of passing tasks Final basis for selection

    To compare options, first check quality. If two options have similar quality, compare their cost per successful task directly. If the quality gap is clear, plot quality and cost on the same chart and observe which option costs less at or above the target quality level.

    7. Recommendations Before Launch

    • Build a fixed evaluation set: Collect 50 to 200 representative tasks that cover common scenarios and edge cases. Run regression tests on the same set whenever you change models or adjust prompts.
    • Record pricing versions: Save the prices, dates, and cache rules used in each evaluation so you can review them later.
    • Run a small-traffic canary: Route a small share of traffic to the new option first, compare cost per successful task and pass rate, and increase traffic gradually once the results check out.
    • Set cost alerts: Configure thresholds by day and by feature module. Send notifications when cost per task or average output tokens exceed the baseline.
    • Verify the caching strategy: After changing prompt structure, check whether the cache hit rate has dropped, so costs do not rise unnoticed.

    8. Conclusion

    Unit price is only one part of API cost. Cost per task is determined by unit prices, cache hits, input size, output length, and the number of retries. Teams should use cost per successful task as their core metric, measure quality with a fixed evaluation set, and keep costs under control by monitoring output length and cache hit rates. When models reach similar capability levels, the team that can reliably complete tasks with fewer tokens has the cost advantage.