Drastically Cut Token Costs Without Changing Models: Context Management Practices
High token consumption in AI agents and coding systems often stems from inefficient context management rather than model limitations. This article outlines practical context engineering strategies to significantly reduce token usage without changing the underlying model. By implementing context layering, history summarization, tool result trimming, optimized tool calling, and on-demand retrieval, developers can minimize redundant information and ensure models only process necessary data at each step. We also provide an implementation checklist and observability metrics to help you balance cost reduction with system stability.
I. The Essence of the Problem: The Bottleneck is “What to Feed”, Not “Which Model”
In AI agent and intelligent programming systems, high token consumption does not necessarily indicate insufficient model capability. More commonly, the model remains the same, but coarse context supply causes a large amount of invalid information to repeatedly enter the reasoning chain. Practical observations suggest that, without changing the model, simply refactoring context management and tool calling strategies can reduce token consumption by up to 77%. While the exact figure varies based on task type, history length, tool return volume, and implementation details, the implication is clear: the cost bottleneck often lies in context engineering rather than model replacement.
Common waste points include: injecting the full conversation history in every turn; passing untrimmed, unstructured raw large objects from tools; verbose and frequently changing system prompts; retrieval results with no upper limit; carrying the full context during failed retries; repeatedly injecting the same background for multiple subtasks; and continuously expanding the context despite diminishing marginal returns. When these issues compound, the bill naturally spikes.
Therefore, the optimization goal is not to “make the model see more,” but to “ensure the model sees only sufficient and necessary information at each step.” The core principles can be summarized in four points: on-demand supply, compressible, verifiable, and observable.
II. Strategy 1: Context Layering and Token Budgeting
Splitting the context into a stable layer, a state layer, a recent layer, and an evidence layer—and setting a token budget for each—is the first gate to control costs.
- Stable layer: System instructions, role constraints, and output format. These should be short, stable, and rarely change, avoiding repetitive expansion every turn.
- State layer: Task goals, completed items, key decisions, and to-do lists. Maintain these using structured summaries rather than the full raw conversation.
- Recent layer: The most recent interactions, retaining necessary details. Once they exceed the window, fold them into the state layer.
- Evidence layer: On-demand retrieved document fragments and tool result summaries, keeping only the parts relevant to the current sub-problem.
The key to budget control is “allocate first, then fill, finally verify.” For example, set a fixed upper limit for the state layer, dual limits (turns and tokens) for the recent layer, and dual limits (count and single-item length) for the evidence layer. The pseudocode is as follows:
function build_context(task, history, evidence, budget):system = compact_system_prompt(task) # Stable and shortstate = summarize_state(task, history, budget.state)recent = select_recent_turns(history, budget.recent)docs = select_evidence(evidence, task, budget.evidence)context = system + state + recent + docsreturn enforce_budget(context, budget.total)
When executing enforce_budget, prioritize trimming low-relevance fragments in the evidence and recent layers, while preserving the task goals and key constraints in the state layer. This controls costs while reducing the risk of critical information being truncated.
III. Strategy 2: History Summarization and Sliding Window
Full history is the most common token black hole. A more reasonable approach is a “sliding window + incremental summary”: keep the recent conversation in its original form, and compress older conversations into state summaries. The summary should only record goals, constraints, decisions made, reasons for failure, and hypotheses to be verified.
Summarization is not simple truncation; it must be verifiable. Every key conclusion should retain source references or tool result identifiers to prevent the model from reasoning based on incorrect summaries later. In implementation, you can trigger a summary update every N turns or when the history exceeds a threshold. Move the old raw text out of the main context, retaining only traceable references.
Pseudocode:
function update_state(state, old_turns, max_tokens):facts = extract_decisions(old_turns)failures = extract_failures(old_turns)pending = extract_pending_items(state)return compress({facts, failures, pending}, max_tokens)
Key points: summary updates should have trigger conditions to avoid calling the model for compression every turn, which adds extra costs; summary results must be structured to prevent free-text bloat; old raw text can be stored on disk as a reference and retrieved on demand, rather than residing in the context by default.
IV. Strategy 3: Tool Result Trimming and Structuring
Tool calls are often another major source of token consumption. Raw returns may contain long logs, complete JSONs, duplicate fields, and irrelevant metadata. If these enter the context as-is, the model pays for this information every turn.
It is recommended to apply three layers of processing to tool results: the first layer is status and summary; the second layer is structured key fields; the third layer externalizes the raw result as a reference. For successful results, retain only the status, core summary, and reference identifier; for failed results, retain the error code, short message, and actionable advice, avoiding the repeated injection of complete stack traces. For list-type results, limit the count and deduplicate; for long texts, segment and summarize first, then expand on demand.
function trim_tool_result(result, max_tokens):if result.ok:return {status: "ok",summary: summarize(result.data, max_tokens),ref: store_artifact(result.data)}else:return {status: "error",code: result.code,message: truncate(result.message, 200)}
The benefit of doing this is not just saving tokens, but also reducing irrelevant information interference for the model, improving decision stability after tool calls. When details need to be expanded, read them on demand via references, forming a context structure of “summary resides, raw text externalized.”
V. Strategy 4: Tool Calling Strategy and Retry Control
Tool calls themselves can amplify token consumption: parameter errors lead to repeated calls, failures trigger full retries, parallel calls return massive amounts of duplicate information, and identical queries are executed multiple times. The optimization direction is “validate first, then call, retry less, reuse.”
- Parameter validation: Perform local validation before calling to reduce invalid round-trips caused by formatting errors.
- Idempotency & deduplication: Reuse results for the same query within a short period to avoid repeated calls.
- Batch merging: Combine read requests where possible to reduce round-trips and context fragmentation.
- Failure grading: Perform minimal context retries for recoverable errors; return a summary directly for unrecoverable errors without repeatedly injecting full history.
- Result reuse: Tool result summaries can be cached into the task state for subsequent steps to reference on demand.
During retries, it is especially crucial to avoid “sending the full history again.” The correct approach is to carry only the failure point, error code, last valid state, and corrected parameters, forming a minimal retry context.
VI. Strategy 5: On-Demand Retrieval Augmentation
Retrieval augmentation can improve factuality, but pre-filling the context with a large number of retrieval results will rapidly increase costs. A more reasonable approach is: first determine whether the current sub-problem requires external evidence; retrieve only if needed; rank and deduplicate the retrieval results first; inject only a small number of highly relevant fragments; and keep the rest as references.
For long document tasks, adopt a “table of contents/summary first, expand sections on demand” approach. Let the model locate the fragments to read based on the summary, then load the corresponding content, avoiding injecting the full text at once. This maintains information integrity while controlling the context size per turn.
VII. Strategy 6: Observation, Regression, and Implementation Checklist
Without measurement, there is no optimization. It is recommended to observe at least the following metrics: total tokens per task, context tokens per turn, tool result proportion, summary proportion, retry count, invalid tool call ratio, task success rate, and rework rate. During optimization, evaluate using dual metrics: “cost per task” and “success rate,” to avoid quality degradation caused by simply compressing the context.
Implementation can proceed in the following order:
- Analyze context composition to identify the proportion of history, tool results, retrieval fragments, and system prompts.
- Set token budgets for each layer, initially limiting tool results and full history.
- Introduce state summaries and a sliding window to retain key decisions and failure reasons.
- Structure tool results, externalize raw text as references, and expand on demand.
- Add parameter validation, deduplication, failure grading, and minimal retries.
- Establish a regression test set to compare cost, success rate, and rework rate before and after optimization.
- Continuously observe and adjust budgets by task type, rather than applying a one-size-fits-all compression.
Conclusion
“Drastically reducing tokens without changing the model” is not magic; it is the result of context engineering and tool call governance. What truly needs to be prioritized is tearing down waste points one by one: full history, untrimmed tool results, unbounded retrieval, and repeated retries. Learn to accurately “feed” the context first, and then consider whether to switch models. This approach often yields a more stable system performance at a lower cost.
