Code Execution Paradigm for AI Agents: Refactoring Tool-Calling Efficiency

    This article explains the code execution paradigm for tool-augmented AI agents, a shift from direct, one-by-one tool calls to generating runnable code that orchestrates multiple calls locally. It covers the two efficiency bottlenecks this approach targets—tool-definition overload and intermediate-result consumption—along with five core advantages: progressive disclosure, context efficiency, stronger control flow, privacy protection, and state persistence. Typical scenarios, engineering constraints, security boundaries, and a phased adoption plan are also included to help teams evaluate where this reusable pattern delivers the most value.

    1. The Starting Problem: Why Tools Slow Agents Down

    In the engineering practice of tool-augmented agents, the model does not operate external systems directly. Instead, it completes tasks through a set of registered tools—retrieval, file read/write, API requests, computation, and so on. As the number of available tools grows, two efficiency problems quickly amplify.

    The first is tool-definition overload. To let the model know what it can do, every request typically has to carry the names, descriptions, and parameter schemas of all tools. The more tools there are, the larger this static overhead becomes. It crowds out the limited context window and dilutes the density of information that is actually relevant to the task, which lowers the accuracy of tool selection.

    The second is intermediate-result consumption. A typical agent runs a serial loop of “call—return—decide again.” When a single retrieval returns a large number of records, all of that content enters the context in full. If the task requires traversal, filtering, or aggregation, the model has to move data in and out of the context round after round. Token consumption grows linearly with data size, or even faster, and latency and cost rise in step.

    2. The Core Idea: From Direct Calls to Writing Code That Calls

    The basic premise of the code execution paradigm is to restructure the division of labor between the model and its tools. The model no longer issues tool calls one at a time. Instead, it first generates a runnable program that performs multiple tool calls, conditional checks, loops, and result filtering, and then returns only the necessary conclusions to the model’s context.

    There are two key design points. First, on-demand loading of tool definitions: tool descriptions do not have to stay resident in the context. During the code-writing stage they are retrieved and referenced in a manner similar to a “list of callable functions,” achieving progressive disclosure. Second, local data flow: intermediate data is passed and processed inside the local runtime and never enters the model context, which separates the “data-shuttling cost” from Token consumption.

    The illustrative pseudocode below expresses structure rather than any specific product interface:

    1. // Pseudocode: generate once, execute continuously and locally
    2. const files = await listFiles({ dir: "./docs" }); // Tool call 1
    3. const targets = files.filter(f => f.endsWith(".md")); // Local filtering, not sent to context
    4. for (const f of targets) {
    5. const content = await readFile({ path: f }); // Tool calls 2..N
    6. if (isStale(content)) await patchFile({ path: f, text: bumpVersion(content) });
    7. }
    8. const report = await runTests({ scope: "changed" }); // Tool call N+1
    9. return { changed: targets.length, passed: report.ok }; // Return only the conclusion

    3. Five Core Advantages

    Progressive disclosure: tool capabilities appear on demand, and the context keeps only the part relevant to the current task, avoiding the degradation where “more tools make the model dumber.”

    Context efficiency: intermediate results are no longer fed back round after round, so Token usage shifts from being “tied to data volume” to being “tied to conclusion volume.”

    Powerful control flow: classic programming capabilities such as loops, branches, retries, and concurrency can be applied directly to tool orchestration, offering far more expressive power than a linear call sequence.

    Privacy protection: raw data flows locally, reducing the scope of sensitive content that enters the model context and outbound requests.

    State persistence: variables and intermediate artifacts in a script persist within a single execution, naturally supporting multi-step, stateful jobs.

    4. Typical Scenarios and Engineering Benefits

    High-frequency data aggregation: for example, batch-reading records and then summing, deduplicating, or sorting them, returning only the aggregated value at the end.

    Investigation-style retrieval: sample first to make a judgment, then decide whether to widen the scope, with the conditional branch handled in code.

    Local file batch processing: batch-modifying configurations, standardizing metadata, scanning for dead links, filling in version numbers for skill descriptions, and so on.

    Real repository-level tasks tend to share the pattern of “many steps, much data, few conclusions,” which is exactly the range where this paradigm delivers the greatest benefit. Independent evaluations and similar practices in the industry have verified its effect on reducing context and call overhead from the perspectives of multiple models and multiple task types, showing that this is not an isolated trick but a reusable engineering pattern.

    5. Constraints and Risk Boundaries

    Restricted runtime environment: this capability is typically available only in a local interactive terminal or a controlled environment connected directly to an official account. Graphical interfaces, editor plugins, and third-party hosted runtimes are often unavailable.

    Experimental marking: it is generally enabled explicitly through an environment variable, and the documentation states that the feature may change or be removed, so production adoption requires feature flags and a fallback path.

    Capability rollback: once enabled, some extension capabilities that depend on the interface or remote control are disabled, so the impact on existing workflows must be assessed.

    Security boundaries: letting the model generate and execute code must be paired with a sandbox, least privilege, a dependency allowlist, and human confirmation—especially for operations that write files or run tests.

    6. Implementation Recommendations

    In general engineering practice on cloud platforms such as Baidu AI Cloud, this paradigm can be combined with common capabilities: use a container platform to host the isolated runtime, use object storage to keep intermediate artifacts, use logging and monitoring with alerting to track execution traces and cost, and use a message queue to decouple long-running tasks. For rollout, it is advisable to start with a small-scale canary: pilot tasks that have “many steps, large data, small conclusions,” measure three metrics—context usage, number of call rounds, and end-to-end latency—then gradually expand the scope, while always keeping the traditional direct-call mode as a fallback.

    Overall, the value of the code execution paradigm lies not in replacing tool calls but in pushing “orchestration logic” down from the model’s round-by-round decisions into executable code, letting the model focus on judgment and generation while handing repetitive shuttling over to the program.