E2B provides an isolated cloud sandbox where an agent can execute Python it has written. This gives the agent a working environment instead of requiring a separate predefined tool for every operation. The workspace can also support filesystem and command-line work. section 8.0 section 8.2.1
A minimal Python workflow is:
- Sign up for E2B, obtain an API key, and install `e2b-code-interpreter`. section 8.2.2
- Call `Sandbox.create()`, then pass Python to `sandbox.run_code(code)`. Read printed output from `execution.logs.stdout`, the last expression’s value from `execution.results`, and failures from `execution.error`. section 8.2.2
- Call `sandbox.kill()` when finished. Set `timeout` at creation or extend it with `set_timeout()`; pass values needed inside the sandbox through `envs`. section 8.2.2
Reuse a result across executions
Run `data = [1, 2, 3]` in one call, then `sum(data)` in another call to the same sandbox. The second call returns `6` because the session retains variables and functions. A failing call such as `x = 1 / 0` instead exposes its error name and message through `execution.error`. section 8.2.2
Isolation matters because generated code can consume resources or damage its environment. Sandbox limits and timeouts protect the host, and a corrupted sandbox can be replaced. E2B supplies a cloud API for this setup rather than requiring direct management of Docker containers and their isolation settings. section 8.2.1
For repeated work, an agent can generate one program containing the loop and execute it inside the sandbox, returning only extracted results. This avoids a separate model call for each iteration. A local Python function is not automatically available there: the cloud sandbox cannot see functions held only in local memory, so using existing tools requires a portability step. section 8.3.1
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 complete minimal listing shows sandbox creation, code execution, inspection of printed output and the final expression, and explicit termination. section 8.2.2
