Agent Context Cost Optimization: How Code Execution Saves Tokens

    As agent conversations grow longer, token consumption often rises almost linearly while only a small fraction of the context relates to the user's actual question. This article breaks down where those tokens go, explains the structural limits of the traditional point-and-pick tool-calling model, and introduces an alternative: turning tools into typed files that the model browses on demand and executes in a sandbox, returning only summaries. It also outlines a five-step implementation path, along with the trade-offs, boundaries, and risk controls engineering teams need to account for.

    Agent Context Cost Optimization: How Code Execution Saves Tokens

    1. Where the Tokens Actually Go

    Many teams notice the same pattern after deploying an AI agent: as the number of conversation turns grows, token consumption climbs almost linearly, yet only a small share of the context is actually relevant to the user’s question. The first step toward cutting cost is not reducing the number of tools, but breaking the consumption down.

    In a typical tool-calling agent, the tokens in context come from roughly four sources:

    1. System prompts and role definitions, which stay relatively fixed;
    2. The tool definition list, including each tool’s name, description, and parameter structure, which reappears every turn;
    3. Conversation history and reasoning traces;
    4. Tool call return values, which are often pasted back into the context as-is.

    The second and fourth items are the easiest to overlook. Tool definitions are a standing cost: no matter whether the user asks about the weather or a database this turn, every tool’s description must be present so the model has something to choose from. Return values are an amplifying cost: a single query can return hundreds of lines of structured data, and once that content enters the context, it gets carried along in every subsequent turn.

    One engineering practice published by a cloud vendor offers a comparison: in a single case, the context size was reduced from about 150,000 tokens to about 2,000 tokens, a drop of roughly 98.7%. It is worth stressing that this is only “one case.” The original text does not specify whether the figure covers tool definitions, return values, or the entire conversation, so it is useful for judging the trend but should not be treated as a performance benchmark or a basis for capacity planning.

    2. The Structural Flaws of the Old Paradigm: Point-and-Pick Calls

    The conventional approach is “point and pick”: the model reads the full tool list, selects one, fills in the parameters, makes the call, and puts the entire response back into the context. If a task requires ten tool calls, that means ten full round trips.

    This mechanism runs into three unavoidable problems:

    • Fixed cost unrelated to the question. The more tools there are, the longer the standing descriptions. An agent integrated with a dozen services and hundreds of endpoints can burn thousands of tokens on the “menu” alone, none of which adds information for the current turn.
    • Irreversible contamination from return values. Once raw tool output enters the context, it cannot be “taken back.” It travels with the conversation, and every subsequent reasoning step pays for it.
    • Selection quality degrades with scale. The more candidates there are, the higher the chance the model picks the wrong tool or fills in the wrong parameters. Retries trigger another round of round trips, creating a positive feedback loop for cost.

    The conclusion is straightforward: if your tokens are mainly consumed by tool descriptions and full return payloads, reducing the number of tools is only a stopgap. The cost is trimmed capability, and you will hit the ceiling again as the business grows.

    3. The New Paradigm: Write the Tools Down and Let the Model Browse on Demand

    The alternative is to change how tools enter the context, not the tools themselves.

    The approach: generate a typed wrapper code file for each tool, and group tools from the same source into the same directory. Instead of facing a long list, the model works like a developer, listing directories, searching, and opening files only as needed. What it reads shifts from “all tools” to “one index plus a few documentation files.” The invocation code it writes is executed in a controlled environment, and only a summary returns to the context.

    An illustrative directory and file layout (structure only):

    1. tools/
    2. index.md # Tool index: name + one-line purpose
    3. storage/
    4. list_objects.py # Typed wrapper: clear parameter and return structures
    5. get_object_meta.py
    6. queue/
    7. send_message.py
    8. peek_messages.py

    Key prompt constraints on the model side can be written as:

    1. 1. Read tools/index.md first to get an overview of available capabilities;
    2. 2. Open specific files only when needed; do not read all tools at once;
    3. 3. Compose calls by writing and executing code;
    4. 4. Write only a summary (item count, first few lines, status line) back to the context; keep the full output in the execution environment.

    The essence of this shift is that what gets replaced is not the tools, but the way tools enter the context. The context degrades from a “full menu” to a “searchable index,” information loads on demand, and cost grows with actual usage rather than total capability.

    4. A Five-Step Implementation Path

    Drawing on publicly described practices, here is a reproducible sequence:

    1. Generate typed wrapper files. One file per tool, grouped by source, with parameter and return structures declared explicitly so the model can call them accurately.
    2. Build an on-demand retrieval mechanism. Provide a directory index and search capability so the model reads only what it uses, avoiding preloading.
    3. Execute code in a restricted sandbox. This is the only hard cost item in the whole approach. It requires resource limits (CPU, memory, execution time), behavior monitoring, and control over network egress.
    4. Return only summaries. Agree on a summary format, such as result count, the first five lines, and a status line. Keep the full output in the execution environment, retrievable via pagination or a follow-up query when necessary.
    5. Capture them as skills. Save working code together with a same-named documentation file (SKILL.md) as a reusable skill. Next time, read the file directly instead of re-reasoning the orchestration.

    For easier recall, the five steps compress into three layers:

    • File layer: tools become files, browsed on demand;
    • Sandbox layer: resource limits plus behavior monitoring;
    • Summary and skill layer: return only summaries, store experience as skills.

    5. Costs, Boundaries, and Risk Controls

    This approach is not a cost-free silver bullet. Engineering teams must confront four points:

    • The execution environment is a new attack surface. Code execution means arbitrary logic can land, so isolation, limits, auditing, and an egress allowlist are mandatory, along with a ban on unauthorized access to credentials.
    • Summaries can lose information. Over-compression can lead the model to make wrong judgments, so key fields should retain structured summaries and a traceable path back to the data.
    • Retrieval quality sets the ceiling. A poorly written index means the model cannot find files, so cost does not drop and the agent takes extra turns instead. The index should include purpose, inputs and outputs, and typical scenarios.
    • Observability must be added in parallel. Track tool-definition tokens, return-value tokens, and retrieval hit counts per turn to verify whether the optimization actually works.

    6. Conclusion

    Wasted context budget is usually not the model “talking too much,” but an architecture that forces irrelevant information to stay resident. Turning tools from a list into files, full returns into summaries, and one-off orchestration into reusable skills are three mutually reinforcing threads. If you want to build this execution and observability chain on top of general capabilities such as the container platform, object storage, and log monitoring offered by Baidu AI Cloud, start with the three-piece set of “index + sandbox + summary,” calibrate the gains with real business data, and then decide whether to expand the scope of the改造.