E2B Cheat Sheet — Sandbox & Code Execution Reference
from e2b_code_interpreter import Sandbox
from e2b_code_interpreter import CodeInterpreter
import os Spawn isolated cloud sandboxes to safely execute LLM-generated code.
Like Docker containers, but pre-provisioned, cloud-hosted, and instantly available: think Replit for AI agents.
Core Patterns
from e2b_code_interpreter import Sandbox
import os
with Sandbox(api_key=os.environ["E2B_API_KEY"]) as sandbox:
result = sandbox.run_code("python", "print('Hello from sandbox')")
print(result.output) Hello from sandbox from e2b_code_interpreter import CodeInterpreter
import os
with CodeInterpreter(api_key=os.environ["E2B_API_KEY"]) as interpreter:
execution = interpreter.run("x = [1, 2, 3]; print(sum(x))")
print(execution.text) 6 from e2b_code_interpreter import CodeInterpreter
import os
with CodeInterpreter(api_key=os.environ["E2B_API_KEY"]) as interpreter:
# Upload file to /tmp
interpreter.upload_file("data.csv", "/tmp/data.csv")
# Code can now read it
result = interpreter.run("""
import pandas as pd
df = pd.read_csv('/tmp/data.csv')
print(df.head())
""")
print(result.text) from e2b_code_interpreter import CodeInterpreter
import os
with CodeInterpreter(api_key=os.environ["E2B_API_KEY"]) as interpreter:
# Use .arun() for async execution with streaming
result = interpreter.run("""
import time
for i in range(3):
print(f'Step {i}')
time.sleep(1)
""")
print(result.text) from e2b_code_interpreter import CodeInterpreter
import os
with CodeInterpreter(api_key=os.environ["E2B_API_KEY"]) as interpreter:
# Install package
interpreter.run("pip install requests")
# Use it
result = interpreter.run("import requests; print(requests.__version__)")
print(result.text) from e2b_code_interpreter import CodeInterpreter
import os
with CodeInterpreter(api_key=os.environ["E2B_API_KEY"]) as interpreter:
try:
result = interpreter.run("1 / 0")
except Exception as e:
print(f"Execution error: {e}")
# Check result object
result = interpreter.run("undefined_var")
if result.error:
print(f"Runtime error: {result.error}")
else:
print(f"Output: {result.text}") API Reference
| Method / Property | Description | Returns |
|---|---|---|
Sandbox(api_key=...) | Create bare sandbox. Lower-level control, used for raw shell commands. | Sandbox object with context manager support |
CodeInterpreter(api_key=..., template=None) | High-level sandbox with Python/JS support, state persistence, better errors. | CodeInterpreter object; template= sets OS (default: Python-enabled Linux) |
sandbox.run_code(language, code, timeout=60) | Execute code in specified language (python, javascript, bash). | ExecutionResult {text, error, exit_code} |
interpreter.run(code, timeout=60) | Execute Python code, maintain state across runs. | ExecutionResult {text, error, exit_code} |
interpreter.upload_file(local_path, remote_path) | Upload file from local machine to sandbox /tmp. | None; raises exception if upload fails |
interpreter.download_file(remote_path, local_path) | Download file from sandbox to local machine. | None; raises exception if path doesn't exist |
interpreter.reset() | Clear interpreter state; all variables & imports reset. | None |
Key Parameters
CodeInterpreter & Sandbox initialization
| Parameter | Type | Default | Notes |
|---|---|---|---|
api_key | str (required) | os.environ['E2B_API_KEY'] | Your E2B API key; get from e2b.dev/dashboard |
timeout | int (seconds) | 60 | Max execution time; raises TimeoutError if exceeded |
template | str | Python | OS template: 'Python', 'Node.js', 'Ubuntu': affects preinstalled runtimes |
metadata | dict | {} | Custom metadata tags for billing/debugging; e.g. {"user_id": "123"} |
Common Errors & Fixes
Authentication Error: Invalid API key Cause: E2B_API_KEY env var not set, expired, or wrong format.
import os
print(os.environ.get('E2B_API_KEY')) # Verify it exists
# If missing, set in .env:
os.environ['E2B_API_KEY'] = 'your_key_here' # Get from https://e2b.dev/dashboard Timeout: Execution exceeded X seconds Cause: Code took longer than timeout parameter (default 60s).
from e2b_code_interpreter import CodeInterpreter
import os
with CodeInterpreter(api_key=os.environ['E2B_API_KEY']) as interpreter:
# Increase timeout for long-running code
result = interpreter.run('import time; time.sleep(120)', timeout=180)
print(result.text) ConnectionError: Failed to connect to sandbox Cause: Network issue, E2B service down, or sandbox provisioning failed.
import time
from e2b_code_interpreter import CodeInterpreter
import os
try:
with CodeInterpreter(api_key=os.environ['E2B_API_KEY']) as interpreter:
result = interpreter.run('print("OK")')
except ConnectionError:
time.sleep(2)
# Retry once
with CodeInterpreter(api_key=os.environ['E2B_API_KEY']) as interpreter:
result = interpreter.run('print("OK")') RuntimeError: Code execution failed (exit_code > 0) Cause: Python error in LLM-generated code (NameError, SyntaxError, etc).
from e2b_code_interpreter import CodeInterpreter
import os
with CodeInterpreter(api_key=os.environ['E2B_API_KEY']) as interpreter:
result = interpreter.run('print(undefined_var)')
if result.error:
print(f'Code failed: {result.error}')
if result.exit_code != 0:
print(f'Exit code: {result.exit_code} (non-zero = failure)') FileNotFoundError: Upload failed: file too large Cause: File exceeds sandbox upload size limit (~1GB per file).
import os
from e2b_code_interpreter import CodeInterpreter
# Check file size before upload
file_path = 'large_file.bin'
if os.path.getsize(file_path) > 500_000_000: # 500MB threshold
print('File too large. Consider splitting or using direct download in sandbox.')
# Alternative: download directly in sandbox
with CodeInterpreter(api_key=os.environ['E2B_API_KEY']) as interpreter:
interpreter.run('wget https://example.com/large_file.bin')
else:
with CodeInterpreter(api_key=os.environ['E2B_API_KEY']) as interpreter:
interpreter.upload_file(file_path, '/tmp/large_file.bin') Production Gotchas
Variables, imports, and functions defined in one interpreter.run() call exist in the next. This is powerful but breaks isolation if you expect fresh state. Call interpreter.reset() between independent code executions.
Don't check just result.error: syntax errors, runtime failures, and print() output all mix in result.text. Parse carefully: check exit_code != 0 first, then inspect text/error fields.
When exiting the `with` block, the sandbox is destroyed. Call interpreter.download_file() before exiting if you need results. No persistent storage across sandbox lifetimes.
Every pip install() call blocks for seconds. If your LLM generates code needing custom packages, pre-bake them in a custom template or cache installed packages in a reusable interpreter instance.
Use interpreter.arun() for async code, interpreter.run() for sync. Don't mix them in the same function. Streaming requires async context; sync .run() blocks until complete.
Each sandbox spawned = cost per minute of runtime. Reuse interpreter instances when possible. Context managers auto-cleanup, so don't hold sandboxes open unnecessarily.