How to Cut Token Usage in AI Coding Agents by 70% Without Changing Models
AI coding agents can burn through tokens quickly because a single task often spans dozens of model calls, and any redundancy in each call gets multiplied across every turn. This article shows how adjusting context management and tool-calling strategies alone—without swapping or fine-tuning the underlying model—can reduce token consumption by up to about 77%. It covers a simple cost model, the five most common ways tokens get wasted, five core principles for context hygiene, five practical implementation strategies (layered context, reference-based tool returns, context budgets, prompt caching, and finer tool control), how to measure the gains against a real bill, and how to turn context governance into a platform capability. It also walks through common pitfalls to avoid.
1. The phenomenon: same model, yet over 70% fewer tokens
Developers discussing AI coding tools have recently noticed a striking pattern. Without changing the underlying model at all, simply adjusting context management and tool-calling strategies can cut token consumption by as much as about 77%.
This finding is worth attention for three reasons:
- The cost structure has shifted. In agent-style applications, a single task is often made up of dozens of model calls. Even a small amount of redundancy per call gets multiplied by the number of calls into a visible gap on the bill.
- The way to optimize has shifted. Context and tool-calling live at the application layer, so tuning them costs far less than switching or fine-tuning a model, and it does not require re-running a large-scale quality evaluation.
- A common bias is broken. When teams hit cost problems, their first instinct is to switch to a cheaper model, or simply drop to a smaller one—overlooking that the most direct waste happens inside the agent loop they wrote themselves.
1.1 Start with a quantitative model
Every optimization starts with measurement. The cost of a single agent task can be approximated as:
Total task cost ≈ Σ (for turn i: input tokens × input price + output tokens × output price)
Where:
- Input tokens = system instructions + tool definitions + conversation history + user request + tool return results
- Output tokens = the model’s reasoning, responses, and tool-call arguments
In an agent loop, input tokens usually make up the vast majority, and within each turn’s input, the history portion grows roughly linearly with the number of turns.
1.2 Run the numbers: how brutal the compounding effect is
Take a simplified illustrative scenario (the numbers are only to explain the principle, not measured data):
- The model receives a user task and enters a “plan → call tool → read result → decide again” loop for a total of 20 turns.
- Each tool call returns about 2,000 tokens on average (directory listings, file contents, command output, and so on).
- To simplify, we ignore model output and the multi-turn dialogue in the planning phase for now.
With no trimming of history whatsoever, the input tokens that must be resent at turn i are roughly 2,000 × i. The total input tokens across the whole task are:
2000 × (1 + 2 + … + 20) = 2000 × 210 = 420000
But if you apply just one lightweight step after each tool return:
- Truncate overly long output;
- Keep only the key information;
- Write large raw content to a temporary file and leave only the file path in the conversation.
Assuming each turn can be compressed to 500 tokens, the total drops to:
500 × 210 = 105000
Input volume drops by 75% directly—while the model, the reasoning process, and even the tool-calling actions in each turn stay unchanged.
Key takeaway: The rate at which agent cost grows is driven by the number of accumulated turns, so any redundancy introduced per turn gets amplified by the “turn count.” Save 1,000 tokens in a single turn, and across a multi-turn task you may save tens of thousands.
1.3 Don’t be misled by the “77%” figure
That ratio comes from a before-and-after comparison on a specific project; it is not a universal benchmark. The actual reduction depends on at least the following factors:
| Factor | Usually larger reduction | Usually smaller reduction |
|---|---|---|
| Number of calls | Multi-turn loops, ongoing exploration | Task finishes in one or two turns |
| Tool output characteristics | Verbose, low-structure output | Short output, high information density |
| Context growth | History accumulates without bound | Fixed window, trimmed early |
| Cache hit rate | No caching or low hit rate | Prompt caching already hits reliably |
| Output ratio | Input dominates | Output dominates |
More importantly, saving tokens does not equal saving money. Many platforms use different pricing rules for cached-hit portions, regular input, and output—check the pricing documentation of the platform you use. When evaluating savings, base them on the real bill, not just token counts.
2. How tokens get “wasted”: five typical problems
2.1 Full history: the most common waste
The most common pattern is to splice the entire conversation history into every request as-is:
messages = [{"role": "user", "content": task}]while not done:response = call_model(messages + tools)result = execute_tool(response)# Append the tool return straight into history, with no processingmessages.append(response)messages.append({"role": "tool", "content": result})
After a few turns, messages ends up piling together:
- Historical steps that finished long ago;
- Large chunks of source code for each file;
- Output from commands that were run repeatedly;
- Intermediate reasoning and trial-and-error.
The contribution of this information to future decisions is decaying quickly, yet every turn resends it unchanged—driving up cost and possibly diluting attention, which increases the risk of wrong decisions.
2.2 Full tool-return backfill
Directory listings, logs, search results, command output, and the like, if returned as-is, tend to cause three problems:
- Volume: a single directory listing or log query can bring back thousands of tokens;
- Noise: much of the content is irrelevant to the current task;
- Not addressable: the model sees a pile of raw text but cannot “look back precisely” at a specific segment in later turns.
More subtly, many tools return a human-friendly format—generous indentation, verbose headers, repeated field names. Most of this can be dropped for a machine.
2.3 Tool definitions permanently occupy context
System prompts and tool definitions usually sit at the very front of the context and get resent every turn. If the tool list swells to dozens or even hundreds of entries, the tool descriptions alone can consume a sizable fixed overhead, and they also dilute the model’s attention to the key instructions.
2.4 Ineffective retries and repeated reads
When tool returns are insufficient or poorly formatted, the model tends to call the same tool repeatedly, retry with different arguments, or re-read files it has already read. This both adds turns (the compounding effect kicks in again) and creates more redundant context.
2.5 No budget and no observability
Many agent loops set no token budget and log no per-turn usage. Developers can only wait until the end of the month to see the bill, without being able to say which task, which step, or which tool is consuming tokens. Without measurement, optimization has nowhere to start.
3. Five core principles
The root of all the problems above is treating the “context window” as a sheet of scratch paper you can write on freely. In reality, it is a scarce, expensive, and limited attention resource—every irrelevant piece of information you add squeezes out the space the model has to process what matters.
Principle 1: References over pastes
Whenever you can put a “pointer” in the context, don’t put the “body”:
- Use a file path instead of the full file contents;
- Use a task ID or record ID instead of a large block of raw results;
- Use a “completed list” instead of a verbose process log.
The raw content always stays in files, object storage, or a search index, and gets read back precisely when needed.
Principle 2: Hot/cold layering, retrieve on demand
Layer the context by “probability of being needed again”:
| Layer | Example content | Retention strategy |
|---|---|---|
| Hot data | Current task goal, recent results, key constraints | Always keep |
| Warm data | Earlier steps, completed subtasks | Compress to conclusions and key points |
| Cold data | Large raw text, full logs, intermediate reasoning | Store externally, read back on demand |
Cold data does not disappear; it just changes from “carried every turn” to “fetched when needed.”
Principle 3: Structured, compact expression
The same piece of information can cost several times more tokens depending on how it is expressed. Prefer:
- Structured fields (JSON, key-value pairs);
- Compact formats (drop irrelevant indentation and decoration);
- Key-field summaries (keep only the status, paths, line numbers, error codes, and other information needed for decisions).
Principle 4: Give the context a “budget”
Manage the context like memory, reserving separately defined limits for system instructions, tool definitions, summaries, recent dialogue, tool returns, and output. Once a limit is exceeded, automatically trigger compression or externalization—rather than finding out only when an error tells you the window has overflowed.
Principle 5: Observable and attributable
Log the input and output tokens, cache-hit status, latency, and tool-call count for every model call, and aggregate the analysis by task and by tool. Only when you know where the money goes can you know where to save it.
4. Five practical strategies
Strategy 1: Hot/cold layering—turn history into “summary + recent raw text”
Instead of carrying the full history, use a three-tier structure:
- Long-term memory: the task goal, key constraints, and decision conclusions, compressed into a fixed-length summary that is updated each time;
- Recent raw text: the most recent several turns of dialogue and tool returns kept as-is, so the model has the latest details;
- Archive: older content written to a file or external storage, keeping the summary and locator information for reading back when needed.
The following is illustrative code to explain the idea (pseudocode style, with framework specifics omitted):
class ContextManager:def __init__(self, window=4, budget=6000):self.window = window # number of recent turns to keep verbatimself.budget = budget # token ceiling for recent contextself.summary = [] # long-term summary (task-level)self.recent = [] # recent messagesself.usage = 0 # budget already useddef add(self, msg):cost = estimate_tokens(msg)# A single oversized message: compress first, and if needed write it# to external storage and keep only a referenceif cost > self.budget // 2:msg = compress_large(msg)cost = estimate_tokens(msg)self.recent.append(msg)self.usage += cost# Over budget: pop the oldest message, compress it to a summary, move it outwhile (self.usage > self.budgetor len(self.recent) > self.window):old = self.recent.pop(0)self.summary.append(to_summary(old))self.usage -= estimate_tokens(old)def build_prompt(self, system, task):return (system+ format_summary(self.summary)+ format_messages(self.recent)+ task)
The key is the combination of “rolling updates + budget constraints”:
- Sliding window alone may drop key constraints such as the early task goal;
- Full summary alone may lose implementation details.
Only when the two work together can you shrink the volume while preserving decision quality.
Strategy 2: Reference-based tool returns—keep only pointers in context
Take an AI coding tool as an example. Tools that read files, list directories, and run commands are the most likely to produce verbose returns. Adjust them along a “observe first, then fetch” approach:
| Scenario | Crude approach | Optimized approach |
|---|---|---|
| Browse a directory | List all subdirectories and files at once | Return only the top-level structure first, expand on demand |
| Read a file | Return the entire file contents directly | Return a summary + key line numbers, read specific lines on demand |
| Run a command | Return full stdout/stderr as-is | Truncate, deduplicate, keep only errors and key lines |
| Search logs | Paste a large block of raw logs into the context | Return the hit count and a summary, expand on demand |
| Large object | Stuff the content into the dialogue after writing it to a variable | Write to a temporary file or object storage, pass only the path/ID |
There is only one criterion for the judgment: Can the model make the next decision based on this turn’s return alone? If yes, stop right there; if not, fetch the details on demand.
You can also pair this with “output-location” tools (read by line/column range, modify by line number, and so on) to move the model from “read whole blocks” to “locate precisely,” reducing pointless shuffling at the source.
Strategy 3: Context budget + automatic degradation
Before building the request, do a “budget allocation” first:
def build_context(ctx: ContextManager, system, tools, task, limit):sections = {"system": system,"summary": format_summary(ctx.summary),"recent": format_messages(ctx.recent),"tools": format_tools(tools),"task": task,}usage = {k: estimate_tokens(v) for k, v in sections.items()}# Guarantee fixed overhead first: system instructions and tool definitions can't be cutfixed = usage["system"] + usage["tools"]if fixed > limit * 0.5:# When there are too many tools, enable grouped loading: inject only# the tool definitions relevant to the current tasktools = select_tools(tools, task)sections["tools"] = format_tools(tools)usage["tools"] = estimate_tokens(sections["tools"])# Compress the history on demand until the total falls within budgetwhile sum(usage.values()) > limit and ctx.recent:ctx.summary.append(to_summary(ctx.recent.pop(0)))usage["summary"] = estimate_tokens(format_summary(ctx.summary))usage["recent"] = estimate_tokens(format_messages(ctx.recent))return sections, usage
Beyond a total budget, you can set additional constraints:
- Maximum number of turns: prevent the loop from failing to converge;
- Per-turn output limit: stop the model from generating overly long content in one go;
- Per-tool return limit: auto-truncate or externalize anything over the limit.
These constraints let the system run with predictable costs, rather than “finding out what it cost only after it finishes.”
Strategy 4: Stable prefix + prompt caching
Most mainstream LLM services offer prompt caching: when a request prefix is identical to a previous one, that portion does not need to be recomputed. The benefits of this mechanism usually include two aspects:
- The cached-hit portion is usually billed at a lower price;
- The cached-hit portion does not need to be recomputed, so the time to first token (TTFT) is shorter.
This requires the context layout to follow a “stable prefix, dynamic suffix” principle:
[System instructions] → [Tool definitions] → [Long-term summary / references] → [Recent dialogue] → [Current user input]Never changes Rarely changes Low-frequency updates Appended over time Changes every turn
Avoid the following operations that break cache hits:
- Embedding high-frequency-changing content such as the current timestamp, random IDs, or temporary paths in the system prompt;
- Rewriting, reordering, or regenerating the summary every turn;
- Inserting, deleting, or rewriting earlier messages in the middle of the conversation.
In addition, caching has a time-to-live (TTL). If a task takes too long, or the interval between turns exceeds the cache’s validity period, the hit rate will drop noticeably. For long tasks, control the pace of turns reasonably, or break the task into segments.
Strategy 5: Finer tool-calling, fewer “ineffective turns”
- Trim tools by task: if a subtask only involves reading files and editing code, expose only the relevant tools. Fewer tools means more accurate selection and less trial-and-error.
- Structured returns: prefer structured formats such as JSON to reduce the ambiguity and redundancy of free text.
- Batch and parallelize: merge multiple independent small operations into a single call—for example, read several files at once rather than asking one file at a time.
- Limit retries: set a maximum retry count and a backoff strategy to avoid the model burning turns on the same error repeatedly.
5. How to verify the savings: turn “saving money” into measurable numbers
5.1 Establish a baseline
- Fixed evaluation set: select 20–50 representative real tasks covering different scenarios such as read, edit, run, and query;
- Lock the variables: the same model, the same temperature, the same tool set—change only the context management strategy;
- Repeat runs: run each task multiple times and take the average to dampen single-run variance.
5.2 Core metrics
| Metric | Meaning | Focus |
|---|---|---|
| Total input tokens | Sum of input across all turns | The primary optimization target |
| Average number of turns | Turns needed to finish the task | Reflects process efficiency |
| Task success rate | Proportion of tasks that pass validation | Prevents “saving money but breaking things” |
| Cost per task | Input/output tokens × unit price | Real-bill basis |
| Cache hit rate | Proportion of prefix that hits the cache | Determines the payoff of the caching strategy |
| End-to-end latency | Total time from start to finish | User experience |
5.3 A suggested usage-record schema
A simplified usage-record table can plug directly into your existing logging system or time-series database:
record = {"task_id": task_id,"turn": turn,"input_tokens": usage.input,"output_tokens": usage.output,"cache_hit_tokens": usage.cache_hit,"tool": tool_name,"latency_ms": elapsed,"strategy": "layered_context_v1", # tag the strategy version for easy comparison}
With dimensions for aggregating by task and by tool, you can answer questions like “which tool burns the most tokens” and “which strategy pays off most.”
5.4 A typical expected result
Take a task of 20 turns with about 2,000 tokens of tool return per turn as an example (illustrative estimate):
| Metric | Before | After | Change |
|---|---|---|---|
| Average input per turn | ~21,000 | ~10,000 | ~52% down |
| Total input tokens | ~420,000 | ~204,000 | ~51% down |
| Number of turns | 20 | 15 | 25% down |
| Total input tokens (including fewer turns) | ~420,000 | ~138,000 | ~67% down |
You can see that:
- Context compression alone cuts input volume by about half;
- Adding finer tool-calling that reduces turns widens the reduction to around 70%.
This is consistent with the “up to 77%” magnitude: a reduction of over 70% does not come out of nowhere, but from the combined effect of several measures—“context compression + fewer turns + cache hits.”
6. Engineering it: turn context governance into a platform capability
6.1 From “scripts” to “platform”
When an agent is used across multiple teams and business lines, context management should not remain private code in one project, but should be consolidated into a unified platform capability:
- Unified access layer: expose a consistent agent-calling interface externally, hiding differences across models and tools;
- Context manager component: provide layering, budgets, compression, reference-based returns, and other capabilities out of the box;
- Policy configuration center: push different window sizes, compression ratios, and tool sets by task type;
- Usage and cost dashboard: show token consumption and trends by team, task, and tool.
6.2 Combining with general cloud services
When deploying on the cloud, you can rely on several kinds of general capabilities to put the governance above into practice:
- Object storage: store archived historical context and raw tool returns, using path references in place of content pastes;
- Message queues: split long tasks into subtasks for asynchronous execution, reducing single-turn context pressure;
- Container platforms: host the agent services, with elastic scaling to handle traffic spikes;
- Logging services and monitoring alerts: collect each call’s tokens, latency, and success rate, and alert promptly on abnormal swings.
Taking Baidu AI Cloud as an example, its general cloud services such as object storage, message queues, containers, and logging, monitoring, and alerting can all be used to carry the capabilities above, helping teams upgrade context governance from “an optimization inside a project” to “platform-level infrastructure.”
6.3 From “reactive firefighting” to “proactive governance”
- Cost budgets: set token quotas for each team and business line, and alert as they approach the threshold;
- Anomaly detection: when a certain type of task suddenly sees a jump in average tokens, automatically flag it and prompt an investigation;
- A/B testing: roll out a new strategy on a portion of traffic first, then go full-scale after comparing success rate and cost.
7. Common misconceptions and how to avoid them
Misconception 1: The harder the compression, the better
Compression loses information. Over-compressing may make the model “forget” key constraints, which actually increases rework turns. The criterion: can the model still complete the task correctly after compression—not “the fewer tokens the better.”
Misconception 2: Turning on caching always saves money
Cache hits depend on a stable prefix. If the context layout is messy and changes every turn, the cache hit rate can be very low, and cache writes can even add extra overhead.
Misconception 3: Switching to a smaller model is more cost-effective
A smaller model has a lower unit price, but it may need more turns to finish a task, so total tokens can end up higher and the success rate may also drop. Recommendation: optimize the context first, then evaluate model selection.
Misconception 4: Looking only at tokens, not the bill
Cache hits, input, and output are often priced differently. Recommendation: base decisions on the actual bill, and establish a “cost per task” metric rather than a simple token count.
Misconception 5: Compression is a one-time job
Businesses change, tools grow, and task types expand, so the context strategy needs continuous iteration. Recommendation: bring compression ratios, window sizes, and tool sets into configuration management, and review them regularly.
8. Conclusion: don’t rush to switch models—learn not to waste first
This practice of “cutting over 70% of tokens without switching models” reveals a long-overlooked truth: the cost bottleneck of an agent often lies not in the model itself, but in how we organize the context and design tool calls.
Looking back over the whole article, five action recommendations emerge:
- Measure first: build a baseline and usage records, and know where the money goes;
- Then layer: separate hot from cold, prefer references, and enforce budgets;
- Then refine: expose tools on demand, and make returns structured and addressable;
- Then cache: keep the prefix stable to improve hit rates;
- Evaluate last: use success rate and the real bill as the final standard.
None of these practices depend on a specific model or tool—they are general engineering methods. For teams building AI coding tools, AIOps agents, or enterprise knowledge assistants, seriously reviewing the prompt pipeline in your project and learning not to waste first often cuts costs and improves stability more immediately than rushing to switch models.
