Skip to Content
Coding Agents

Last Updated: 3/7/2026


Coding Agents

E2B sandboxes are perfect for building AI coding agents that can write, test, and execute code safely.

Why Use E2B for Coding Agents?

Isolated Execution

  • Each agent runs in its own secure sandbox
  • No risk to your host system
  • Perfect for untrusted or AI-generated code

Fast Startup

  • Sandboxes start in seconds
  • On-demand creation and destruction
  • Optimized for agent workflows

Full Linux Environment

  • Complete access to filesystem
  • Install any packages or tools
  • Run any programming language

Basic Example

import { Sandbox } from 'e2b' // Create a sandbox for code execution const sandbox = await Sandbox.create() // AI-generated code const code = ` import pandas as pd import matplotlib.pyplot as plt # Create sample data data = {'x': [1, 2, 3, 4, 5], 'y': [2, 4, 6, 8, 10]} df = pd.DataFrame(data) # Create plot plt.plot(df['x'], df['y']) plt.savefig('output.png') print('Plot saved!') ` // Write code to file await sandbox.files.write('/home/user/script.py', code) // Execute the code const result = await sandbox.commands.run('python /home/user/script.py') console.log(result.stdout) // Download the generated plot const plotData = await sandbox.files.read('/home/user/output.png') await sandbox.close()

Advanced Patterns

Persistent Code Context

Keep a sandbox alive across multiple agent interactions:

// Create once const sandbox = await Sandbox.create() // Multiple operations await sandbox.commands.run('pip install numpy pandas') await sandbox.files.write('/home/user/data.csv', csvData) await sandbox.commands.run('python analyze.py') // Close when done await sandbox.close()

Template with Pre-installed Tools

Create a custom template with all your tools pre-installed:

FROM ubuntu:22.04 RUN apt-get update && apt-get install -y \ python3 python3-pip \ nodejs npm \ git RUN pip3 install pandas numpy matplotlib scikit-learn

Then use it:

const sandbox = await Sandbox.create({ template: 'your-template-id' })

Integration with AI Frameworks

LangChain

import { Sandbox } from 'e2b' import { Tool } from 'langchain/tools' class E2BCodeExecutor extends Tool { name = 'code_executor' description = 'Executes Python code in a secure sandbox' async _call(code) { const sandbox = await Sandbox.create() try { const result = await sandbox.commands.run(`python -c "${code}"`) return result.stdout || result.stderr } finally { await sandbox.close() } } }

OpenAI Function Calling

const functions = [{ name: 'execute_code', description: 'Execute Python code in a secure sandbox', parameters: { type: 'object', properties: { code: { type: 'string', description: 'Python code to execute' } }, required: ['code'] } }] // Handle function call async function executeCode(code) { const sandbox = await Sandbox.create() const result = await sandbox.commands.run(`python -c "${code}"`) await sandbox.close() return result.stdout }

Best Practices

1. Resource Management

  • Always close sandboxes when done
  • Use try/finally blocks to ensure cleanup
  • Set timeouts for long-running operations

2. Error Handling

  • Check exit codes: result.exitCode
  • Capture stderr: result.stderr
  • Implement retry logic for transient failures

3. Security

  • Never pass sensitive data directly in code strings
  • Use environment variables for secrets
  • Validate AI-generated code before execution

4. Performance

  • Reuse sandboxes for multiple operations
  • Use templates for faster startup
  • Enable caching for dependencies

Common Patterns

File-based Communication

// Write input await sandbox.files.write('/home/user/input.json', JSON.stringify(data)) // Process await sandbox.commands.run('python process.py') // Read output const output = await sandbox.files.read('/home/user/output.json') const result = JSON.parse(output)

Streaming Output

const process = await sandbox.commands.run('python long_script.py', { onStdout: (data) => console.log('stdout:', data), onStderr: (data) => console.error('stderr:', data) })

Multi-step Workflows

// Step 1: Install dependencies await sandbox.commands.run('pip install -r requirements.txt') // Step 2: Run tests const testResult = await sandbox.commands.run('pytest tests/') // Step 3: Execute main script if (testResult.exitCode === 0) { await sandbox.commands.run('python main.py') }