Reducing Token Costs in LLM Agents with Code-Based Orchestration
LLM agents often become expensive because tool definitions are resent on every turn and verbose intermediate tool outputs remain in the conversation history. This article explains the cost structure and presents three practical approaches: code-based orchestration in a restricted sandbox, filtering and summarizing tool outputs, and loading tool definitions on demand. It also covers applicability, security controls, measurement metrics, and a step-by-step adoption path.
1. Background: Why Agents Get More Expensive as They Run
Using tools to complete complex tasks is now a standard pattern for agent applications. The model reads files, queries data, executes commands, and modifies code, and each step depends on results returned by tools. This pattern works well for simple tasks. When a task involves dozens of files, hundreds of records, or multiple external systems, token consumption can quickly get out of control.
In a standard turn-by-turn invocation pattern, cost mainly comes from two sources.
First, tool definitions are retransmitted. On every request, the model needs to know which tools are available and what parameters each tool accepts. Developer environments often register a dozen built-in tools at the same time, plus externally connected tools, so the tool specification alone may consume tens of thousands of tokens. As long as the session continues, this specification is resent with every request.
Second, intermediate results are fully retained. Many tool outputs are long, but the model only needs a few lines. For example, a search command may return thousands of matching lines, and an API query may return hundreds of complete records. Under turn-by-turn invocation, this content is written verbatim into the conversation history, and every subsequent round pays for it.
The two types of overhead compound, creating a structural problem: the more rounds, the higher the cost.
2. A Cost Model
A simplified estimate illustrates the problem. Assume:
- Tool definitions total about 30,000 tokens and are carried in every request;
- The task requires 20 rounds of tool calls;
- Each round adds an average of about 5,000 tokens of tool output, all retained in history.
The input size for round n is roughly:
Input(n) ≈ tool definitions + task instructions + Σ(tool outputs from previous n-1 rounds)
By round 20, the input is close to the order of 30,000 + 95,000, and each round recomputes previous content. The cumulative input for the entire task grows roughly quadratically with the number of rounds. This is what “snowballing” means.
These numbers only illustrate order-of-magnitude relationships. Actual values depend on the specific system, model billing method, and task structure. Evaluation should be based on your own request logs.
3. Approach 1: Replace Round-by-Round Calls with Scripts
The first approach is to have the model generate an orchestration script in one pass and execute it in a controlled runtime. Tool calls happen inside the script, and the model receives only the final results it needs.
In turn-by-turn mode, the model participates in every intermediate step:
- Call the search tool and get all matches;
- Return the matches to the model so it can select files;
- Call the read tool and get file contents;
- Return them to the model again to decide the next step.
In script orchestration mode, intermediate steps are completed directly in the runtime environment:
# Orchestration script generated by the model, executed in a restricted sandboxfiles = search_files(pattern="FIXME", root="src/")hits = []for path in files:text = read_file(path)for line_no, line in enumerate(text.splitlines(), start=1):if "FIXME" in line:hits.append(f"{path}:{line_no}: {line.strip()}")# Return only the first 50 results to the modelprint("\n".join(hits[:50]))
In this script, the model sees only 50 lines of output instead of the full contents of every file. Loops, conditionals, and data aggregation are completed locally and do not occupy the model’s context.
The differences between the two modes can be summarized as follows:
| Dimension | Turn-by-turn calls | Script orchestration |
|---|---|---|
| Model involvement | Once per intermediate step | Usually one generation and one summary |
| Tool definitions | Retransmitted every round | Provided as needed |
| Intermediate results | Fully enter history | Only required output returned |
| Control flow | Decided step by step by the model | Written in the script, reusable |
| Debugging difficulty | Lower, each step visible | Higher, execution logs required |
Script orchestration delivers the clearest benefits when a task has many intermediate steps, large data volumes, and deterministic logic between steps.
4. Approach 2: Filter and Summarize at the Tool Output Layer
Even without changing the invocation method, you can compress content immediately after a tool returns a result. The principle is: the tool layer filters, and the model layer receives only conclusive information.
def summarize_tickets(tickets):refunded = [t for t in tickets if t["status"] == "refunded"]total = sum(t["refund_amount"] for t in refunded)return {"refund_count": len(refunded),"refund_total": total,}
The function above compresses 120 raw records into two numbers. During subsequent reasoning, the model sees only the summary and does not need to see the field details of every record.
Several rules can be followed during implementation:
- Set limits for list-type results, and provide a total count and truncation notice for items beyond the limit;
- For long text, prefer returning matching lines and their context rather than the entire file;
- For structured data, prefer returning aggregated results and return details only when necessary;
- Preserve the storage location of the raw output so it can be read again by identifier when needed.
5. Approach 3: Load Tool Definitions on Demand
The third approach targets repeated transmission of tool definitions. Not every task needs every tool, so tools can be divided into two groups:
ALWAYS_ON = ["search_files", "read_file", "edit_file"]ON_DEMAND = {"database": ["run_query", "describe_table"],"issue_tracker": ["list_issues", "get_issue"],"deploy": ["trigger_pipeline", "get_pipeline_status"],}def build_tool_list(task_tags):tools = list(ALWAYS_ON)for tag in task_tags:tools.extend(ON_DEMAND.get(tag, []))return tools
At task start, the system loads only the relevant tool groups based on task type or the model’s request. This makes the specification carried in each request shorter without affecting the capabilities the model needs to complete the current task.
Note that tool grouping adds complexity to one decision. If grouping is wrong, the model may be unable to call necessary tools. Therefore, it is recommended to add clear trigger conditions for each tool group and log loading status for troubleshooting.
6. Applicability and Boundaries
Script orchestration and output compression are not equally effective for all tasks.
Suitable scenarios include:
- Batch processing of files or records where each item follows the same processing logic;
- Tasks that require multi-step filtering, aggregation, or statistics where intermediate results do not need human judgment;
- Tasks involving multiple tools in sequence, where the output of one step determines the parameters of the next;
- Repeated workflows that can be captured as reusable scripts.
Unsuitable scenarios include:
- Every step requires open-ended judgment by the model based on context, such as solution design or code review;
- Tasks require only one or two tool calls, so the cost of modification exceeds the savings;
- Tool outputs are structurally unstable and difficult to parse reliably in a script;
- Execution results require a very high level of auditability and complete logs are unavailable.
You can ask three questions when deciding: Can the intermediate steps be expressed with deterministic logic? Are the intermediate results much larger than the final required output? Are there enough rounds for cumulative overhead to become significant? If the answer to all three is yes, the change is usually worth making.
7. Security and Risk Controls
Having the model generate and execute code introduces new risks. Security should be the first priority during such changes, following these principles.
First, the runtime environment must be isolated. Scripts should execute in a sandbox isolated from the host system’s files, network, and credentials. The sandbox should expose only the directories and interfaces required by the task.
Second, follow the principle of least privilege. Tools callable by scripts should have an explicit allowlist, and write operations should be authorized separately from read operations. High-risk operations such as deletion, publishing, and payment should retain a human confirmation step and should not be completed automatically by scripts.
Third, set resource limits. Define thresholds for execution time, memory usage, output length, and call count to prevent scripts from entering infinite loops or producing abnormally large requests.
Fourth, validate inputs and outputs. Tool parameters should be checked for type and range, and external data should be treated as untrusted before entering scripts, so that text within it is not executed as instructions.
Fifth, retain complete logs. Record each script’s source code, execution time, tools called, and returned summaries for later review and troubleshooting.
8. Measuring the Impact
Before and after the change, run a controlled experiment using the same batch of tasks, the same model, and the same evaluation criteria. Recommended metrics include:
- Total input and output tokens per task;
- Number of model requests;
- Task success rate and result correctness;
- End-to-end latency;
- Billed amount per task.
Looking only at token reduction is not enough. If the success rate drops, the saved cost may be offset by rework. Confirm that quality metrics have not degraded before discussing cost benefits.
The sample size should also be sufficient. It is recommended to collect at least dozens of runs for each task category and report results stratified by task difficulty to avoid being misled by a few simple samples.
9. Implementation Recommendations
If you plan to introduce these approaches into your own agent system, proceed in the following order:
- First use logs to count rounds, input size, and tool output length for each task, and identify the largest source of overhead;
- Summarize outputs from tools that produce overly long results; this type of change has the lowest risk;
- Split tool groups by usage frequency to reduce definitions retransmitted every round;
- For batch tasks with strong determinism and many steps, introduce script orchestration in a restricted sandbox;
- Build a comparison evaluation set and check changes in cost and quality after each modification.
The benefit of gradual rollout is that each step can be validated independently, and problems can be rolled back easily.
