LLM API Cost Breakdown: Input, Output, and Cache Billing

    This article explains why changes in LLM API unit prices do not directly translate into changes in real cost. It breaks down billing for input tokens, output tokens, and cached input tokens, shows how to estimate cost per task with a Python example, and offers architecture and budget-management practices for controlling spend as model prices change.

    1. Why Unit Price Changes Do Not Equal Real Cost Changes

    Model price adjustments are a recurring event in the industry. Each adjustment prompts discussion, but looking only at the numbers in a price table makes it hard to judge what the change means for actual cost. To assess the impact of a price change, it helps to distinguish two concepts: unit price, meaning the billing rate per million tokens, and cost per task, meaning the actual cost of completing one business request.

    When unit price rises, cost per task does not necessarily rise in tandem. If a newer model can complete the same task with fewer tokens, or if one call can replace multiple calls, total cost may stay flat or even fall. Conversely, if model output is longer, the reasoning chain is more complex, or more retries are required, cost will rise even if the unit price does not change.

    Therefore, when evaluating a price change, focus on three metrics: unit price, average tokens consumed per task, and task success rate. The combination of these three—not unit price alone—is a useful cost indicator.

    2. Technical Meaning of the Three Billing Categories

    Most LLM APIs bill three types of tokens: input tokens, output tokens, and cache-hit input tokens. Understanding their billing differences requires a basic understanding of the inference process.

    1. Input Tokens and the Prefill Phase

    The prompt submitted by the user, including system instructions, conversation history, retrieved documents, and other content, is sent into the model at once during the prefill phase. This phase can be highly parallelized and is computationally efficient. The unit price of input tokens is usually lower than that of output tokens.

    2. Output Tokens and the Decoding Phase

    When the model generates a response, it produces tokens one by one autoregressively, and each generated token depends on all previous context. This phase is difficult to parallelize, and both the compute cost and latency per token are higher. As a result, the unit price of output tokens is generally significantly higher than that of input tokens.

    3. Cache Hits and KV Cache Reuse

    In multi-turn conversations or scenarios with long fixed prefixes, the same prefix is sent repeatedly. If the server can reuse the KV cache already computed for the prefix, it can skip repeated prefill computation. Cache-hit input tokens are therefore billed at a lower rate. This is a general inference optimization technique, and specific implementations and billing rules vary by service, so consult the relevant API documentation before use.

    These three billing categories reflect differences in the underlying computation. Understanding this helps teams actively control cost structure when designing systems.

    3. How to Estimate Cost per Task

    To judge the actual impact of a price change, you can use a simple model to estimate cost per task. The core formula is:

    Cost per request = (uncached input tokens × input unit price + cached input tokens × cache unit price + output tokens × output unit price) ÷ 1,000,000

    Below is a general Python example. The unit prices are hypothetical values used only to demonstrate the calculation method and do not represent the prices of any actual product.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. input_per_m: float # unit price per million uncached input tokens (CNY)
    5. output_per_m: float # unit price per million output tokens (CNY)
    6. cache_hit_per_m: float # unit price per million cache-hit input tokens (CNY)
    7. def estimate_request_cost(pricing: Pricing,
    8. avg_input_tokens: int,
    9. avg_output_tokens: int,
    10. cache_hit_ratio: float) -> float:
    11. """Estimate the cost of a single request in CNY.
    12. cache_hit_ratio is in [0, 1] and represents the share of input tokens that hit cache.
    13. """
    14. if not 0.0 <= cache_hit_ratio <= 1.0:
    15. raise ValueError("cache_hit_ratio must be between 0 and 1")
    16. cached = avg_input_tokens * cache_hit_ratio
    17. uncached = avg_input_tokens - cached
    18. cost = (
    19. uncached * pricing.input_per_m
    20. + cached * pricing.cache_hit_per_m
    21. + avg_output_tokens * pricing.output_per_m
    22. )
    23. return cost / 1_000_000
    24. def estimate_monthly_cost(pricing: Pricing, requests_per_month: int, **kwargs) -> float:
    25. return estimate_request_cost(pricing, **kwargs) * requests_per_month
    26. if __name__ == "__main__":
    27. old = Pricing(input_per_m=2.0, output_per_m=8.0, cache_hit_per_m=0.2)
    28. new = Pricing(input_per_m=10.0, output_per_m=40.0, cache_hit_per_m=1.0)
    29. # Assumed scenario: 3,000 input tokens, 800 output tokens, 60% cache hit rate per request
    30. scenario = dict(avg_input_tokens=3000, avg_output_tokens=800, cache_hit_ratio=0.6)
    31. for name, p in [("Old plan", old), ("New plan", new)]:
    32. monthly = estimate_monthly_cost(p, requests_per_month=100_000, **scenario)
    33. print(f"{name} estimated monthly cost: CNY {monthly:,.2f}")

    The key point of this code is to separate unit price, token consumption, and cache hit rate. In real scenarios, replace the assumed values in the example with average token counts and hit rates from production logs.

    Estimation Notes

    • Averages hide the long tail. A small number of very long requests may account for most of the cost, so track percentiles as well.
    • Output length is affected by the prompt. Clearly specifying the response format can effectively reduce the number of output tokens.
    • Retries and failed requests are also billed. Before launch, measure the failure rate and retry count.

    The billing advantage of cache hits only works when the prompt structure is designed well. Common practices include:

    1. Put fixed content first. Place system instructions, role settings, tool definitions, and other unchanged content at the beginning of the prompt, and place changing user input at the end to increase the probability of prefix hits.
    2. Control conversation history length. Apply rolling truncation or summarization to conversation history to avoid unbounded growth.
    3. Avoid meaningless changes. Inserting timestamps, random IDs, or other fields that differ on every request breaks prefix consistency and causes cache misses.

    An example structure is shown below:

    1. [Fixed part] System instructions + tool definitions + general rules ← high hit rate
    2. [Semi-fixed part] Session-level background material ← hit within the same session
    3. [Changing part] Current user question ← different each time

    This structure can improve cache hit rate and also makes it easier to locate the source of cost changes later when replacing models or adjusting prompts.

    5. Model Selection and Budget Management Recommendations

    Facing frequent price adjustments, technical teams can consider the following practices.

    1. Measure Value Against Business Metrics

    A low unit price does not mean high value. Test different models on your own business dataset, and record accuracy, human review pass rate, average token consumption, and latency. Then calculate the average cost per effective task, meaning total cost divided by the number of successfully completed tasks.

    2. Build an Abstraction Layer to Reduce Switching Cost

    Wrap model calls behind a unified service interface, with prompt templates, parameter configurations, and routing policies managed centrally. This keeps the scope of changes controllable when switching models or running canary comparisons.

    3. Set Up Usage Monitoring and Alerts

    It is advisable to monitor the following metrics:

    • Daily token consumption, split by input, output, and cache hits;
    • The trend of average cost per task;
    • The share of cost by individual user or feature module.

    Monitoring data can be integrated into common monitoring and alerting systems to notify teams promptly when costs are abnormal.

    4. Use Tiered Models

    Not every task requires the strongest model. Tasks with higher determinism, such as classification, extraction, and format conversion, can use smaller models, while complex reasoning tasks can be routed to higher-capability models. Tiered routing can usually significantly reduce cost without an obvious drop in overall quality.

    6. Conclusion

    Changes in model prices should be evaluated within a complete cost model. A unit price increase may be offset by higher task efficiency, or it may be amplified by longer output or more retries. Developers should understand the technical meaning of the three billing categories, estimate cost per task using production data, and control spending through prompt structure design, model tiering, monitoring, and alerts. Only by establishing this evaluation method can teams make stable technical and budget decisions in an environment of frequent price adjustments.