liveBook · Manning

Sandboxing

As explained in Build an AI Agent (From Scratch)

A sandbox environment is an isolated execution environment that restricts code or tool operations from affecting the surrounding system.

An agent that writes Python can do more than select predefined tools: it can use loops, retain intermediate results, and combine operations in one execution. But generated code is unpredictable. A mistaken file deletion, an infinite loop, excessive memory use, or code induced by prompt injection should not run unchecked on the host. Sandboxing moves execution into an isolated environment instead. section 8.2.1 section 8.6

A sandbox provides three practical protections:

  • Host protection: code cannot directly read sensitive host files such as SSH keys or system files. Network access can be restricted by domain. section 8.2.1
  • Resource control: CPU, memory, and execution-time limits contain runaway work. section 8.2.1
  • Recovery: if code deletes files or corrupts its environment, start a fresh sandbox. section 8.2.1

For a minimal E2B implementation, create a cloud sandbox with `Sandbox.create()`, submit Python with `run_code()`, inspect the returned execution, and call `kill()` when finished. Check `execution.logs.stdout` for printed output, `execution.results` for evaluated results, and `execution.error` for failures. Repeated `run_code()` calls in the same sandbox retain variables and functions, so later steps can reuse earlier work. section 8.2.2

Listing 8.5 Basic E2B sandbox flow
from e2b_code_interpreter import Sandbox

# Create sandbox
sandbox = Sandbox.create()
print(f"Sandbox ID: {sandbox.sandbox_id}")

# Execute code
code = """
result = 2 + 3
print(f"Calculation: 2 + 3 = {result}")
result
"""
execution = sandbox.run_code(code)

# Check results
print("Output:", execution.logs.stdout)
print("Return value:", execution.results[0].text)

# Terminate sandbox
sandbox.kill()

The runnable example shows the complete create–execute–inspect–terminate sequence before an agent is connected. section 8.2.2

Set a lifetime with `Sandbox.create(timeout=...)`; extend it with `sandbox.set_timeout()` when needed. The creation timeout does not reset while code runs. If sandboxed code must call an external API, pass the required key through `envs` and read it there with `os.environ`. Such a key is available to code inside that sandbox, so isolation should not be confused with withholding deliberately supplied credentials. section 8.2.2

Batch work inside the boundary

Configure an agent with `code_execution="e2b"` and a sandbox-executable Wikipedia revision tool. Generated Python loops over 31 pages, counts matching references in each page, and prints per-page counts and a total. Page contents are processed inside the sandbox; the agent context receives the smaller results rather than every full page. This is useful when many dependent operations need only an aggregation, but startup overhead makes it less attractive for one simple tool call. section 8.3.5 section 8.3

A sandbox can also serve as a workspace with files, a CLI, and Python packages. An agent can upload a spreadsheet, install a needed library, and analyze it with pandas without installing that package or running the code on the host. This replaces some format-specific local tools, while preserving state across the workspace session. section 8.4.3

How Build an AI Agent (From Scratch) covers it

How deep it goes
Works through E2B creation, execution results, state, timeouts, and cleanup; contrasts managed sandboxes with configuring Docker isolation directly.
Examples
Uses an E2B calculation, Wikipedia reference counting across 31 pages, and spreadsheet analysis with pandas.
What it assumes
Assumes working Python and agent code; introduces the E2B sandbox lifecycle, while requiring an E2B account and API key.
What you can do after
Build it from scratch with E2B to run agent code, inspect failures, retain session state, and contain host-side risks.
How it connects
Connects code execution, resource limits, prompt injection, tool composition, and agent workspaces.

Also explained in

Compare how 3 books explain sandboxing →

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.