Orchestrating Tool Calls in Code: Parallel Execution for Agent Batch Tasks
Learn how code-based tool orchestration lets AI agents run batch tasks in parallel. This article covers the costs of step-by-step tool calling, four practical scenarios, runtime design requirements, and risk controls for sandboxed script execution.
Background: The Cost of Step-by-Step Tool Calling
In a typical agent-assisted development workflow, the model issues one tool call at a time—executing a terminal command, reading a file, or editing a piece of code. Once the result comes back, the model decides on the next step. The benefit of this pattern is that every step is observable and can be interrupted, but the costs are significant.
First, latency grows linearly with the number of steps. For a renaming task involving dozens of files, if each file requires four round trips—search, read, modify, verify—the total waiting time is multiplied accordingly.
Second, the context window fills up with intermediate output. Search results, build logs, and test output mostly contain large amounts of text irrelevant to decision-making. This text continuously occupies the model’s context window, increasing cost and making key information harder to notice.
Third, independent operations are forced to run sequentially. Two checks that have no dependency on each other could run simultaneously, yet they must execute one after another.
The Core Idea of Code-Based Tool Orchestration
One way to address these problems is to have the model output a scheduling program first, which a local runtime then executes. The model writes the entire subtask as a script, and the runtime executes it in a controlled environment. Inside the script, it can:
- Launch multiple independent commands in parallel;
- Pass the output of one step directly as input to the next;
- Filter, sort, and truncate data locally;
- Return only conclusive information to the model’s context.
A pseudo-code example:
# Example: batch-replace a function namehits = parallel([run_shell("search for files containing old_name")])target = hits[0].path # take the first matching fileapply_replace(target, "old_name", "new_name")report = run_shell("run the test suite") # run tests after the changereturn {"changed": target, "test_summary": report.tail(20)}
The key point is that intermediate results stay in the runtime’s memory, and the model only sees the final summary. This keeps the model’s attention and context budget focused on the decision itself.
Four Applicable Scenarios
1. Repetitive Batch Modifications
When the same change must be applied to many files, confirming them one by one is the least efficient approach. A script can locate all targets first, apply modifications according to a unified rule, and then verify everything at once. The key is that the rule must be reproducible—avoid making inconsistent manual judgments for each file.
2. Large-Scale Searches That Need Pre-Filtering
Search results may contain thousands of lines. Rather than handing all of them to the model, filter locally by path, keyword, or count, and keep only the portion the model actually needs to evaluate. This saves context and reduces the chance that the model is distracted by irrelevant noise.
3. Independent Commands That Can Run in Parallel
Static analysis, type checking, and unit tests can be launched simultaneously when they don’t depend on each other. Parallelization shortens total runtime, but watch out for shared resource conflicts—for example, two commands writing to the same build directory can corrupt each other’s artifacts.
4. Long-Running Background Tasks
Long builds or test runs can be moved to the background. The script returns a task identifier, the model continues handling other questions in the conversation, and queries the result later. This requires the runtime to provide task status queries and timeout management.
Design and Execution Architecture Essentials
To implement this pattern, the runtime must meet several basic requirements.
Isolation and permissions. Scripts should run in a sandbox with access only to authorized directories and commands. Write operations should be restricted by default, and actions involving deletion, network requests, or permission changes should require explicit confirmation.
Resource limits. Set timeouts and output caps for every command. A runaway loop or infinite output should not bring down the entire session.
Structured returns. The runtime should organize results into well-defined structures, such as file lists, exit codes, and key error lines. Structured results make it easier for the model to reason and for humans to audit later.
Error handling. When a step in the script fails, whether subsequent steps continue should be decided explicitly by the script. Before batch modifications, record each file’s original content so it can be restored on failure.
Observability. Retain the generated scripts, execution timelines, and per-step outputs. Users need the ability to trace what the model actually did—this matters for both debugging and compliance.
Implementation Risks and Control Strategies
Amplified mistakes. A loop can replicate one wrong judgment across dozens of files. It’s recommended to do a trial run on a small sample first and proceed to full execution only after confirming correctness.
Non-idempotent operations. If a script fails midway, re-running it may produce duplicate modifications. Make modification operations idempotent where possible, or perform them under version control so rollback is simple and reliable.
Hidden dependency ordering. Parallel execution assumes commands are independent of one another. If hidden dependencies exist—for example, a file must be generated before it is read—parallelism causes intermittent failures. Dependencies should be declared explicitly in the script.
Trust boundaries. Script content is generated by the model and should not be trusted by default. Command whitelists, argument escaping, and path validation are necessary lines of defense that prevent command injection when external input is concatenated into commands.
When to Use It—and When Not To
Tasks suited to this pattern typically share three traits: the steps can be described clearly in advance, intermediate results far outnumber final results, and operations can be verified in bulk.
Unsuitable tasks include those where every step requires human judgment, where a single operation is sufficient, or where irreversible side effects cannot be rehearsed. In these scenarios, step-by-step calling is actually safer.
Practical Recommendations
- Validate search and filtering logic with read-only operations first, then move on to write operations.
- Set a sample-size cap for batch modifications; process only a small number of files in the first round.
- Include tests and static checks at the end of the script so results are reported back automatically.
- Control the length of script output to avoid returning too much content at once.
- Regularly review auto-generated scripts, especially those involving file deletion and network access.
