Slimming Down Agent Tool Calls: Making Code the Communication Protocol Between Agents and Tools
AI coding agents deliver impressive speed, yet the soaring token counts and month-end bills are hard to ignore. This article argues that the real problem is not expensive models but "talking too much"—the useless content resent on every turn. It explores code-orchestrated tool calling, a structural optimization that reduces token consumption without switching models or sacrificing quality. You'll learn why traditional tool calling becomes heavy at scale, how letting code act as the protocol between agents and tools works, a comparison of three technical approaches, the four core cost-saving mechanisms, and why token reductions (roughly 62%–77%) far outpace bill reductions (around 22%–23%). It closes with a practical checklist covering sandboxed execution, least-privilege permissions, observability, and cost guardrails, plus guidance on when to use the approach and when not to.
The Real Source of Billing Anxiety: Not Expensive Models, but Too Much Talking
The experience of using AI agents to write code is nearly unanimous: delivery feels great, but watching the token counter climb in the background and facing the month-end bill is hard to take calmly. For a long time, getting “faster, cheaper, and no quality loss” all at once meant only two options—wait for a vendor to release a cheaper new model, or manually swap your main model for a weaker small model and then endure higher rework rates and slipping delivery quality.
Both paths essentially play with the unit price. But the real bill is a product: unit price × usage, and in practice it’s usually the second factor that spins out of control—the ineffective content repeatedly resent in the context. Over the past two years, a more worthwhile direction has emerged in the industry: structural-side optimization—leave the model untouched, don’t reduce capability, and only change how the model communicates with tools. Public third-party benchmarks show that with code-orchestrated tool calling enabled and no model replacement, real bills on multi-step development tasks drop by about 22%–23%; and in stress-test scenarios with frequent external tool calls, the total tokens the model cumulatively processes fall by 62%–77%.
A caveat is warranted: these numbers vary widely with task type, codebase size, external data volume, and specific configuration, and should be treated as order-of-magnitude references rather than guaranteed metrics. But the conclusion they reveal is stable—an agent’s context overhead can be compressed through engineering means, and the compression headroom is often larger than the gains from switching models.
Why Traditional Tool Calling Feels Heavy
In the normal mode, the model is the orchestrator: it decides which tool to call first, what the parameters are, and what to do next after getting a result. A typical chain is to search for files first, then read the content, and finally edit the code. This mechanism is intuitive and highly general-purpose, and for a small single change it’s almost beyond reproach. The problems appear only after scaling up.
2.1 The First Cost: Tool “Manuals” Always Resident at the Starting Line
The model can’t call a tool it doesn’t know exists. So every request must carry the complete tool definitions—name, purpose description, parameter structure, field types. One independent evaluation broke down the request payload: with code orchestration off, a mainstream AI coding client attaches about 16 built-in tool definitions per round by default, and the first request’s payload alone approaches 38,000 tokens.
The key isn’t that “38k is large,” but that it’s paid every single round. As long as the session continues, this manual must reappear in every request. A ten-round task carries ten copies of fixed overhead; if the task runs two hundred rounds, the manual itself becomes a considerable cost.
2.2 The Second Cost: Raw Output “Deposited in Full” into Conversation History
For many tools, you only need to glance at the return value and pick out a few useful lines—among a build log, the three errors are what really matter; among a batch of external records, a single sum is what really matters. But under the round-by-round calling mechanism, the entire log and the entire batch of raw records enter the conversation history as tool results, and are then carried along in every subsequent round.
A typical example from public testing: have the model pull about 120 work-order records through an external data access channel and tally the total refund amount. In normal mode, these 120 records must enter the context in full across multiple rounds before the model can “see” them and complete the judgment. And once these 120 records are in the history, every subsequent round pays for them again.
2.3 The Amplification Effect: The More Rounds, the Steeper the Snowball
Combining the two points above into a simplified cost model:
cumulative input tokens ≈ rounds N × [ tool definition overhead D + system prompt S+ Σ(raw tool output Oi added each round) ]
This is a quantity that grows roughly quadratically with the number of rounds: the k-th request carries all the raw output accumulated from the previous k-1 rounds. So tasks like “locating a defect across dozens of files” or “pulling hundreds of external records for statistics” are exactly the type with the steepest cost—they naturally require many rounds, many tools, and large outputs.
Now look at the model side: attention computation cost rises with context length, and long contexts can also trigger segmented cache invalidation in some implementations. In other words, context bloat doesn’t just cost more money—it also brings rising latency and the quality risk of attention being diluted by irrelevant content. “Saving tokens” and “improving accuracy” don’t conflict here; they point in the same direction.
The New Paradigm: Making Code the Protocol Between Agents and Tools
3.1 The Core Idea
The idea behind code orchestration can be summed up in one sentence: don’t let tool results flow back to the model; instead, let the model write code to call the tools, and give the code’s return value to the model.
What the model outputs is no longer a string of structured tool-call intentions, but a small executable script. Inside the script, loops, filtering, aggregation, branching, and error retries are all handled; when the script finishes running, only the results it prints enter the model’s context. The model shifts from “an operator who must watch every step” to “an engineer who writes the work instructions.”
# Traditional mode: 120 records → multiple round-trips → all 120 raw segments stay in contextfor page in pages:raw = tool_call("query_records", page=page) # The model must see the full content to continue# ...the next request will carry the full text of raw
# Code-orchestrated mode: raw data stays in runtime memory; only the summary flows backraw = tool_call("query_records", status="refunded", limit=200)items = raw["items"]result = {"record_count": len(items),"refund_total": round(sum(r["amount"] for r in items), 2),"top3": sorted(items, key=lambda r: -r["amount"])[:3],}print(json.dumps(result, ensure_ascii=False)) # Only these few dozen lines enter the context
Both versions accomplish exactly the same business goal, but the amount of information entering the context differs by orders of magnitude. This is the direct source of the “62%–77% token reduction”: what’s saved is not model inference, but the intermediate shuttling that was never truly needed.
3.2 Comparing Three Technical Approaches
| Dimension | Inline tool calling | Code orchestration | Sub-context isolation |
|---|---|---|---|
| Orchestrator | Model decides each round | Model writes the script; runtime executes | Sub-agent executes; only conclusions returned |
| Intermediate results | All enter main context | Stay in runtime, not in context | Stay in sub-session |
| Tool definition overhead | Resident every round | Lazy-loaded / imported on demand | Main context exposes only a few entry points |
| Chains strongly dependent on prior results | Need multiple round-trips | Completed within a single script | Need multiple task delegations |
| Debugging observability | Intuitive | Needs logs and replay | Needs trace tracking |
The three are not mutually exclusive replacements. Mature implementations usually combine them in layers: the main context keeps only a few high-level entry points, complex orchestration sinks down into code execution, and very large retrieval tasks are further delegated to isolated sub-sessions.
Breaking Down the Four Time-Saving Mechanisms
1) Lazy loading of tool definitions and progressive disclosure. Tools don’t have to be laid out in full on the first round; you can start with a directory and index, and load the detailed description of the corresponding shard only when the model needs it. A stable static prefix also helps with prefix-cache hits. This directly cuts the fixed cost of “resending the manual every round.”
2) In-place filtering and aggregation of intermediate results. Filtering, deduplication, sorting, grouping, summing, and sampling are all the cheapest work at runtime. Changing the judgment from “read the full text, then decide” to “process first, then return” leaves only the minimal information set needed for the decision in the context.
3) Keeping only contract-based artifacts in the context. Define the script’s output structure: counts, aggregate values, key samples, error summaries, and set hard limits (such as returning at most N rows, or a truncation length per field). Write raw logs and full datasets to temporary files or object storage, and have the model retrieve them by path only when needed.
4) Replacing multiple round-trips with a single orchestration. Chains with strong dependencies originally needed several “call—wait—judge—call again” rounds; in code, they become a few sequential statements. Fewer round-trips also reduce server-side queuing and network latency.
Why the Bill Drops Only 20% While Tokens Drop 60%
This “scissors gap” deserves its own explanation, or you’ll easily misjudge the gains:
- Fixed costs don’t move. The system prompt, project conventions, and codebase context—parts unrelated to tool calling—still have to be paid for.
- Output tokens cost more per unit. The scripts the model generates are output tokens, whose unit price is usually higher than input, so “reading less” doesn’t necessarily translate into “spending less” proportionally.
- Caching and discounts affect the conversion. The portion that hits the prefix cache is already cheap, so the marginal gain from cutting it is small; what’s truly eliminated is mostly the long-tail raw output that misses the cache.
- No quality cost is the biggest hidden benefit. Savings achieved without downgrading the model or sacrificing capability are the ones that can be banked for the long term, whereas savings from downgrading the model often get eaten up by rework costs.
Conclusion: The token reduction is the ceiling of capability; the bill reduction is the actual result. When reporting gains, present both metrics side by side, along with the quality evaluation conclusions.
Deployment Checklist: Security, Reliability, Observability
Code execution means handing execution authority to the model’s output, so security boundaries must come first, not be patched on later.
- Sandboxed execution. Run inside a one-off container or a restricted runtime; disable external network access or allow only whitelisted addresses; cap CPU, memory, execution time, and concurrency.
- Least privilege. Default to read-only and no credentials; when writes are truly needed, open them by directory whitelist; and route dangerous operations (deletion, force-push, production changes) through manual confirmation without exception.
- Keep secrets out of scripts. Provide credentials via runtime-injected environment variables or temporary tokens; they must not enter the model’s context or appear in logs and returned results.
- Idempotency and retries. Make scripts re-entrant, and give external calls backoff retries and timeouts to avoid duplicate charges or duplicate write operations.
- Contract-based return values. Fix the output structure, limit the volume, and express errors explicitly (which step failed, categorized failure reason), so the model can continue deciding based on the summary rather than on guesswork.
- Observability. Instrument round counts, input/output tokens, peak context length, tool-call counts, and script execution time separately, and wire them into logging services and monitoring alerts; abnormal growth should be catchable in minutes, not discovered when reading the bill at month-end.
- Cost guardrails. Set a per-task token budget and a round limit; abort on exceeding either and report back the partial conclusions already reached.
- Build an evaluation set before going live. Prepare cases covering four types—“single-point small change,” “cross-file refactor,” “large-batch external data aggregation,” and “tasks with failure branches”—and measure four metrics for each: task success rate, rework rounds, tokens, and bill, compared against the original mode.
From cloud engineering practice, this capability typically sits on top of general-purpose infrastructure: container platforms host the sandbox runtime, object storage holds intermediate artifacts and large files, message queues decouple the scheduling and return of long tasks, logging and monitoring/alerting services provide cost observability, and permission and key-management capabilities enforce least-privilege constraints. Cloud platforms such as Baidu AI Cloud provide exactly these categories of general-purpose capabilities, making it easier for teams to compose an agent execution chain that meets the boundaries above within their own business systems.
When to Use It and When Not To
Suitable for: frequently calling external tools, needing retrieval and aggregation across multiple files or data sources, chains with strong dependencies, needing loops and batch processing, and production tasks sensitive to both cost and latency.
Not yet suitable for: small one- or two-step changes (where the fixed orchestration overhead becomes heavier instead), tasks that are highly open-ended with steps that can’t be pre-structured, and scenarios where the execution environment can’t be isolated or permissions can’t be constrained.
Conclusion
The shift from “the model calls tools round by round” to “the model writes code to call tools” changes more than the form of interaction—it’s a migration of the cost structure: fixed overhead is thinned by lazy loading, variable overhead is eliminated by in-place aggregation, and rounds are compressed into sequential statements. With model capability unchanged, this is currently one of the most cost-effective forms of context engineering.
For teams, the judgment criterion truly worth remembering is this: any intermediate data the model doesn’t need to see with its own eyes should not enter the context. Apply this principle across the design of tool definitions, return-value contracts, and execution sandboxes, and the drop in the token bill becomes a natural result rather than a separate optimization target.
