E2B - Secure sandboxes for AI-generated code execution
Open-source infrastructure for running AI-generated code in secure isolated cloud sandboxes, enabling safe execution of LLM outputs for enterprise-grade AI agents.
- Step 1
Overview
E2B (Execute to Build) is an open-source infrastructure platform that enables developers to run AI-generated code in secure, isolated sandboxes in the cloud. It provides a safe environment for executing code produced by LLMs without risking host system security. E2B is designed for building enterprise-grade AI agents with robust isolation guarantees, supporting multiple cloud providers and self-hosting options.
- Step 2
Technology Stack
E2B is built with a modern, polyglot technology stack optimized for security and performance:
Primary Languages: - Python: 54.9% (SDK and tooling) - TypeScript: 43.8% (SDK and web interfaces) - Go: 0.6% (infrastructure services) - Docker: 0.3% (containerization) - JavaScript: 0.2% Core Technologies: - Firecracker VMs (secure microVM isolation) - Terraform (infrastructure as code) - PostgreSQL (metadata and state) - Docker + Buildx (container images) Cloud Providers: - ✓ Google Cloud Platform (GCP) - fully supported - ✓ Amazon Web Services (AWS) - beta - Azure - planned - Linux machines - planned License: Apache 2.0 GitHub Stars: ~12,330 Repository: https://github.com/e2b-dev/E2B - Step 3
Key Features
E2B provides comprehensive capabilities for safe AI code execution:
Security: - Isolated Firecracker microVMs for each sandbox - Secure execution of untrusted AI-generated code - Network isolation and resource limits - Per-sandbox filesystem isolation Development: - Multi-language SDK support (Python, JavaScript/TypeScript) - Command execution within sandboxes - Python code interpreter with streaming output - File upload/download operations - Custom environment templates - Real-time sandbox management Integrations: - OpenAI (GPT-4, o1, o3-mini) - Anthropic (Claude 3.x, Claude Code) - Mistral, Groq, Together AI, WatsonX - LangChain, LangGraph, AutoGen - Vercel AI SDK, Model Context Protocol (MCP) - Playwright browser automation Deployment: - Managed cloud service (e2b.dev) - Self-hosted infrastructure - Terraform-based provisioning - Multi-cloud support - Step 4
Use Cases
E2B is designed for scenarios requiring safe execution of AI-generated or untrusted code:
1. AI Agent Development - Building autonomous agents that write and execute code - LLM-powered coding assistants - Automated code generation and testing 2. Data Analysis - AI-driven data exploration and visualization - Dataset analysis with LLM guidance - Automated report generation 3. Web Automation - AI-controlled browser automation (Playwright) - Web scraping with dynamic code generation - Testing and QA automation 4. Enterprise AI Applications - Internal tools with code execution - Customer-facing AI features - Regulated environments requiring isolation 5. Educational Platforms - Safe code execution for learning platforms - Interactive coding tutorials - AI tutoring systems - Step 5
Managed Service Setup
The fastest way to get started is using E2B's managed cloud service. This approach requires no infrastructure management.
- Step 6
1. Create an E2B Account
Sign up at e2b.dev to receive $100 in free credits for testing and development. After creating your account, navigate to the E2B Dashboard to access your API key.
# Visit https://e2b.dev and create an account # Navigate to Dashboard → API Keys # Copy your API key (starts with e2b_) - Step 7
2. Install the SDK
E2B provides two main SDKs: the base SDK for command execution and the Code Interpreter SDK for Python code execution. Install based on your use case.
# JavaScript/TypeScript - Base SDK npm install e2b # JavaScript/TypeScript - Code Interpreter SDK npm install @e2b/code-interpreter dotenv # Python - Base SDK pip install e2b # Python - Code Interpreter SDK pip install e2b-code-interpreter python-dotenv - Step 8
3. Configure API Key
Store your API key securely in environment variables. Never commit API keys to version control.
# Create a .env file in your project root echo "E2B_API_KEY=e2b_your_api_key_here" > .env # Add .env to .gitignore echo ".env" >> .gitignore # For production, set environment variable on your platform # Vercel: vercel env add E2B_API_KEY # AWS Lambda: Use environment variables in function config # Docker: Pass via -e flag or docker-compose - Step 9
4. Basic Sandbox Usage
The base SDK allows you to create sandboxes and execute shell commands. Each sandbox is an isolated Linux VM.
// TypeScript - Basic command execution import Sandbox from 'e2b'; const sandbox = await Sandbox.create(); try { // Execute a shell command const result = await sandbox.commands.run('echo "Hello from E2B!"'); console.log('Output:', result.stdout); console.log('Exit code:', result.exitCode); // Run multiple commands const install = await sandbox.commands.run('apt-get update && apt-get install -y curl'); const check = await sandbox.commands.run('curl --version'); console.log(check.stdout); } finally { await sandbox.close(); } - Step 10
Basic Sandbox Usage (Python)
Python SDK with context manager for automatic cleanup:
# Python - Basic command execution from e2b import Sandbox # Context manager ensures cleanup with Sandbox.create() as sandbox: # Execute a shell command result = sandbox.commands.run('echo "Hello from E2B!"') print(f'Output: {result.stdout}') print(f'Exit code: {result.exit_code}') # Run multiple commands install = sandbox.commands.run('apt-get update && apt-get install -y curl') check = sandbox.commands.run('curl --version') print(check.stdout) - Step 11
5. Code Interpreter SDK
The Code Interpreter SDK provides a higher-level API for executing Python code with automatic dependency management and streaming output.
// TypeScript - Code Interpreter import { Sandbox } from '@e2b/code-interpreter'; const sandbox = await Sandbox.create(); try { // Execute Python code const execution = await sandbox.runCode('x = 1\nx += 1\nx'); console.log('Result:', execution.text); // outputs: 2 // Execute code with output const analysis = await sandbox.runCode(` import pandas as pd import numpy as np # Create sample data data = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'score': [95, 87, 92] }) print(data.describe()) data.to_csv('results.csv') `); console.log('Logs:', execution.logs.stdout); // Download generated files const files = await sandbox.files.list('/'); console.log('Files:', files); } finally { await sandbox.close(); } - Step 12
Code Interpreter SDK (Python)
Python version of the Code Interpreter SDK:
# Python - Code Interpreter from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # Execute Python code execution = sandbox.run_code('x = 1; x += 1; x') print(f'Result: {execution.text}') # outputs: 2 # Execute code with libraries analysis = sandbox.run_code(""" import pandas as pd import numpy as np # Create sample data data = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'score': [95, 87, 92] }) print(data.describe()) data.to_csv('results.csv') """) print('Logs:', execution.logs.stdout) # List generated files files = sandbox.files.list('/') print('Files:', files) - Step 13
6. File Operations
Upload files to the sandbox, execute code that uses them, and download results.
// TypeScript - File operations import { Sandbox } from '@e2b/code-interpreter'; import fs from 'fs'; const sandbox = await Sandbox.create(); try { // Upload a file const dataContent = 'name,age\nAlice,30\nBob,25'; await sandbox.files.write('/home/user/data.csv', dataContent); // Process the file await sandbox.runCode(` import pandas as pd df = pd.read_csv('/home/user/data.csv') df['age_doubled'] = df['age'] * 2 df.to_csv('/home/user/output.csv', index=False) `); // Download the result const output = await sandbox.files.read('/home/user/output.csv'); console.log('Result:', output); // List all files in directory const files = await sandbox.files.list('/home/user'); console.log('Files:', files.map(f => f.name)); } finally { await sandbox.close(); } - Step 14
7. Integration with LLMs
E2B excels at executing code generated by LLMs. Here's a complete example with OpenAI:
// TypeScript - LLM Integration with OpenAI import OpenAI from 'openai'; import { Sandbox } from '@e2b/code-interpreter'; const openai = new OpenAI(); const sandbox = await Sandbox.create(); try { const prompt = 'Write Python code to calculate fibonacci numbers up to n=10'; // Generate code with OpenAI const response = await openai.chat.completions.create({ model: 'gpt-4', messages: [ { role: 'system', content: 'You are a helpful coding assistant. Generate only Python code without markdown formatting.' }, { role: 'user', content: prompt } ], temperature: 0.2 }); const code = response.choices[0].message.content; console.log('Generated code:', code); // Execute in E2B sandbox const execution = await sandbox.runCode(code); console.log('Output:', execution.logs.stdout); console.log('Errors:', execution.logs.stderr); if (execution.error) { console.error('Execution error:', execution.error); } } finally { await sandbox.close(); } - Step 15
8. LangChain Integration
Use E2B as a tool within LangChain for agentic workflows:
# Python - LangChain Integration from langchain.agents import initialize_agent, AgentType from langchain_openai import ChatOpenAI from langchain.tools import Tool from e2b_code_interpreter import Sandbox def execute_python_code(code: str) -> str: """Execute Python code in E2B sandbox.""" with Sandbox.create() as sandbox: execution = sandbox.run_code(code) if execution.error: return f"Error: {execution.error}" return execution.text or execution.logs.stdout # Create tool e2b_tool = Tool( name="Python Code Executor", func=execute_python_code, description="Executes Python code in a secure sandbox. Use for data analysis, calculations, and code generation." ) # Create agent llm = ChatOpenAI(model="gpt-4", temperature=0) agent = initialize_agent( tools=[e2b_tool], llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) # Run query result = agent.run( "Calculate the sum of squares of numbers from 1 to 100" ) print(result) - Step 16
9. Streaming Output
For long-running code execution, stream output in real-time:
// TypeScript - Streaming execution import { Sandbox } from '@e2b/code-interpreter'; const sandbox = await Sandbox.create(); try { const code = ` import time for i in range(10): print(f'Processing step {i+1}/10...') time.sleep(0.5) print('Done!') `; // Stream output as it's generated const execution = await sandbox.runCode(code, { onStdout: (output) => console.log('STDOUT:', output), onStderr: (output) => console.error('STDERR:', output), }); console.log('Final result:', execution.text); } finally { await sandbox.close(); } - Step 17
10. Custom Templates
Create custom sandbox templates with pre-installed dependencies for faster startup:
# Create a custom template via E2B CLI npm install -g @e2b/cli # Login e2b auth login # Create template from Dockerfile cat > Dockerfile.e2b <<EOF FROM ubuntu:22.04 RUN apt-get update && apt-get install -y \ python3 \ python3-pip \ nodejs \ npm \ curl \ git RUN pip3 install \ pandas \ numpy \ scikit-learn \ matplotlib \ seaborn EOF # Build and push template e2b template build -n my-data-science-template # Use in code: # const sandbox = await Sandbox.create({ template: 'my-data-science-template' }); - Step 18
Self-Hosting Overview
For enterprise deployments requiring full control, E2B can be self-hosted on your own infrastructure using Terraform. This provides complete data sovereignty and customization.
- Step 19
Self-Hosting: Prerequisites
Self-hosting requires significant infrastructure tooling and cloud resources:
Required Tools: - Terraform v1.5.x (last MPL version: v1.5.7) - Packer (disk image building) - Go (for building services) - Docker + Buildx plugin - NPM - Cloud CLI (gcloud or aws) Required Accounts: - Cloud provider (GCP or AWS) - Cloudflare (domain and DNS management) - PostgreSQL database (Supabase recommended) Optional (Recommended): - Grafana Stack (monitoring) - PostHog (analytics) - LaunchDarkly (feature flags) Minimum Resources (GCP example): - 2500GB Persistent Disk SSD quota - 24 vCPU quota - Multiple compute instances - Secret Manager, Certificate Manager APIs enabled Cost Estimate: - Variable based on usage - Default AWS setup: 3x t3.medium + t3.xlarge + m8i instances - Expect $500-2000/month for production workloads - Step 20
Self-Hosting: GCP Setup
Step-by-step guide for deploying E2B infrastructure on Google Cloud Platform:
# 1. Clone infrastructure repository git clone https://github.com/e2b-dev/infra.git cd infra # 2. Install dependencies brew install packer terraform@1.5 golang docker npm install -g npm # 3. Authenticate with GCP gcloud auth login gcloud auth application-default login # 4. Create configuration from template cp .env.template .env.gcp # 5. Edit .env.gcp with your values: # PROVIDER=gcp # GCP_PROJECT_ID=your-project-id # GCP_REGION=us-central1 # DOMAIN=your-domain.com # POSTGRES_CONNECTION_STRING=postgresql://... # CLOUDFLARE_API_TOKEN=your-token # 6. Initialize infrastructure make init # Note: May need to run twice due to race conditions # 7. Build and upload container images make build-and-upload # 8. Copy public builds (kernels, Firecracker binaries) make copy-public-builds # 9. Set secrets in GCP Secret Manager # Follow prompts to add: # - Cloudflare API token # - Database credentials # - Supabase JWT secrets # 10. Plan and apply Terraform (two phases) make plan make apply # 11. Prepare cluster (create users and base template) make prep-cluster # 12. Access Nomad UI # https://nomad.your-domain.com # Use API token from terraform output for authentication - Step 21
Self-Hosting: AWS Setup
AWS setup requires additional steps for AMI building and nested virtualization support:
# 1. Clone and setup (same as GCP) git clone https://github.com/e2b-dev/infra.git cd infra # 2. Configure AWS CLI aws configure --profile e2b # 3. Create configuration cp .env.template .env.aws # Edit .env.aws: # PROVIDER=aws # AWS_ACCOUNT_ID=123456789012 # AWS_PROFILE=e2b # AWS_REGION=us-east-1 # DOMAIN=your-domain.com # POSTGRES_CONNECTION_STRING=postgresql://... # CLOUDFLARE_API_TOKEN=your-token # 4. Build Packer AMI for cluster nodes cd packer packer build -var-file=../variables.pkrvars.hcl cluster-node.pkr.hcl cd .. # 5. Initialize and apply infrastructure make init make build-and-upload make copy-public-builds make plan make apply # 6. Prepare cluster make prep-cluster # Note: AWS instance types must support nested virtualization # Recommended: m8i.4xlarge (client), m8i.2xlarge (build) # May require service quota increase requests⚠ Heads up: AWS setup is in beta. Nested virtualization support is critical - verify instance type compatibility before deployment. - Step 22
Self-Hosting: Architecture
Understanding the self-hosted infrastructure components:
Infrastructure Layers: 1. Orchestration (Nomad) - Manages sandbox lifecycle - Schedules workloads across cluster - Auto-scaling based on demand 2. Compute Nodes (Auto Scaling Groups) - Control servers (3x for HA) - API servers (public-facing) - Client nodes (run sandboxes with Firecracker) - Build nodes (template building) 3. Storage - Object storage (GCS/S3) for templates - PostgreSQL for metadata and state - Shared filesystem (Filestore/EFS) for builds 4. Networking - Cloudflare DNS and CDN - TLS certificates via Certificate Manager - VPC isolation and security groups 5. Observability - Stackdriver/CloudWatch for logs and metrics - Optional: Grafana dashboards - ClickHouse for analytics (optional) 6. Security - Firecracker microVMs for isolation - Secret Manager for credentials - Network policies and firewalls - Regular security updates via custom AMIs - Step 23
Security Considerations
E2B provides multiple layers of security for safe code execution:
Isolation: - Each sandbox runs in a dedicated Firecracker microVM - Kernel-level isolation between sandboxes - No shared memory or processes between VMs - Automatic cleanup on sandbox termination Resource Limits: - CPU and memory limits per sandbox - Configurable timeout limits - Disk quota enforcement - Network rate limiting Network Security: - Sandboxes can be internet-isolated - Configurable egress filtering - TLS for all API communication - API key authentication Best Practices: - Never pass sensitive data to untrusted code - Use short-lived sandboxes (create, execute, destroy) - Implement rate limiting on your application layer - Monitor sandbox creation patterns for abuse - Regularly rotate API keys - Use custom templates to reduce attack surface - Enable logging and monitoring in production - Step 24
Monitoring and Debugging
Tools and techniques for monitoring E2B sandboxes:
// TypeScript - Monitoring and error handling import { Sandbox } from '@e2b/code-interpreter'; const sandbox = await Sandbox.create(); try { // Set timeout const execution = await sandbox.runCode( 'import time; time.sleep(100)', { timeout: 5000 } // 5 seconds ); } catch (error) { if (error.message.includes('timeout')) { console.error('Execution timed out'); } } // Get sandbox metadata console.log('Sandbox ID:', sandbox.sandboxId); console.log('Sandbox URL:', sandbox.getHost()); // Monitor resource usage (self-hosted only) const stats = await sandbox.commands.run('top -bn1 | head -20'); console.log('Resource usage:', stats.stdout); // Check sandbox health try { await sandbox.commands.run('echo "health check"'); console.log('Sandbox is healthy'); } catch (error) { console.error('Sandbox unhealthy, recreating...'); await sandbox.close(); // Create new sandbox } await sandbox.close(); - Step 25
Cost Optimization
Tips for reducing E2B costs in production:
Managed Service: - Use sandbox pooling (reuse sandboxes when safe) - Implement aggressive timeouts - Close sandboxes immediately after use - Cache results of deterministic operations - Monitor credit usage via dashboard - Set up billing alerts Self-Hosted: - Use spot/preemptible instances for build nodes - Scale down non-production environments - Implement auto-scaling based on demand - Use smaller instance types for low-traffic periods - Enable compute engine committed use discounts - Store templates in lifecycle-managed storage - Clean up old snapshots and images - Monitor and optimize network egress costs General: - Profile code execution times - Optimize AI-generated code before execution - Batch operations when possible - Use custom templates to reduce cold-start time - Implement request queuing to limit concurrency - Step 26
Common Issues and Troubleshooting
Solutions to frequent E2B problems:
Issue: "API key invalid" Solution: Verify E2B_API_KEY is set correctly, check for trailing spaces Issue: "Sandbox creation timeout" Solution: Check cloud provider quotas, verify network connectivity, try different region Issue: "Code execution timeout" Solution: Increase timeout parameter, optimize code, check for infinite loops Issue: "Module not found" errors Solution: Use custom template with pre-installed dependencies, or install in code: await sandbox.runCode('!pip install package-name') Issue: "Permission denied" on file operations Solution: Use /home/user/ directory instead of root, check file paths Issue: Self-hosted deployment fails Solution: Verify Terraform version (must be v1.5.x), check cloud quotas, run 'make init' twice for GCP, verify all secrets are set Issue: High latency on sandbox creation Solution: Use custom templates, implement sandbox pooling, choose closer region Issue: Out of memory errors Solution: Optimize code, process data in chunks, upgrade sandbox tier (managed), increase instance sizes (self-hosted) - Step 27
Production Best Practices
Guidelines for running E2B in production environments:
1. Error Handling - Always wrap sandbox operations in try/catch - Implement retry logic with exponential backoff - Log all errors with context (sandbox ID, code, user) - Monitor error rates and set up alerts 2. Resource Management - Set conservative timeouts (default: 30s) - Always close sandboxes in finally blocks - Implement sandbox pooling for high-traffic apps - Monitor concurrent sandbox limits 3. Security - Never execute code from untrusted sources without review - Sanitize outputs before displaying to users - Implement rate limiting per user/IP - Use custom templates to minimize attack surface - Regularly audit sandbox usage patterns 4. Performance - Cache sandbox results when deterministic - Use custom templates for faster cold starts - Batch operations when possible - Choose regions close to your users - Monitor P95/P99 latency metrics 5. Monitoring - Track sandbox creation/execution metrics - Set up alerts for unusual patterns - Monitor costs and usage trends - Log all code executions for debugging - Implement health checks and dashboards 6. Development Workflow - Test with managed service first - Use staging environment before production - Version custom templates - Document sandbox usage patterns - Keep SDKs updated to latest versions - Step 28
Example: Building a Code Assistant
Complete example of an AI code assistant using E2B, OpenAI, and Next.js:
// app/api/code-assistant/route.ts import { NextRequest, NextResponse } from 'next/server'; import OpenAI from 'openai'; import { Sandbox } from '@e2b/code-interpreter'; const openai = new OpenAI(); export async function POST(request: NextRequest) { const { prompt } = await request.json(); const sandbox = await Sandbox.create(); try { // Generate code with GPT-4 const completion = await openai.chat.completions.create({ model: 'gpt-4', messages: [ { role: 'system', content: 'You are a Python coding assistant. Generate clean, executable Python code.' }, { role: 'user', content: prompt } ], temperature: 0.3 }); const generatedCode = completion.choices[0].message.content; // Execute in E2B sandbox const execution = await sandbox.runCode(generatedCode, { timeout: 30000, // 30 seconds onStdout: (output) => console.log('Output:', output) }); return NextResponse.json({ success: true, code: generatedCode, output: execution.text || execution.logs.stdout, error: execution.error || execution.logs.stderr }); } catch (error) { console.error('Code assistant error:', error); return NextResponse.json( { success: false, error: error.message }, { status: 500 } ); } finally { await sandbox.close(); } } - Step 29
Resources and Community
Additional resources for E2B development:
Official Resources: - Documentation: https://e2b.dev/docs - GitHub Repository: https://github.com/e2b-dev/E2B - Cookbook (Examples): https://github.com/e2b-dev/e2b-cookbook - Infrastructure Repo: https://github.com/e2b-dev/infra - Dashboard: https://e2b.dev/dashboard Community: - Discord: Join via e2b.dev - Twitter: @e2b_dev - GitHub Discussions: Ask questions and share projects Example Projects: - AI Analyst: https://github.com/e2b-dev/ai-analyst - Fragments: Code snippets with E2B - Surf: Web automation examples Integration Guides: - LangChain: https://github.com/e2b-dev/e2b-cookbook/tree/main/guides/langchain - Vercel AI SDK: Check cookbook for examples - AutoGen: Multi-agent examples available - MCP Servers: Model Context Protocol integrations Support: - GitHub Issues for bug reports - Discord for community help - Email: support@e2b.dev for enterprise inquiries - Step 30
What's Next
After setting up E2B, explore these advanced topics:
1. Custom Templates - Create templates with pre-installed ML libraries - Build domain-specific environments - Version and manage template lifecycle 2. Advanced Integrations - Build multi-agent systems with AutoGen - Implement RAG with code execution - Create AI-powered data analysis tools - Build browser automation with Playwright 3. Production Deployment - Implement sandbox pooling and reuse - Set up monitoring and alerting - Configure auto-scaling for self-hosted - Optimize costs and performance 4. Enterprise Features - Deploy self-hosted infrastructure - Integrate with existing auth systems - Set up compliance and audit logging - Configure VPC peering and private networking 5. Community Projects - Explore the E2B cookbook for examples - Contribute to open-source integrations - Share your use cases with the community - Build plugins for popular AI frameworks
Feature requests
Sign in to suggest features or vote on existing ones.
No feature requests yet.
Discussion
Sign in to join the discussion.
No comments yet.