liveBook · Manning

Code execution

As explained in Build an AI Agent (From Scratch)

Code execution is the running of a program or code fragment in a computational environment to obtain behavior or results.

Code execution lets an agent write a program and run it, rather than ask an LLM to select one predefined tool at a time. A single program can loop over items, branch on conditions, retain intermediate results, and combine tools. This expands the agent’s action space while keeping routine processing out of repeated LLM calls. section 8.1 section 8.1.2

A minimal agent integration has four parts:

  • Store the sandbox in ExecutionContext so the execution tool can access it. section 8.2.3
  • Enable code execution through the Agent constructor and automatically register execute_python. section 8.2.3
  • Create the sandbox when a run starts, then close it in a finally block even if execution fails. section 8.2.3
  • Have execute_python run code in the sandbox and return structured results that distinguish output from errors. section 8.2.3
Listing 8.12 Managing the sandbox lifecycle in the run() method
async def run(
    self, 
    user_input: str, 
    context: Optional[ExecutionContext] = None
) -> AgentResult:
    if context is None:
        context = ExecutionContext()

    # Initialize sandbox
    if self.code_execution == "e2b" and context.code_env is None:
        from e2b_code_interpreter import Sandbox
        context.code_env = Sandbox.create(timeout=300)

    try:
        # Existing agent execution logic
        ...
    finally:
        # Clean up sandbox
        if context.code_env is not None:
            context.code_env.kill()

The run-method listing shows where sandbox creation and guaranteed cleanup fit around the existing agent loop. section 8.2.3

Run LLM-generated code in an isolated sandbox, not directly on the host. Generated code might delete the wrong file, loop indefinitely, or consume excessive memory; prompt injection adds another route to harmful behavior. Isolation protects host files and credentials, permits resource limits, and makes it possible to start again with a fresh environment. section 8.2.1

Code inside a remote sandbox cannot automatically call functions held in the agent’s local memory. Tools must be made executable in that sandbox before generated programs can compose them. This is particularly useful when many calls produce large results but the agent needs only a small aggregation. section 8.3 section 8.3.1

Count references across daily pages

Instead of making 31 LLM-mediated calls for 31 Wikipedia dates, generated Python loops over the dates, retrieves each revision, counts matching links, and returns compact counts. Full page contents remain in the sandbox rather than accumulating in the agent’s context. section 8.3.1 section 8.3.5

For file-based work, add a filesystem and CLI to make a fuller workspace. An agent can upload a spreadsheet, install needed packages, and analyze it with pandas without adding a dedicated reader tool for that format. Prefer ordinary tool calling for a single simple response, immediate user feedback, or work too small to justify execution overhead. section 8.4.3 section 8.3.5

How Build an AI Agent (From Scratch) covers it

How deep it goes
Builds through Agent configuration, sandbox lifecycle, execution results, tool portability, and practical tests.
Examples
Works through daily Wikipedia reference counts and spreadsheet sales analysis.
What it assumes
Assumes an existing Python Agent, ExecutionContext, and tool-calling setup; introduces sandbox integration rather than Python fundamentals.
What you can do after
Build it from scratch by adding sandbox-backed Python execution to an Agent and choosing when batching outweighs execution overhead.
How it connects
Connects tool calling, control flow, data flow, tool composition, sandbox isolation, and agent workspaces.

Also explained in

Compare how 3 books explain code execution →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build an AI Agent (From Scratch). The section links point to the parts of the book it draws on.