How AI Agents Turn Multi-Step Tool Calls into a Single Program
This article examines Code Mode, a tool orchestration approach where an AI agent writes multiple dependent tool calls into one small program that the host executes in a single pass, returning only a final summary to the model. Using the example of locating a symbol's callers in a repository, reading related files, and returning a condensed conclusion, it explains why data dependencies force extra round trips in the conventional tool-call loop, how moving control flow into host-executed code changes context visibility, and what the execution sequence looks like. It also covers when the pattern fits and when it does not, failure modes and engineering constraints such as timeouts, least privilege, observability, idempotency, consistent error semantics and serializable results, and how the approach works with context engineering practices.
How AI Agents Turn Multi-Step Tool Calls into a Single Program
In the practice of AI coding tools and automation agents, a recurring source of cost is not that “the model cannot write code,” but that “the model must stop and wait for a result before it can obtain the parameters for the next step.” Using a typical task as a thread — locating the callers of a symbol in a code repository, reading the relevant files, and returning a converged conclusion — this article discusses a tool orchestration approach known as Code Mode: the model writes multiple steps as a small program, the host executes it in one pass, and only the final summary is placed back into the model’s context. The discussion covers mechanisms and engineering boundaries only, and does not involve any performance figures for a specific implementation.
1. Where the Problem Starts: Data Dependencies Push Decisions Back to the Model
The conventional tool-calling loop is straightforward: the model declares in its reply that it wants to call a tool, the host executes it, the result is appended back to the session as a tool message, and the model decides the next step after seeing that result. The strengths of this loop are transparency, auditability, and the ability to intervene midway. The weakness is that once data dependencies exist between steps, the number of round trips cannot be compressed.
A data dependency means the parameters of a later call must depend on the return value of an earlier one. For example:
- The model issues a search to find the file paths containing the target symbol.
- The host executes the search and writes the path text back into the session.
- After seeing the paths, the model issues a read whose parameter is one of those paths.
- The host returns the file content.
- The model summarizes the content and produces the final answer.
What is genuinely unavoidable here is the two intermediate round trips in which results return to the model, plus one final answer. It is worth stressing that not every tool call consumes a full turn: if multiple calls are independent of each other, the model can declare them side by side in the same reply, and the host can execute them in parallel and return everything at once. The problem only arises on dependency chains — the longer the chain, the more times the model must be woken up.
This structure carries three hidden costs. First, intermediate results enter the conversation history; search output and file fragments all consume context budget. Second, every time the model is woken up it must redo the decision of “what should I do now,” and that decision has its own cost and variability. Third, the longer the chain, the higher the probability of being distracted by irrelevant information midway and drifting from the original intent.
2. The Idea Behind Code Mode: Moving Control Flow from the Conversation into a Program
The core of Code Mode is not “making the model write more code” but relocating where control flow lives. Control flow that was previously negotiated back and forth between model and host is moved inside a small program executed by the host; the model keeps only one entry and one exit.
The model still enters this mode through an ordinary tool call, except that the tool accepts a piece of code to execute and a timeout constraint. Schematically, the parameters look roughly like this:
{"code": "const hit = await tools.search({ pattern: 'start_call', dir: 'src' });\nconst path = hit.content[0].text.trim();\nconst file = await tools.read({ path });\nreturn { path, excerpt: file.content[0].text.slice(0, 4000) };","timeoutMs": 30000}
This code is usually treated as the body of an async function: inside it, await can wait sequentially for each sub-call, ordinary variables can hold intermediate results, standard control flow can handle conditional branches, loops, truncation, and aggregation, and it finally returns a value that can be serialized to JSON. The sub-calls are not real network requests but a tool namespace injected by the host, and their behavior is identical to calling the same-named tool directly in the conversation, including return structures, error shapes, and permission constraints.
The key change is what becomes visible in the context. On the conventional path, search results and file content enter the model’s context one by one. In Code Mode, the model only sees the object the program finally returns. Intermediate artifacts exist in the program’s runtime memory and are discarded after use. This has two direct effects: context usage is approximately decoupled from the number of steps, and the model’s decision count drops from “once per step” to “once for the whole program.”
3. Breaking Down the Execution Path: One Entry, One Exit
Expanding the example above into a timeline makes the responsibility boundaries clear:
- The model emits one tool call carrying the code and the timeout.
- The host performs static and policy validation: the allowlist of permitted tools, the accessible path scope, the timeout ceiling, and whether human confirmation is required.
- The host creates an isolated execution context and injects the tool namespace along with any necessary read-only views.
- The program executes sequentially: the first step searches and obtains candidate paths, and the second step reads content using such a path as its parameter.
- Inside the program, truncation, field selection, and formatting are completed, and a condensed object is returned.
- The host serializes the return value and sends it back to the session as the result of this tool call.
- The model produces the final conclusion based on the summary, or issues another program if necessary.
Compared with the conventional path, the two sub-calls inside step 4 are invisible to the model, which appears only at step 1 and step 7. This is the practical meaning of “writing the decisions into a program”: what previously required two model decisions is now completed by a piece of deterministic code within a single execution.
4. Capability Boundaries: What Fits and What Does Not
Code Mode is not a universal accelerator. It trades away round trips in exchange for visibility and flexibility. The criteria can be summarized in three points.
Suitable scenarios: clear data dependencies between steps; intermediate results that are large while the model only needs a small part of them; stable process shapes, such as “locate — read — extract,” “paginated fetch — filter — aggregate,” and “traverse multiple targets — process one by one — merge.”
Unsuitable scenarios: when the parameters of the second step require semantic judgment from the model rather than a mechanical transformation, for example when a completely different tool must be chosen based on an understanding of the first segment’s content; when the process needs user confirmation midway; when the error-handling strategy itself must be decided by the model on the spot. Forcing these cases into a program only hides uncertainty inside the code and makes problems harder to locate when they occur.
A practical compromise is segmentation: write the deterministic parts as one program and leave the points that require judgment to the model, forming an alternating “program — model — program” structure. This compresses mechanical round trips while preserving human visibility at the key nodes.
5. Failure Modes and Engineering Constraints
Programmatic execution shifts responsibility for error handling from the model to the code, which requires a more complete set of constraints on the host side.
- Timeouts and resources: there must be an overall timeout and a per-step timeout to keep a loop from dragging down the executor; the return size must also be capped to prevent an entire large file from being brought back into the context.
- Least privilege: the injected tool namespace should follow least privilege, with write operations, network access, and paths outside the repository disabled by default and explicitly enabled with an audit trail when needed.
- Observability: although intermediate results do not enter the model’s context, they should be written to execution logs, with support for tracing the parameters and state of each step by call identifier, which eases troubleshooting and auditing.
- Idempotency and side effects: if the program contains write operations, the impact of repeated execution must be considered; irreversible operations should require explicit confirmation or be changed to two-phase commit.
- Consistent error semantics: when a sub-call throws, it should preserve the same error structure as a direct call, so the program can catch and degrade in the usual way instead of producing an exception that is hard to identify.
- Serializable results: the return value must be a pure data structure, avoiding handles, stream objects, and other things that cannot be passed across the boundary.
6. Working with Context Engineering
Code Mode is essentially a means of managing the context budget. What it reduces is not only the number of round trips but also the attention dilution caused by irrelevant intermediate information staying resident. In practice it is usually combined with a few habits: complete filtering and truncation inside the program and return only the fields needed for the decision; use pagination and aggregation for long lists, returning statistics rather than the full set; and solidify stable extraction logic into reusable fragments to reduce the variability of the model reconstructing code each time.
In agent development practice on platforms such as Baidu AI Cloud, this kind of orchestration is often combined with general-purpose capabilities such as log services, monitoring and alerting, and object storage: every step of program execution can be recorded in logs, exceptions can be routed to alerting, and intermediate artifacts can be stored on demand without entering the model’s context.
7. Summary
Conventional tool calling hands the decision for each step back to the model, so data dependencies translate directly into round trips and context bloat. Code Mode writes control flow into a small program constrained by the host, letting the model enter once and exit once while receiving only a converged summary. Its benefits come from structure rather than anything mysterious: the dependency chain is folded into a single execution, and intermediate artifacts no longer occupy the conversation. The costs are equally clear: reduced visibility, limited flexibility, and higher demands on the host’s security and observability capabilities. The correct engineering posture is to split the process by degree of determinism — leave mechanical transformations to the program and semantic judgment to the model.
