LLM API Costs for AI Agents: Why Cache Hit Rate Matters

    LLM API pricing alone does not reveal the cost of an AI agent workload. This article explains how cache hit rate and input-to-output token ratios determine effective costs, examines the infrastructure demands of long-context and mixture-of-experts models, and outlines practical ways to reduce spending through prompt structure, task routing, token budgets, and cost monitoring.

    1. Why Listed Token Prices Are Not Enough

    LLM APIs typically charge separately for input and output tokens. Input pricing is often further divided into cached and uncached tokens, producing three rates:

    • Uncached input price
    • Cached input price
    • Output price

    These rates do not necessarily change by the same amount. For example, output pricing may rise substantially while cached input pricing increases only slightly.

    Looking at the change in a single rate can therefore be misleading. The more useful question is: How does the actual cost per million tokens change for your workload?

    The answer depends on three factors: cache hit rate, the ratio of input to output tokens, and the price of each token category.

    2. How Cache Hits Change Effective Token Costs

    Let:

    • p be the uncached input price.
    • c be the cached input price.
    • o be the output price.
    • h be the input-token cache hit rate.
    • r be the input-to-output token ratio: r input tokens for every output token.

    All prices use the same currency per million tokens. For this calculation, the cache hit rate refers to the proportion of input tokens billed at the cached rate, rather than simply the proportion of requests that encounter a cache hit.

    The effective input price is:

    1. Effective input price = h × c + (1 − h) × p

    To spread the cost across all input and output tokens, calculate the blended price:

    1. Blended price = (r × effective input price + o) / (r + 1)

    This formula highlights two important points.

    First, cache hit rate directly determines the weighted input price, so it can have a substantial effect on costs.

    Second, when input tokens greatly outnumber output tokens, changes in input pricing can dominate the blended cost even if output pricing remains unchanged.

    The following Python code implements the calculation:

    1. def effective_input_price(p_miss, p_hit, hit_rate):
    2. """Weighted input price in CNY per million tokens."""
    3. return hit_rate * p_hit + (1 - hit_rate) * p_miss
    4. def blended_cost(p_miss, p_hit, p_out, hit_rate, ratio):
    5. """Blended price across all tokens; ratio is input tokens per output token."""
    6. p_in = effective_input_price(p_miss, p_hit, hit_rate)
    7. return (ratio * p_in + p_out) / (ratio + 1)
    8. # Scenario A: Enterprise agent with extensive reuse of a long prefix
    9. print(round(blended_cost(10, 1, 50, 0.9, 20), 2)) # 4.19
    10. # Scenario B: Occasional requests with different prompts each time
    11. print(round(blended_cost(10, 1, 50, 0.2, 5), 2)) # 15.17

    The prices in this example—CNY 10 for uncached input, CNY 1 for cached input, and CNY 50 for output, all per million tokens—are hypothetical. They illustrate the calculation and do not represent any actual product’s pricing. Use the provider’s published rates for real estimates.

    3. Cost Estimates for Two Common Workloads

    Scenario A: A Long-Running Enterprise Agent

    System prompts, tool definitions, and knowledge snippets remain unchanged across many requests, allowing extensive prefix reuse.

    Assume a cache hit rate of 90% and an input-to-output ratio of 20:1.

    1. Effective input price
    2. = 0.9 × 1 + 0.1 × 10
    3. = CNY 1.9 per million input tokens
    4. Blended price
    5. = (20 × 1.9 + 50) / 21
    6. ≈ CNY 4.19 per million total tokens

    Scenario B: A Developer Making Occasional Requests

    Prompts vary substantially between requests, leaving limited opportunity for cache reuse.

    Assume a cache hit rate of 20% and an input-to-output ratio of 5:1.

    1. Effective input price
    2. = 0.2 × 1 + 0.8 × 10
    3. = CNY 8.2 per million input tokens
    4. Blended price
    5. = (5 × 8.2 + 50) / 6
    6. ≈ CNY 15.17 per million total tokens

    The blended unit cost in Scenario B is approximately 3.6 times that of Scenario A. Cache reuse is a major contributor to the difference, but the input-to-output ratio also changes between the scenarios. Although the output rate is identical, output tokens carry a different weight in each blended calculation.

    These examples illustrate two practical lessons:

    1. The same price schedule can produce very different effective costs for different users.
    2. Engineering choices—such as keeping prefixes stable and standardizing request structure—can matter as much as, or more than, changes in listed prices.

    4. Where Long-Context Agent Costs Come From

    A conventional conversational interaction may use tens to thousands of tokens. An agent task can be much larger, involving hundreds or thousands of tool calls, with successive model requests carrying an increasingly long conversation history.

    This causes token consumption to accumulate rapidly. The underlying inference costs come primarily from four sources.

    Model Weight Memory

    Model parameters need to remain available in accelerator memory, with storage requirements proportional to parameter count.

    For example, a model with one trillion parameters requires approximately:

    • 1 TB for weights at one byte per parameter, such as 8-bit quantization.
    • 2 TB for weights at two bytes per parameter, such as 16-bit floating point.

    These figures describe weight storage, not the full memory requirements of serving the model.

    KV Cache Memory

    The key and value vectors associated with processed tokens are retained in the KV cache. Its memory footprint grows linearly with context length.

    Longer contexts therefore consume more memory per request, reducing the number of requests that can be served concurrently.

    Prefill Computation

    Prefill processes the input tokens before output generation begins. With full attention, attention computation grows approximately quadratically with sequence length.

    Architectures using sparse attention or combinations of linear and full attention are commonly used to reduce this growth.

    Decode Memory Bandwidth

    Generating each output token requires accessing model weights and the KV cache. Memory bandwidth is often a bottleneck, and longer contexts increase the KV cache burden.

    An individual agent step may be inexpensive, yet total task costs can grow superlinearly as both step count and context length increase.

    This is why prefix caching matters so much for agent workloads: reusable prefixes reduce repeated computation and, when billed at a cached rate, lower the effective input price.

    5. What Sparse Activation Means for Model Costs

    Mixture-of-experts, or MoE, models activate only a subset of their experts for each token. Their per-token computation can therefore be much lower than that of a dense model with the same total parameter count.

    However, hardware requirements do not fall in the same proportion. Three factors explain the difference.

    Weight Storage

    All expert weights must be available in accelerator memory or other accessible storage so that the router can select experts as needed.

    Sparse activation does not eliminate the storage requirements associated with the model’s total parameter count.

    Expert Routing Communication

    Experts are often distributed across multiple devices. Routing tokens to those experts introduces cross-device communication, whose overhead can increase as the deployment scales.

    Kernel Optimization

    Sparse computation, hybrid attention, and expert parallelism require specialized kernel optimization. Without effective implementation, theoretical reductions in computation may not translate into higher serving throughput.

    This distinction helps explain the cost structure behind provider pricing. A low active parameter count indicates less computation per token; it does not mean that deployment requirements or serving costs are negligible.

    6. Practical Engineering Measures to Reduce Costs

    Cost analysis should lead to system improvements. The following measures are applicable to many agent workloads.

    1. Keep Prefixes Stable and Put Dynamic Content Last

    Place system prompts, tool definitions, and fixed instructions at the beginning of the request. Put changing content, such as user input and retrieval results, after the stable prefix.

    Keep the reusable prefix identical and follow the provider’s cache-matching requirements.

    1. [Stable section] System prompt + tool definitions + fixed instructions
    2. Keep unchanged wherever possible
    3. [Dynamic section] Current time + user question + retrieved passages
    4. Place after the stable section

    2. Keep Volatile Information Out of the Prefix

    Timestamps, request IDs, and randomly ordered lists can cause an otherwise reusable prefix to change on every request.

    Move these elements toward the end of the prompt. Where structured fields are used, keep their format consistent and avoid placing changing values inside the reusable prefix.

    3. Route Tasks Across Model Tiers

    Use smaller, less expensive models for straightforward classification, extraction, and format conversion. Reserve the primary model for complex reasoning.

    Routing rules should reflect task type rather than prompt length alone.

    4. Limit Agent Steps and Output Length

    Set a maximum step count, a per-task token budget, and a per-step output limit, such as max_tokens.

    When a task exceeds its budget, stop execution and return intermediate results rather than allowing long-tail tasks to consume resources indefinitely.

    5. Compress Conversation History

    Summarize completed steps and retain only the information needed for subsequent decisions.

    This helps control context growth and reduces the KV cache footprint of later requests.

    6. Establish Cost Observability

    At a minimum, monitor:

    • Input-token cache hit rate
    • Average input and output token counts per request
    • Average number of steps per task
    • Average total cost per task

    Break these metrics down by functional module and user segment to identify the parts of the system responsible for high costs.

    7. How to Evaluate Pricing Changes

    Whether a price change benefits or harms your workload depends on how you use the API, not simply on whether one listed rate rises or falls.

    • High prefix reuse and input-heavy workloads: Effective costs may fall if the revised pricing favors cached input, potentially dropping below the previous level.
    • Highly variable requests with limited cache reuse: Effective costs may rise, especially for tasks in which output tokens account for a larger share of usage.
    • Long-running agent tasks: Total spending depends on step count, context growth, and caching strategy. Token prices are only one part of the calculation.

    The most reliable approach is to estimate costs using actual request logs.

    Group the previous month’s requests by function, model, and user segment. Use their token counts and cache usage to compare costs under different price schedules and engineering configurations.

    For an overall blended rate, aggregate total spending and total tokens rather than taking an unweighted average of request-level rates.

    A workload-based analysis provides a stronger basis for decisions than comparing headline price increases alone.