How to Cut AI Agent Token Costs: A Practical Guide to Context Caching
AI agents can burn through millions of tokens on a single task because every loop resends the full context. This article explains why input tokens dominate agent bills, how prompt caching discounts change the cost equation, and six practical ways to reduce spending—stabilizing the cache prefix, splitting task threads, compressing history, trimming tool declarations, controlling read granularity, and shortening outputs. It also covers observability metrics and context budget circuit breakers.
1. Read the Bill First: Why Agents Burn Through Millions of Tokens
Many developers get a shock the first time they attach a weaker model to a coding tool and run a long task: a single question ends up consuming millions of tokens in the background. This is not a metering error. It is an inevitable result of how agents operate.
An agent does not work in a simple “one question, one answer” fashion. It runs a loop of observe, reason, act, and observe again. Every iteration reassembles the system prompt, tool definitions, conversation history, files already read, and command output into one complete request. The more turns a task takes, the more context gets carried forward repeatedly.
A typical long-task request body looks roughly like this:
[system prompt + tool/skill declarations] # repeated every turn[message history and reasoning trace] # grows linearly per turn[newly read files/logs/errors this turn] # can be large in a single turn--------------------------------= input tokens this turn (usually 90%+ of the total)output tokens this turn (usually a single-digit percentage)
The conclusion is counterintuitive but important: for coding tasks, the biggest cost is feeding context to the model, not the answer the model gives you.
2. A Human Analogy: Heavy Input, Light Output Is Normal
This structure closely resembles how people solve complex problems. The first step of a multi-part problem is reading the question, organizing the conditions, and looking up references; the final answer is often just a number or a short conclusion. Writing a paper is even more extreme: loading the literature up front can take weeks, while the time actually spent “producing the conclusion” might be ten minutes.
So a high input share is not waste. It is determined by the information density of the task itself. Most tasks need sufficient input to produce a correct output. What actually needs optimizing is not “reducing input” in itself, but reducing repeated and cheap input.
3. The Vendor Approach: Don’t Cut Input, Discount Cache Hits
The pricing strategies of mainstream cloud providers and model services generally do not lower the input unit price. Instead, they offer steep discounts on the context cache hit portion. A common industry practice is to bill the cached portion at roughly one-tenth of the input unit price, with some platforms discounting even more aggressively.
This leads to a key inference: in long tasks, if the prefix of each request (system prompt, tool declarations, files already read) stays consistent, the cache hit rate can usually be very high. Let the input unit price be 1, the cache discount be d, and the hit rate be h. The effective input cost is approximately:
effective input cost ≈ input volume × [h × d + (1 - h) × 1]
With h = 0.9 and d = 0.1, the coefficient is about 0.19; in other words, ninety percent of the input is billed at less than two-tenths of the price. Even though input accounts for ninety percent of the tokens, the actual cost may be on par with the output. This explains why a bill that “looks disastrous” often turns out to be acceptable.
The inference is also clear: caching is the gateway to the discount, and any behavior that breaks prefix stability voids the discount.
4. Cost-Reduction Measures That Actually Work
1. Preserve the stability of the cache prefix
Move volatile content out of the front of the prompt. Timestamps, random request IDs, live retrieval results, and user input should all go at the tail of the request body; the system prompt and tool declarations should stay byte-for-byte identical. Example:
def build_request(system_prompt, tools, history, volatile):# keep the stable prefix first and volatile content last to maximize cache hitsprefix = system_prompt + serialize(tools) + historyreturn {"messages": prefix + [volatile]}
2. Split task threads by “continuity needs”
Exploration, format conversion, and single-file fixes that have no real context dependency should start a new session instead of being appended to a long-running one. The test is simple: does the next step truly need the raw content of the previous one? If not, reopen.
3. Compress proactively and use structured summaries
In the mid-to-late stages of a long task, have the agent archive history into a structured summary (goal, confirmed facts, ruled-out approaches, to-dos) and let only the summary carry into subsequent turns. Compression is not discarding information; it is swapping the “original text” for the “conclusions.”
4. Trim tool, skill, and extension declarations
The schema of every tool, skill, and extension enters the fixed prefix of every request. Removing low-frequency tools and loading on demand instead of registering everything is the optimization with the most direct payoff and the lowest risk.
5. Control read granularity per call
Use retrieval to locate content instead of reading whole files. Read by line range or by symbol, and avoid pouring large blocks of irrelevant code into the context.
6. Make output “shorter and more precise”
Constrain the output format (patches, JSON, diff lists) and reduce long explanatory prose. The output-side unit price is usually the highest, so compression there pays off immediately.
5. Observability: Measure Before Optimizing
Optimization must be built on measurement. It is advisable to connect logging and monitoring/alerting services and collect four metrics per session:
input_tokens / cached_tokens / cache_hit_rate / cost_per_task
Without the cache hit rate metric, any cost reduction is guesswork. A practical diagnostic order is: first check whether the hit rate is below expectations, then check whether single-turn input is abnormally inflated, and finally inspect the number of tool declarations and the read granularity.
6. Engineering Practice: Context Budgets and Circuit Breakers
Managing context as a finite resource is the key to long-term control.
class ContextBudget:def __init__(self, max_tokens, soft_limit=0.7):self.max, self.soft = max_tokens, int(max_tokens * 0.7)def should_compress(self, used):return used >= self.softdef should_fork_new_task(self, used):return used >= self.max * 0.9
Three supporting policies: a soft threshold triggers summary compression; a hard threshold triggers a new task thread; when a single task exceeds its cost budget, trip a circuit breaker and emit intermediate artifacts to avoid “the bill running out of control halfway through.”
7. Common Pitfalls
- Blindly switching to a cheaper model: a weaker model often needs more correction turns, so total tokens actually rise.
- Frequently tweaking the system prompt: this punches straight through the cache and zeroes out the discount.
- Stuffing all material in at once: both hit rate and accuracy drop.
- Looking only at total tokens and not the hit rate: you cannot locate the source of the cost.
8. Conclusion
The essence of agents burning tokens is that long context gets carried back and forth repeatedly. The core of cost reduction is not feeding less information, but making repeated prefixes hit the cache, archiving irrelevant history promptly, keeping tool declarations lean, and making cost observable and able to trip a circuit breaker. Do these four things, and ninety percent input can still be billed at a fraction of the price. To support this collection and alerting capability, you can build it yourself on Baidu AI Cloud using general-purpose logging services, monitoring and alerting, and container platforms, forming a cost loop that can be optimized continuously.
