Cutting AI Agent Token Costs by 70% Through Smarter Context Engineering

    This article explains how teams can reduce token consumption in AI agents by improving context management rather than immediately switching to a different model. It identifies common sources of waste in agent workflows, including full-history replay, untrimmed tool outputs, and weak reuse of stable prompts. It then presents four practical techniques: sliding-window history compression, tool-output trimming with on-demand expansion, retrieval-based context loading, and prompt structuring for prefix caching. The article also explains how to turn these techniques into measurable, configurable, and regression-tested engineering practices.

    1. The Overlooked Fact: The Bottleneck Is Not the Model, but How You Feed It

    When costs rise, many teams first try to switch to a larger and more capable model, or look for a cheaper alternative. However, engineering practice has repeatedly shown that in long-chain scenarios such as AI coding agents and automated agents, the main source of token consumption is often not the model itself, but the way the input content is organized.

    For the same task, a well-structured input may complete the loop with only around 10,000 to 20,000 tokens. A poorly structured input can easily consume tens or even hundreds of thousands of tokens, especially when full conversation history is replayed and tool outputs are inserted into the context without trimming. In practice, without changing the model or adding any new capabilities, simply redesigning context management and tool-call behavior has been shown to reduce token consumption by as much as 70%.

    This is an important point: before looking for a new model, teams should first examine their own engineering pipeline. The sections below break down common sources of waste and practical ways to reduce them.

    2. Where Are Tokens Wasted?

    To reduce token consumption, you first need to understand where the tokens are going. In a typical agent loop — perceive, reason, call a tool, observe the result, and reason again — waste usually concentrates in three areas.

    1. Full-History Replay

    Each iteration may include the entire conversation history without modification. As the number of turns grows, early content that is no longer relevant to the current subtask continues to be billed and processed repeatedly. The context becomes increasingly bloated.

    2. Untrimmed Tool Results

    Reading a file may return thousands of lines, running a command may produce tens of thousands of characters, and fetching an API response may return an entire JSON object. These raw outputs are often inserted into the context as-is, even though only a small portion may be useful for the next decision.

    3. Lack of Reuse and Structure

    System prompts, tool definitions, project background, and other content that remains unchanged across turns may not be cached or reused effectively. If the prompt structure is loose or unstable, prefix caching may fail to hit, causing repeated computation and unnecessary cost.

    3. Four Practical Optimization Techniques

    1. History Compression and Sliding Windows

    Do not treat all history as mandatory content that must be preserved. A layered retention strategy is often more effective:

    • Keep recent turns verbatim: preserve the latest several turns to maintain continuity.
    • Summarize medium-term turns: compress older turns into a structured summary that keeps conclusions, key decisions, and unresolved questions.
    • Archive older content: move earlier content to external storage and retrieve it only when needed, rather than keeping it in the context at all times.

    An example of a window-based context management approach:

    1. def build_context(messages, window=6, max_summary_tokens=800):
    2. recent = messages[-window:] # Keep recent messages verbatim
    3. older = messages[:-window]
    4. summary = summarize(older, # Compress older messages into a summary
    5. max_tokens=max_summary_tokens)
    6. return [system_prompt] + summary + recent

    The key idea is that a context is not better simply because it contains more information. It is better when it contains more useful information. A summary only needs to retain the details required for decision-making.

    2. Trim Tool Results and Expand on Demand

    Tool outputs should be treated as resources that can be truncated, summarized, or paginated, not as data that must always be inserted into the context in full. Common techniques include:

    • Truncate with a notice: keep only key beginning and ending portions of very long output, and tell the model that the content was truncated and that it can request a specific range if needed.
    • Extract structured data: filter and aggregate command output before sending it to the model, leaving only the fields relevant to the task.
    • Use pagination or cursors: for large files, read only the needed range and let the model request additional pages when necessary instead of loading everything at once.
    1. def trim_tool_output(raw, head=2000, tail=500):
    2. if len(raw) <= head + tail:
    3. return raw
    4. omitted = len(raw) - head - tail
    5. return f"{raw[:head]}\n...[omitted {omitted} characters]...\n{raw[-tail:]}"

    This step often contributes the most to the overall reduction, because raw tool outputs can be the largest single contributor to context size.

    3. Layered On-Demand Loading: Prefer Retrieval Over Full Injection

    Instead of injecting everything into the prompt in advance, load content only when needed. Project background, historical documents, codebase context, and similar information can be retrieved on demand. This reduces the base size of the context and helps the model focus more effectively on the current task, which can also improve output quality.

    4. Prefix-Caching Reuse and Prompt Structuring

    Place content that remains unchanged across turns — such as system instructions, tool definitions, and project conventions — at the beginning of the prompt, and keep it byte-stable. Place variable content at the end. This allows the stable prefix to be cached, avoiding repeated billing and repeated computation.

    The structural principle can be summarized simply: stable content goes first, variable content goes last, and the stable part should not be changed unnecessarily.

    4. Turn Optimization into Reusable Engineering Capability

    These techniques should not be treated as temporary patches. They should be built into a reusable context-governance layer that is observable, testable, and easy to regression-test:

    • Measure first: log input/output tokens and the composition of the context for each request. Identify the largest sources of waste before making changes.
    • Make strategies configurable: parameters such as window size, summary length, and truncation thresholds should be configurable so they can be tuned for different tasks.
    • Compare before and after: run A/B tests with the same set of tasks to confirm that quality does not regress and that cost actually decreases.
    • Externalize storage: move older content out of the context and into object storage or a vector database. Retrieve it precisely when needed so that removed content is not simply lost.

    5. Conclusion: Before Switching Models, Stop Wasting Tokens

    Switching models is often the most expensive and least certain way to solve a cost problem. A more practical order is:

    1. Review your prompt pipeline.
    2. Check whether full history is being replayed.
    3. Check whether tool results are being inserted unchanged.
    4. Check whether stable prefixes are actually hitting the cache.

    Fixing these waste points one by one can often recover most of the cost without changing the model.

    The 70% reduction does not come from a single magic technique. It comes from the compounding effect of compressing history, trimming tool outputs, loading context on demand, and reusing cached prefixes. For developers, this is not only a cost-saving measure, but also a fundamental skill for building high-quality agents. As AI coding tools and automated agents become more common, learning to “feed the model smartly” is an engineering capability that will keep paying off.