E2B SDK
E2B is an open-source infrastructure that provides isolated cloud sandboxes for AI agents to safely execute code, process data, and run tools. The Python SDK, currently at version 2.20.0, enables starting and managing these environments. Releases are frequent, often weekly or bi-weekly, addressing minor changes, patch fixes, and new features.
Warnings
- breaking The method for creating a Sandbox instance changed in v2. Instead of direct instantiation `Sandbox()`, you must now use the class method `Sandbox.create()`.
- breaking File operation APIs were updated in v2 for consistency. Single file writes now use `sandbox.files.write()`, and multiple file writes use `sandbox.files.write_files()`.
- gotcha An E2B API Key is required for most operations and must be provided, typically via the `E2B_API_KEY` environment variable or explicitly passed during sandbox creation. Failing to provide it will result in errors or limited functionality.
- gotcha There are two distinct Python packages for E2B: `e2b` (for general sandbox management and commands) and `e2b-code-interpreter` (specifically for `run_code()` functionality). Both can export a `Sandbox` class, leading to potential import confusion if not installed and used correctly.
- gotcha In v2, sandboxes are secure by default. If you are using custom templates created before `envd v0.2.0`, you might need to rebuild them to enable secure communication, or you may encounter errors.
Install
-
pip install e2b -
pip install e2b-code-interpreter
Imports
- Sandbox
from e2b import Sandbox
- Sandbox
from e2b_code_interpreter import Sandbox
Quickstart
import os
from e2b import Sandbox
# Ensure E2B_API_KEY is set in your environment
# You can get your API key from the E2B dashboard: https://e2b.dev/docs/quickstart/running-your-first-sandbox
api_key = os.environ.get('E2B_API_KEY', '')
if not api_key:
print("Warning: E2B_API_KEY environment variable not set. Sandbox creation may fail or default to a limited scope.")
with Sandbox.create(api_key=api_key) as sandbox:
print(f"Sandbox created with ID: {sandbox.sandbox_id}")
result = sandbox.commands.run('echo "Hello from E2B!"')
print(f"Stdout: {result.stdout}")
if result.stderr:
print(f"Stderr: {result.stderr}")
print("Sandbox session ended.")