Beyond API Unit Prices: How to Calculate the True Cost of LLM Tasks

    Estimating the actual expenses of Large Language Model (LLM) APIs based solely on the per-million-token price is insufficient. This article explains how to calculate true single-task costs by factoring in actual token consumption, billing weights, cache hit rates, and failure retries. It provides a practical framework, Python code examples, and an evaluation process to help developers balance model capability and cost.

    1. Unit Price is Only the Entry Point for Costs

    LLM APIs typically bill by token, with dimensions usually including uncached input, cached input, and output tokens. A unit price table is useful for horizontal comparison of base pricing across services, but it cannot answer the question: “How much does it cost to complete a specific task?” With identical unit prices, different task structures can cause actual expenditures to vary by several multiples.

    A common pitfall during model selection is looking only at the per-million-token price and estimating the budget by intuition. This approach ignores two key variables: the actual number of tokens consumed to complete a task, and the billing weight of different token types. If either variable changes, the final bill will deviate from expectations.

    Therefore, a more reasonable metric for comparing model costs is single-task cost—the total expense incurred to achieve a complete business objective.

    2. A Calculation Framework for Single-Task Cost

    Single-task cost can be broken down into three components:

    Single-Task Cost = Uncached Input Tokens × Input Price + Cached Input Tokens × Cached Price + Output Tokens × Output Price

    (Note: The prices in the formula above refer to the price per million tokens. The calculation result must be divided by 1,000,000.)

    The following function implements this calculation. Price parameters should be obtained from the service provider’s pricing page and updated alongside version changes:

    1. def estimate_task_cost(input_tokens, output_tokens, cached_tokens,
    2. price_in, price_out, price_cached):
    3. """
    4. Calculate the cost of a single API call.
    5. Price parameters are the unit prices per million tokens.
    6. cached_tokens represents the portion of input that hit the cache,
    7. and must not exceed input_tokens.
    8. """
    9. if cached_tokens > input_tokens:
    10. raise ValueError("Cached tokens cannot exceed input tokens")
    11. uncached = input_tokens - cached_tokens
    12. cost = (uncached * price_in
    13. + cached_tokens * price_cached
    14. + output_tokens * price_out)
    15. return cost / 1_000_000

    This function only describes the billing logic and does not contain any specific prices. In actual projects, price configurations should be kept in a separate configuration file or environment variables to facilitate model switching and price updates.

    3. Why Output Tokens Have a Greater Impact

    The unit price of output tokens is generally higher than that of input tokens, and the fluctuation in output length is often larger. Models generate output content token by token; the verbosity of the response, formatting requirements, and whether intermediate reasoning steps are included will all alter the output length.

    Consider a hypothetical example to illustrate this impact. Suppose the output price is four times the input price. A task uses 20,000 input tokens and 5,000 output tokens. Treating the input price as 1 unit, the task cost is:

    • 20,000 × 1 + 5,000 × 4 = 40,000 units

    If the model’s output increases by 20% to 6,000 output tokens, the cost becomes:

    • 20,000 × 1 + 6,000 × 4 = 44,000 units

    A 20% increase in output tokens results in a 10% increase in total cost because the input portion remains constant. The higher the proportion of output in the total cost, the more pronounced the impact of output length variations on cost.

    This leads to two practical conclusions. First, even if the unit price remains unchanged, a longer required output for a task will drive up actual spending. Second, when evaluating models, you should track both the unit price and the average output token count per task; both are indispensable.

    4. Cache Hits and Multi-Step Tasks

    Cache hits reduce the cost of the input portion. When the same prefix content appears repeatedly across multiple calls, the server can reuse pre-computed results, and the corresponding input is billed at a lower cached price.

    Multi-step tasks, such as AI agent workflows requiring multiple rounds of tool calls, rely heavily on caching. Each step typically involves resending the previous context to the model. If the context contains a large amount of stable, unchanging content, the cache hit rate will be high. Conversely, if the prefix is altered at each step, caching will barely take effect.

    To improve cache hit rates, follow these practices:

    1. Place stable content—such as system instructions, tool definitions, and fixed examples—at the very beginning of the prompt.
    2. Place variable content like user inputs, retrieval results, and timestamps at the end.
    3. Avoid inserting dynamic fields like random numbers or session IDs into the prefix.
    4. Record the cache hit token count returned by each API call and periodically check the actual hit rate.

    Note that cache expiration, hit conditions, and minimum cache length vary by service. Before deployment, consult the official documentation and verify the actual effect using real traffic.

    5. Balancing Capability Improvements and Costs

    Improved model capabilities do not necessarily mean higher costs; they can even lead to lower costs. A more capable model might complete tasks in fewer steps or with fewer retries, reducing total spending. However, it might also generate longer, more detailed outputs, offsetting those savings.

    Therefore, when comparing different models, introduce the “Cost Per Successful Task” metric:

    Cost Per Successful Task = Total Cost of All Tasks / Number of Successfully Completed Tasks

    The key to this metric is that the numerator includes the costs of failed tasks. A model with very cheap single calls but a high failure rate requiring constant retries might end up with a much higher cost per successful task than a more expensive but reliable model.

    6. Building Your Own Cost Evaluation Process

    A general evaluation process can be divided into the following steps:

    1. Build an evaluation set: Extract representative tasks from real business scenarios, covering common cases and edge cases. The volume should be sufficient to reflect distribution characteristics.
    2. Fix experimental conditions: Use the same prompts, tool configurations, and evaluation criteria for all candidate models.
    3. Record details: For each call, log input tokens, output tokens, cached tokens, latency, and whether the result was successful.
    4. Calculate metrics: Compile single-task cost, cost per successful task, average latency, and success rate.
    5. Comprehensive decision-making: Combine cost, quality, latency, and stability to select the most suitable solution for your business.

    The following code example demonstrates how to calculate the cost per successful task based on call logs:

    1. def cost_per_success(runs, price):
    2. """
    3. runs: A list where each element contains calls (a list of call details) and success (a boolean).
    4. price: A dictionary containing the in, out, and cached unit price fields.
    5. """
    6. total_cost = 0.0
    7. successes = 0
    8. for run in runs:
    9. for call in run["calls"]:
    10. total_cost += estimate_task_cost(
    11. call["input"],
    12. call["output"],
    13. call["cached"],
    14. price["in"],
    15. price["out"],
    16. price["cached"],
    17. )
    18. if run["success"]:
    19. successes += 1
    20. if successes == 0:
    21. return float("inf")
    22. return total_cost / successes

    This function sums the costs of all runs—including failed ones—and divides by the number of successes. Callers can use the same evaluation set to calculate multiple candidate solutions and directly compare the results.

    When evaluating, also consider sample size. Success rates and average costs with small sample sizes can fluctuate significantly, leading to unstable conclusions. It is recommended to run the entire evaluation set for each solution at least once, and calculate confidence intervals or standard deviations across multiple repeated experiments for key metrics.

    7. Common Pitfalls

    In cost evaluation, the following issues frequently occur:

    • Comparing only unit prices while ignoring the token consumption per task.
    • Drawing conclusions based on a small number of examples without covering long-tail scenarios.
    • Ignoring fluctuations in output length, looking only at averages without paying attention to extremes.
    • Overlooking extra calls caused by failure retries.
    • Estimating costs based solely on pricing pages without measuring cache hit rates with real traffic.
    • Evaluating once and never reviewing again, while service prices and model versions can change over time.

    The key to avoiding these issues is treating cost as an engineering metric that requires continuous monitoring, rather than a one-time selection conclusion.

    8. Conclusion

    Determining whether an LLM service is cost-effective should start with single-task cost rather than just unit price. Core steps include breaking down the cost formula, monitoring output length variations, increasing cache hit rates through stable prefixes, and using cost per successful task to measure the balance between capability and spending, while establishing a repeatable evaluation process. After completing these steps, teams can compare different solutions using the same dataset and make rapid adjustments when model versions or prices change.