How to Reduce Agent Token Costs: A Practical Guide to Context Caching and Cost Optimization

    Agent workloads often spend over 90% of their tokens on input rather than output, which means optimizing where your money actually goes requires a shift in strategy. This guide explains why input-heavy token usage is normal for agents, how prompt prefix caching can dramatically reduce the cost of repeated context, and how to structure your requests for maximum cache hits. It also covers additional proven cost-saving techniques—including session isolation, context compression, tool definition cleanup, and controlled RAG injection—plus a decision framework for systematically cutting your LLM bill without sacrificing task quality.

    How to Reduce Agent Token Costs: A Practical Guide to Context Caching and Cost Optimization

    1. First, Understand Where Your Agent Actually Spends Tokens

    Many developers are surprised the first time they carefully audit an agent task’s bill. The assumption is that the most expensive part is the model’s long generated answers. In reality, the biggest cost usually comes from the input side—the system prompt, conversation history, tool definitions, and retrieved content that get sent to the model again on every turn.

    In typical long-running tasks, input tokens can easily account for over 90% of usage, while the model’s actual output is only a few percentage points. This structure means:

    • Simply making the model “talk less” doesn’t save much money;
    • The real optimization opportunity lies in reducing repeated input and improving the cache hit rate on input;
    • The longer the context, the more obvious the waste from repeated input—in the later stages of a long task, you’re paying for almost the same context on every single turn.

    Once you understand this, the optimization focus shifts from “compressing output” to “managing input.”

    2. A Counterintuitive Fact: High Input Ratios Are Normal

    At first, I also felt like I was getting ripped off and wanted to compress the context to the bare minimum on every turn. But after deeper analysis, I realized a high input ratio doesn’t mean the agent is poorly designed—it’s determined by the nature of the task itself:

    1. The model must “see” the full context to answer correctly. No matter how long the context is, it must be re-sent with every inference call. That’s how mainstream large language models work.
    2. Many tasks inherently require large amounts of background information. Codebase structure, business rules, historical decisions, tool lists—these are all prerequisites for correct output.
    3. Output is usually sparse. A code change may only need a few dozen lines, but it requires understanding tens of thousands of lines of context.

    So instead of agonizing over “why is there so much input,” accept this as the norm and focus on optimizing how input is billed.

    3. The Core Solution: Context Caching Discounts

    The main solution offered by model providers isn’t reducing the amount of input—it’s making repeated input prefixes billed at a steep discount.

    Here’s how it works: within a request, the model service caches the common prefix of the request (system prompt, conversation history, tool definitions, etc.). If the next request’s prefix matches the cached content, those tokens are billed at the cached rate—typically a fraction, sometimes as little as one-tenth to one-twentieth of the normal input price.

    This leads to a key conclusion:

    For agent tasks with highly repetitive context, even though input accounts for over 90% of tokens, if the cache hit rate also reaches around 90%, the actual input cost drops dramatically—ultimately, the effective input cost and output cost may end up in the same ballpark.

    Prerequisites for Cache Discounts

    1. The prefix must match exactly. Caching works by prefix matching—a single character change in the system prompt or the beginning of the context invalidates the cache. Put volatile content (timestamps, random IDs) at the end of the message list, and stable content at the beginning.
    2. The task must have continuity. Caches typically have a time-to-live; requests spaced too far apart will miss the cache. High-frequency, continuous sessions benefit the most.
    3. The context structure must be stable. Avoid rewriting history messages or reordering tool lists on every turn. A stable structure significantly improves hit rates.

    Here’s pseudocode showing a cache-friendly request structure:

    1. messages = [
    2. {"role": "system", "content": STABLE_SYSTEM_PROMPT}, # fixed, cache-friendly
    3. *history_messages, # appended, not rewritten
    4. {"role": "user", "content": new_user_input}, # volatile content goes last
    5. ]

    The following pattern, on the other hand, causes frequent cache misses:

    1. messages = [
    2. {"role": "system", "content": f"Current time: {now()}, session ID={uuid4()}"}, # changes every time, cache fully invalidated
    3. ...
    4. ]

    4. Let AI Analyze Your Own Bill: A Practical Self-Audit Method

    An easily overlooked trick: feed your model service’s usage logs, token statistics, and pricing rules to the model itself for analysis. Only it can see your complete call records—external tools often can’t access this data.

    Here’s how:

    1. Export your call logs for a period of time, including input tokens, cache-hit tokens, output tokens, and unit prices for each request.
    2. Feed the log summary along with the pricing rules to the model, and ask it to output:
      • The input/output token ratio;
      • Cache hit rate and guesses about why caches are missing;
      • Which sessions or tasks consume the most;
      • Targeted optimization suggestions.
    3. Verify the model’s suggestions one by one, then compare your bill before and after optimization.

    This process can also surface hidden problems—like a plugin injecting large amounts of repeated tool descriptions every turn, or a history message being accidentally rewritten and invalidating the cache.

    That said, you need to understand the underlying principles yourself; otherwise, you may blindly follow suggestions and run into pitfalls.

    5. Other Proven Token-Saving Techniques

    Beyond caching, several engineering practices are also effective:

    1. Start a New Session When There’s No Real Need for Continuity

    Long sessions accumulate context like a snowball. If a new task is unrelated to the old context (say, you’re switching to developing a different feature module), start a fresh session and let the context begin from zero. This is much cheaper than continuing to append in an overly long session.

    2. Actively Compress the Context

    Once the context grows past a certain point, you can:

    • Have the agent periodically summarize completed work, key decisions, and pending to-dos into a compact “state summary” that replaces verbose history messages;
    • Adopt a layered memory structure: keep recent messages in full, and only keep summaries of older messages;
    • Delete irrelevant intermediate processes (failed attempts, overly long tool outputs), keeping only the conclusions.

    3. Slim Down Plugins, Skills, and Tool Definitions

    Every plugin, skill, and MCP tool injects its own description and parameter schema into the context of every request—a hidden input cost. Audit for:

    • Tools not needed by the current task—remove them;
    • Tools with overlapping functionality—merge them;
    • Verbose tool descriptions and parameter documentation—trim them down to the minimum information the model needs to make correct calls.

    4. Control How Much Retrieved and External Content You Inject

    For RAG-style tasks, don’t stuff entire documents into the context. Use retrieval results for coarse filtering first, then inject only the needed fragments. Prioritize placing fixed, unchanging reference material in the prefix to capture caching benefits.

    6. A Decision Framework for Cost Optimization

    Here’s the above methods condensed into a simple decision flow:

    1. 1. Measure input/output ratio and cache hit rate
    2. ├─ Low hit rate → check prefix stability, session intervals, and message organization
    3. └─ High hit rates but absolute costs still high → proceed to step 2
    4. 2. Is the context still needed?
    5. ├─ Old content unrelated to the current task → start a new session
    6. └─ Still needed → apply summary compression and layered memory
    7. 3. Are tools/plugins redundant?
    8. └─ Remove unused tools and verbose descriptions
    9. 4. Can output be more concise?
    10. └─ Request structured, concise output formats (limited gains, but better than nothing)

    7. Conclusion

    An agent’s token cost structure dictates that optimization should focus on the input side: accept the high input ratio as the norm, maximize cache hit rates through a stable prefix structure, and combine that with task isolation, context compression, and tool cleanup to bring costs down without sacrificing task quality. For repetitive batch tasks, the cost difference from caching is especially significant.

    I recommend doing three things today: export your usage logs and have a model analyze your bill, check the prefix stability of your own requests, and clean out unused plugins once. None of these steps require changes to your business logic, yet you can see the impact on your bill immediately.