Reducing AI Agent Token Costs with Code Orchestration for Tool Calls
AI agents typically complete tasks through multi-turn loops, which can lead to escalating token costs due to repeated tool definitions and the full accumulation of intermediate results within the context window. This article explores how using code orchestration to handle intermediate processes can significantly reduce token overhead. By generating and executing a single script locally, agents can process large datasets and return only summarized results to the model. We also cover key implementation designs, applicable scenarios, risk management, and practical steps for evaluating and deploying this approach.
1. Where Do the Costs Come From?
AI agents typically complete tasks through a multi-turn loop: the model proposes a tool call, the tool executes and returns the result to the model, and the model then decides the next step. This pattern works well for simple tasks, but costs rise significantly when troubleshooting across a large number of files or batch pulling hundreds of external records.
The costs primarily come from two sources:
First, repeated transmission of tool definitions. To let the model know which tools are available, every request must carry the names, descriptions, and parameter structures of all tools. The more tools there are, the larger the base size of a single request. This “instruction manual” does not shrink as the task progresses; it must be re-uploaded every turn.
Second, full retention of intermediate results. Many tools return lengthy content, such as complete logs, entire batches of database records, or full web pages. However, the model often only needs a few lines of it. Under the multi-turn calling mechanism, these raw contents are written entirely into the conversation history and are billed again in every subsequent turn.
2. Understanding the Snowball Effect Mathematically
Let $T_i$ be the number of input tokens for the $i$-th request, $D$ be the tool definition part, $S$ be the combined system prompt and user input, and $r$ be the average new content added to the history per turn. Then:
$T_i \approx D + S + (i - 1) \times r$
After $n$ turns, the cumulative input volume is:
$\sum T_i = n \times (D + S) + r \times n(n - 1) / 2$
The first term grows linearly with the number of turns, while the second term grows quadratically. The more turns there are, the larger the proportion of overhead brought by historical accumulation. This is the mathematical reason behind the cost “snowball effect.”
Here is a hypothetical example with values used only to illustrate the structure, not actual test results. Assuming $D = 30,000$, $S = 2,000$, $r = 3,000$, and the task takes 20 turns, the cumulative input is approximately $20 \times 32,000 + 3,000 \times 190 = 1,210,000$ tokens.
3. Core Concept: Offloading Intermediate Processes to Code
The key to reducing costs lies in minimizing the steps that require the model’s turn-by-turn participation. A viable approach is to have the model generate a script at once, which is then executed by a local runtime to handle loops, branches, filtering, and aggregation. Finally, only the summarized result is returned to the model.
The differences between the two approaches can be summarized as follows:
| Dimension | Multi-turn Tool Calling | Code Orchestration |
|---|---|---|
| Model Participation | Requires a turn for every tool call | Participates during script generation, not during execution |
| Tool Definition Transmission | Repeatedly transmitted every turn | Transmitted only once during the orchestration phase |
| Intermediate Results Destination | All enter the conversation history | Remain in local variables, retained as needed |
| Control Flow | Determined step-by-step by the model | Expressed by script conditions and loops |
| Debugging Difficulty | Each step is visible, easy to locate | Requires logs and error messages for assistance |
Here is an illustrative example, assuming you need to calculate the total refund amount across 120 tickets:
def summarize_refunds(ticket_ids, fetch_ticket):"""Iterate through tickets locally and return only the aggregated result."""total = 0.0counted = 0for ticket_id in ticket_ids:record = fetch_ticket(ticket_id) # Raw records exist only in local variablesamount = record.get("refund_amount")if amount is not None:total += float(amount)counted += 1return {"tickets_scanned": len(ticket_ids),"tickets_with_refund": counted,"total_refund": round(total, 2),}
With this approach, the model only needs to receive the final dictionary; the 120 raw records never enter the context. If using the multi-turn calling method, each record must return to the model as a tool result, causing the context length to increase continuously with the number of records.
4. Key Design Considerations for Implementation
1. Execution Environment Isolation. The generated script must run in a sandbox that limits accessible file paths and network addresses, with execution timeouts and memory limits set. Only the tool functions essential to the task should be exposed, adhering to the principle of least privilege.
2. Standardized Structured Return Values. The script should return a fixed-structure summary, such as counts, totals, Top N items, and an exception list. Additionally, set a size limit on the returned content. Content exceeding the limit should be written to a file, with the file path provided in the summary for on-demand reading when necessary.
3. Readable Error Information. When the script throws an exception, the error type, location, and a summary of the related inputs should be returned to the model. If the error information is just a single line of a stack trace, it is difficult for the model to correct the script based on it.
4. Maintain Traceability. Raw data should be persisted to disk or written to logs, recording the parameters, duration, and return size of each tool call. When the summarized result does not meet expectations, engineers can trace back to the raw data.
5. Write Operation Confirmation. Irreversible operations such as deletion, sending, or modification should not be included in an unattended script. The orchestration layer should expose these operations before execution, allowing them to be executed only after user confirmation.
5. Applicable Boundaries and Risks
Code orchestration is not superior in all scenarios.
Suitable scenarios include: processing a large number of similar objects with the same logic; instances where intermediate results are large but only a small amount of information is needed; and cases where the logic between steps can be expressed with clear conditions.
Unsuitable scenarios include: highly exploratory tasks where each step requires the model to see the full result to decide the next step; simple single calls where the orchestration overhead is not worth it; and cases where the side effects of the tools are difficult to describe in advance.
There are three main types of risks. First, script logic errors may be masked by the summarized results—for example, a wrongly written filter condition leading to missing samples. The mitigation is to output the number of samples processed and skipped, making anomalies visible. Second, code execution itself poses a security risk, which must be mitigated by relying on sandboxes and permission controls. Third, summarization loses details, which needs to be compensated by the persistence and logging mechanisms mentioned in Section 4.
6. How to Evaluate Effectiveness
The cost reduction effect should be confirmed through actual testing rather than relying on empirical judgment. The recommended evaluation method is as follows:
Define Metrics. Record at least four metrics: total input tokens, total output tokens, task success rate, and number of model call turns. If you need to calculate costs, combine these with the pricing rules.
Fixed Variable Comparison. Select a representative set of tasks. Under the same model version, same toolset, and same input conditions, run both the multi-turn calling and code orchestration methods separately, and record the above metrics.
Sufficient Samples. Fluctuations from a single run may mask real differences. Repeat each method multiple times and compare the distributions rather than just looking at the averages.
The reduction margin depends on the task structure, number of tools, and result volume. Different teams may get very different results, so you should rely on the actual test data from your own task sets.
7. Implementation Recommendations
- Inventory the Current State. List all tools currently used by the agent. Count the definition length and typical return size of each tool to identify the largest source of overhead.
- Prioritize High-Frequency Batch Tasks. Choose tasks with high call frequencies and large single result volumes for initial pilots, as the returns are usually the most obvious.
- Design Summary Formats. Work with stakeholders to determine which fields need to be retained, avoiding summaries that are too brief or too verbose.
- Canary Release. Run on a small portion of traffic first, comparing costs, success rates, and anomalies. Gradually expand the scope after confirming there are no issues.
- Continuous Monitoring. Record the token consumption and turns for each task. Periodically review whether the toolset has become bloated and clean up tool definitions that are no longer used.
Overall, the key to reducing agent costs lies in minimizing redundant transmission and invalid retention. Offloading deterministic intermediate processes to local code execution, leaving the model to handle only the parts that require judgment, is a verifiable and measurable engineering path.
