# E2B SDK Documentation E2B is an open-source infrastructure that allows you to run AI-generated code in secure isolated sandboxes in the cloud. The SDK provides JavaScript/TypeScript and Python libraries for creating, managing, and interacting with cloud-based sandbox environments. These sandboxes give AI agents and applications access to a full Linux OS with filesystem operations, command execution, git operations, and internet connectivity. The E2B SDK consists of three main components: the JavaScript SDK (`e2b` npm package), the Python SDK (`e2b` pip package), and the CLI tool (`@e2b/cli`). The SDKs support both synchronous and asynchronous APIs, allowing developers to create sandboxes, run commands, manipulate files, execute git operations, and build custom sandbox templates programmatically. ## Sandbox Creation Create a new sandbox instance from the default base template or a custom template. Sandboxes are secure isolated cloud environments where you can run commands, manage files, and execute code. ```python from e2b import Sandbox # Create sandbox from default base template sandbox = Sandbox.create() # Create sandbox with custom template and options sandbox = Sandbox.create( template="my-custom-template", timeout=600, # 10 minutes in seconds metadata={"project": "my-app"}, envs={"API_KEY": "secret123"} ) # Use context manager for automatic cleanup with Sandbox.create() as sandbox: result = sandbox.commands.run('echo "Hello from E2B!"') print(result.stdout) # Hello from E2B! # Sandbox is automatically killed when exiting the context ``` ```typescript import Sandbox from 'e2b' // Create sandbox from default base template const sandbox = await Sandbox.create() // Create sandbox with custom template and options const sandbox = await Sandbox.create('my-custom-template', { timeoutMs: 600000, // 10 minutes metadata: { project: 'my-app' }, envs: { API_KEY: 'secret123' } }) // Run a command const result = await sandbox.commands.run('echo "Hello from E2B!"') console.log(result.stdout) // Hello from E2B! // Clean up await sandbox.kill() ``` ## Command Execution Run shell commands in the sandbox with support for environment variables, working directory, custom users, and real-time output streaming. ```python from e2b import Sandbox with Sandbox.create() as sandbox: # Run command and wait for completion result = sandbox.commands.run('ls -la /home/user') print(f"Exit code: {result.exit_code}") print(f"Stdout: {result.stdout}") print(f"Stderr: {result.stderr}") # Run command with options result = sandbox.commands.run( 'npm install', cwd='/home/user/app', envs={'NODE_ENV': 'production'}, user='root', timeout=120 # 2 minutes ) # Run command in background handle = sandbox.commands.run('python server.py', background=True) # Stream output with callbacks result = sandbox.commands.run( 'pip install numpy', on_stdout=lambda data: print(f"OUT: {data}"), on_stderr=lambda data: print(f"ERR: {data}") ) # List running processes processes = sandbox.commands.list() for proc in processes: print(f"PID: {proc.pid}, Command: {proc.cmd}") # Kill a specific process sandbox.commands.kill(pid=1234) ``` ```typescript import Sandbox from 'e2b' const sandbox = await Sandbox.create() // Run command and wait for completion const result = await sandbox.commands.run('ls -la /home/user') console.log(`Exit code: ${result.exitCode}`) console.log(`Stdout: ${result.stdout}`) console.log(`Stderr: ${result.stderr}`) // Run command with options const result2 = await sandbox.commands.run('npm install', { cwd: '/home/user/app', envs: { NODE_ENV: 'production' }, user: 'root', timeoutMs: 120000 // 2 minutes }) // Run command in background const handle = await sandbox.commands.run('python server.py', { background: true }) // Stream output with callbacks await sandbox.commands.run('pip install numpy', { onStdout: (data) => console.log(`OUT: ${data}`), onStderr: (data) => console.log(`ERR: ${data}`) }) // List running processes const processes = await sandbox.commands.list() processes.forEach(proc => console.log(`PID: ${proc.pid}, Command: ${proc.cmd}`)) // Kill a specific process await sandbox.commands.kill(1234) await sandbox.kill() ``` ## Filesystem Operations Read, write, list, and manage files and directories in the sandbox filesystem. ```python from e2b import Sandbox with Sandbox.create() as sandbox: # Write a file sandbox.files.write('/home/user/hello.txt', 'Hello, World!') # Write multiple files at once sandbox.files.write_files([ {'path': '/home/user/file1.txt', 'data': 'Content 1'}, {'path': '/home/user/file2.txt', 'data': 'Content 2'} ]) # Read file as text content = sandbox.files.read('/home/user/hello.txt') print(content) # Hello, World! # Read file as bytes binary_content = sandbox.files.read('/home/user/image.png', format='bytes') # List directory contents entries = sandbox.files.list('/home/user') for entry in entries: print(f"{entry.name} - {entry.type} - {entry.size} bytes") # List directory recursively entries = sandbox.files.list('/home/user', depth=3) # Check if file exists exists = sandbox.files.exists('/home/user/hello.txt') # Get file info info = sandbox.files.get_info('/home/user/hello.txt') print(f"Size: {info.size}, Permissions: {info.permissions}") # Create directory sandbox.files.make_dir('/home/user/new_folder') # Rename/move file sandbox.files.rename('/home/user/hello.txt', '/home/user/greeting.txt') # Remove file or directory sandbox.files.remove('/home/user/greeting.txt') # Watch directory for changes watcher = sandbox.files.watch_dir('/home/user', recursive=True) for event in watcher: print(f"Event: {event.type} - {event.path}") if some_condition: watcher.stop() break ``` ```typescript import Sandbox from 'e2b' const sandbox = await Sandbox.create() // Write a file await sandbox.files.write('/home/user/hello.txt', 'Hello, World!') // Write multiple files at once await sandbox.files.write([ { path: '/home/user/file1.txt', data: 'Content 1' }, { path: '/home/user/file2.txt', data: 'Content 2' } ]) // Read file as text const content = await sandbox.files.read('/home/user/hello.txt') console.log(content) // Hello, World! // Read file as bytes const binaryContent = await sandbox.files.read('/home/user/image.png', { format: 'bytes' }) // List directory contents const entries = await sandbox.files.list('/home/user') entries.forEach(entry => console.log(`${entry.name} - ${entry.type} - ${entry.size} bytes`)) // List directory recursively const allEntries = await sandbox.files.list('/home/user', { depth: 3 }) // Check if file exists const exists = await sandbox.files.exists('/home/user/hello.txt') // Get file info const info = await sandbox.files.getInfo('/home/user/hello.txt') console.log(`Size: ${info.size}, Permissions: ${info.permissions}`) // Create directory await sandbox.files.makeDir('/home/user/new_folder') // Rename/move file await sandbox.files.rename('/home/user/hello.txt', '/home/user/greeting.txt') // Remove file or directory await sandbox.files.remove('/home/user/greeting.txt') // Watch directory for changes const watcher = await sandbox.files.watchDir('/home/user', (event) => { console.log(`Event: ${event.type} - ${event.path}`) }, { recursive: true }) // Stop watching watcher.stop() await sandbox.kill() ``` ## Git Operations Clone repositories, manage branches, commit changes, and push/pull with optional authentication. ```python from e2b import Sandbox with Sandbox.create() as sandbox: # Clone a repository sandbox.git.clone('https://github.com/user/repo.git', path='/home/user/repo') # Clone with options sandbox.git.clone( 'https://github.com/user/private-repo.git', path='/home/user/private-repo', branch='main', depth=1, # Shallow clone username='user', password='token' ) # Initialize a new repository sandbox.git.init('/home/user/new-repo', initial_branch='main') # Configure git user sandbox.git.configure_user('John Doe', 'john@example.com') # Get repository status status = sandbox.git.status('/home/user/repo') print(f"Branch: {status.branch}, Modified: {status.modified}") # List branches branches = sandbox.git.branches('/home/user/repo') print(f"Current: {branches.current}, All: {branches.all}") # Create and checkout branch sandbox.git.create_branch('/home/user/repo', 'feature-branch') sandbox.git.checkout_branch('/home/user/repo', 'main') # Stage and commit changes sandbox.git.add('/home/user/repo') # Stage all changes sandbox.git.add('/home/user/repo', files=['file1.py', 'file2.py']) sandbox.git.commit('/home/user/repo', 'Add new feature') # Push changes with authentication sandbox.git.push('/home/user/repo', remote='origin', branch='main', username='user', password='token', set_upstream=True ) # Pull changes sandbox.git.pull('/home/user/repo', remote='origin', branch='main', username='user', password='token' ) # Add remote sandbox.git.remote_add('/home/user/repo', 'upstream', 'https://github.com/other/repo.git') ``` ```typescript import Sandbox from 'e2b' const sandbox = await Sandbox.create() // Clone a repository await sandbox.git.clone('https://github.com/user/repo.git', { path: '/home/user/repo' }) // Clone with options await sandbox.git.clone('https://github.com/user/private-repo.git', { path: '/home/user/private-repo', branch: 'main', depth: 1, // Shallow clone username: 'user', password: 'token' }) // Initialize a new repository await sandbox.git.init('/home/user/new-repo', { initialBranch: 'main' }) // Configure git user await sandbox.git.configureUser('John Doe', 'john@example.com') // Get repository status const status = await sandbox.git.status('/home/user/repo') console.log(`Branch: ${status.branch}, Modified: ${status.modified}`) // List branches const branches = await sandbox.git.branches('/home/user/repo') console.log(`Current: ${branches.current}, All: ${branches.all}`) // Create and checkout branch await sandbox.git.createBranch('/home/user/repo', 'feature-branch') await sandbox.git.checkoutBranch('/home/user/repo', 'main') // Stage and commit changes await sandbox.git.add('/home/user/repo') // Stage all changes await sandbox.git.add('/home/user/repo', { files: ['file1.ts', 'file2.ts'] }) await sandbox.git.commit('/home/user/repo', 'Add new feature') // Push changes with authentication await sandbox.git.push('/home/user/repo', { remote: 'origin', branch: 'main', username: 'user', password: 'token', setUpstream: true }) // Pull changes await sandbox.git.pull('/home/user/repo', { remote: 'origin', branch: 'main', username: 'user', password: 'token' }) await sandbox.kill() ``` ## Sandbox Management Manage sandbox lifecycle including pausing, resuming, connecting, snapshots, and monitoring. ```python from e2b import Sandbox # Create sandbox sandbox = Sandbox.create(timeout=300) # Get sandbox ID for later reconnection sandbox_id = sandbox.sandbox_id # Check if sandbox is running is_running = sandbox.is_running() # Get sandbox info info = sandbox.get_info() print(f"Template: {info.template}, Started: {info.started_at}") # Get sandbox metrics (CPU, memory, disk) metrics = sandbox.get_metrics() for m in metrics: print(f"CPU: {m.cpu_pct}%, Memory: {m.mem_used_mib}MiB") # Extend sandbox timeout sandbox.set_timeout(600) # Pause sandbox (preserves state) sandbox.pause() # Connect to existing sandbox (resumes if paused) same_sandbox = Sandbox.connect(sandbox_id) # Create snapshot for later use snapshot = sandbox.create_snapshot() print(f"Snapshot ID: {snapshot.snapshot_id}") # Create new sandbox from snapshot new_sandbox = Sandbox.create(snapshot.snapshot_id) # List all snapshots for snap in sandbox.list_snapshots(): print(f"ID: {snap.snapshot_id}, Created: {snap.created_at}") # Delete snapshot Sandbox.delete_snapshot(snapshot.snapshot_id) # Kill sandbox sandbox.kill() # List all running sandboxes for sbx in Sandbox.list(): print(f"ID: {sbx.sandbox_id}, Template: {sbx.template}") ``` ```typescript import Sandbox from 'e2b' // Create sandbox const sandbox = await Sandbox.create({ timeoutMs: 300000 }) // Get sandbox ID for later reconnection const sandboxId = sandbox.sandboxId // Check if sandbox is running const isRunning = await sandbox.isRunning() // Get sandbox info const info = await sandbox.getInfo() console.log(`Template: ${info.template}, Started: ${info.startedAt}`) // Get sandbox metrics (CPU, memory, disk) const metrics = await sandbox.getMetrics() metrics.forEach(m => console.log(`CPU: ${m.cpuPct}%, Memory: ${m.memUsedMiB}MiB`)) // Extend sandbox timeout await sandbox.setTimeout(600000) // Pause sandbox (preserves state) await sandbox.pause() // Connect to existing sandbox (resumes if paused) const sameSandbox = await Sandbox.connect(sandboxId) // Create snapshot for later use const snapshot = await sandbox.createSnapshot() console.log(`Snapshot ID: ${snapshot.snapshotId}`) // Create new sandbox from snapshot const newSandbox = await Sandbox.create(snapshot.snapshotId) // List all snapshots const snapshots = sandbox.listSnapshots() for await (const snap of snapshots) { console.log(`ID: ${snap.snapshotId}, Created: ${snap.createdAt}`) } // Kill sandbox await sandbox.kill() // List all running sandboxes const sandboxList = Sandbox.list() for await (const sbx of sandboxList) { console.log(`ID: ${sbx.sandboxId}, Template: ${sbx.template}`) } ``` ## Template Building Build custom sandbox templates programmatically using a fluent API to define the environment configuration. ```python from e2b import Template, wait_for_port, wait_for_url # Create template from Python base image template = ( Template() .from_python_image('3.11') .copy('requirements.txt', '/home/user/') .run_cmd('pip install -r /home/user/requirements.txt') .copy('app.py', '/home/user/') .set_workdir('/home/user') .set_start_cmd('python app.py', wait_for_port(8000)) ) # Build and deploy the template build_info = Template.build(template, 'my-python-app:v1.0') print(f"Template ID: {build_info.template_id}") # Build with multiple tags build_info = Template.build( template, 'my-python-app', tags=['v1.0', 'latest', 'stable'], cpu_count=2, memory_mb=2048 ) # Template from Node.js with npm packages node_template = ( Template() .from_node_image('20') .copy('package.json', '/app/') .set_workdir('/app') .npm_install() # Install from package.json .copy('src/', '/app/src/') .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health', 200)) ) # Template with apt packages system_template = ( Template() .from_ubuntu_image('24.04') .apt_install(['git', 'curl', 'vim']) .run_cmd('curl -fsSL https://example.com/install.sh | bash') ) # Template from Dockerfile dockerfile_template = Template().from_dockerfile('Dockerfile') # Template from existing template extended_template = ( Template() .from_template('my-base-template') .pip_install(['pandas', 'numpy']) ) # Template from private registry private_template = ( Template() .from_image('myregistry.com/myimage:latest', username='user', password='token') .run_cmd('echo "Hello"') ) # Build in background (non-blocking) build_info = Template.build_in_background(template, 'async-template') status = Template.get_build_status(build_info) print(f"Status: {status.status}") # Check if template exists exists = Template.exists('my-python-app') # Manage template tags Template.assign_tags('my-python-app:v1.0', ['production', 'stable']) Template.remove_tags('my-python-app', ['old-tag']) tags = Template.get_tags('my-python-app') ``` ```typescript // TypeScript template building is done via CLI or API // Use the e2b CLI for template management: // e2b template build - Build template from Dockerfile // e2b template list - List all templates // e2b template delete - Delete a template ``` ## CLI Commands The E2B CLI provides commands for authentication, sandbox management, and template operations. ```bash # Install CLI npm install -g @e2b/cli # or brew install e2b # Authentication e2b auth login # Login to E2B e2b auth logout # Logout from E2B e2b auth info # Show current authentication info # Sandbox management e2b sandbox list # List running sandboxes e2b sandbox create # Create a new sandbox e2b sandbox kill # Kill a sandbox e2b sandbox connect # Connect to a sandbox e2b sandbox logs # View sandbox logs e2b sandbox metrics # View sandbox metrics # Template management e2b template init # Initialize template in current directory e2b template build # Build template from e2b.toml/Dockerfile e2b template list # List all templates e2b template delete # Delete a template # Example: Build custom template # 1. Create e2b.toml and Dockerfile in your project # 2. Run build command e2b template build --name my-template --tag v1.0 # Using environment variable for CI/CD E2B_ACCESS_TOKEN=sk_e2b_... e2b template build ``` ## Async Python API The Python SDK provides both synchronous and asynchronous APIs for all operations. ```python import asyncio from e2b import AsyncSandbox async def main(): # Create sandbox asynchronously sandbox = await AsyncSandbox.create() # Run commands result = await sandbox.commands.run('echo "Hello async!"') print(result.stdout) # File operations await sandbox.files.write('/home/user/test.txt', 'Async content') content = await sandbox.files.read('/home/user/test.txt') # Background command with streaming handle = await sandbox.commands.run('python server.py', background=True) # Concurrent operations results = await asyncio.gather( sandbox.commands.run('command1'), sandbox.commands.run('command2'), sandbox.commands.run('command3') ) # Cleanup await sandbox.kill() asyncio.run(main()) ``` ## Summary The E2B SDK enables developers to create secure, isolated cloud sandbox environments for AI-generated code execution. The primary use cases include building AI coding assistants, code interpreters, development environments, and automated testing systems. The SDK integrates seamlessly with LLM frameworks like LangChain, providing sandboxed execution environments where AI agents can safely run generated code, manipulate files, and interact with the system. Integration patterns typically involve creating sandboxes on-demand for code execution tasks, using templates to pre-configure environments with specific dependencies, and leveraging snapshots for quick environment restoration. The SDK supports both request-response patterns for synchronous operations and streaming patterns for long-running commands, making it suitable for interactive applications and batch processing workflows alike.