How to Cut AI Agent Token Consumption by 77%: The Logic Behind Code-Based Execution
As AI agents take on larger, multi-step tasks, their token usage—and cost—can spiral out of control. This article explains why traditional tool-calling agents accumulate tokens so quickly, then shows how shifting from step-by-step tool calls to code-based execution lets the model write a script that performs retrieval, filtering, and aggregation locally and returns only the final result. You'll learn the two main sources of context bloat, how code-based orchestration cuts real API bills by more than 20% (and cumulative token volume by more than 60% in tool-heavy scenarios), and where the approach works best along with the sandboxing and access controls it requires.
Developers who have used AI coding tools know the same frustration: the task quality is satisfying, but the rapidly climbing token counter—and the bill that follows—is unsettling. Traditionally, making an AI agent run faster and cost less left only two options: wait for a cheaper model to be released, or downgrade the primary model to a smaller one and accept the drop in delivery quality.
A new approach gaining traction in the industry shifts the focus of optimization from the “model side” to the “execution architecture side.” Without swapping models or sacrificing reasoning ability, simply changing how the agent calls tools can cut real API bills by more than 20%. In scenarios with high-frequency external tool calls, the total volume of tokens the model processes can drop by more than 60%.
1. The Real Source of Runaway Costs: Context Snowballing
To understand what this new mode saves, you first need to see how “heavy” traditional agents are at work.
In the conventional mode, the agent has the model directly organize tool calls: run a file search, read the content, then modify the code. If a later action depends on the result of a previous step, the tool must hand the full return value back to the model so it can decide the next step. While mainstream AI coding tools already support parallel calls and scripted batch execution, for tasks that need multi-step reasoning and cross-tool collaboration, the model still repeatedly intervenes in the intermediate steps.
When you change one or two functions, this process is harmless. But once the task becomes locating a bug across dozens of files, or pulling hundreds of business records via an external protocol, two hidden costs quickly bloat the context.
The first cost is at the starting line. When efficient mode isn’t enabled, the agent must send the model the structured definitions of a dozen or so built-in tools every round; the first request alone can reach tens of thousands of tokens. As long as the session continues, this “tool manual” is re-transmitted with every request, forming a fixed cost.
The second cost hides in the middle of the process. Most tool return values only need a glance to filter out a few lines of key information, but under round-by-round calling, entire logs and entire batches of raw records stay in the conversation history. A typical case: asking the model to pull hundreds of support tickets and total the refund amount; the conventional mode is forced to load all records into context across multiple rounds.
The conclusion is clear: every tool call stuffs the full raw output, along with all tool definitions, into the next round’s context. The more rounds there are, the more consumption snowballs.
2. The Fix: Hand Orchestration to Local Scripts
The starting point of the new mode is to change “the model decides step by step” into “the model writes code, and the script runs the flow.”
Its core is code-based execution: the model no longer issues tool requests one by one. Instead, it generates a script that performs search, filtering, aggregation, and multi-tool chaining in one pass within a local sandbox, returning only the final conclusion. Code thus becomes the most efficient communication protocol between the agent and its tools—data flows locally, and only necessary information enters the context.
Illustrative pseudocode:
# Orchestration script generated and run by the model (illustrative)records = tool.query_tickets(limit=120) # batch pull; not returned record by recordrefunds = [r for r in records if r.type == "refund"]total = sum(r.amount for r in refunds)files = tool.search("TODO", path="./src") # chain multiple toolsreturn {"refund_total": total, "hits": len(files)}
This script returns just two numbers instead of hundreds of raw records. What’s saved here is exactly the “intermediate-state context.”
3. Breaking Down the Gains and Knowing the Limits
The gains stack up from three sources: tool definitions are loaded once rather than re-transmitted every round; intermediate results are trimmed locally and don’t enter the history; and multi-step flows compress into a single round or a few rounds, reducing repeated reasoning.
The applicable boundaries need to be clear as well: the more a task depends on multi-step reasoning and external data aggregation, the more obvious the benefit; for small changes to a single file, the gain is limited. Script execution also requires sandbox isolation, least-privilege access, and result validation to avoid mistakes.
For enterprises and teams, this approach can be applied directly to daily development workflows: script the high-frequency, batch-able operations, and leave the steps that need judgment to the model. Paired with general-purpose cloud container platforms, log services, and monitoring and alerting capabilities for isolation and observability, you can push the agent’s per-task cost into a lower range without changing the model’s capabilities.
