The E2B Toolkit provides comprehensive sandbox management, code execution, file operations, and server hosting capabilities.
SandboxManager
Manages E2B sandbox lifecycle operations.
class SandboxManager:
def __init__(
self,
api_key: Optional[str] = None,
default_timeout: int = 300,
default_options: Optional[Dict] = None
)
E2B API key (falls back to E2B_API_KEY environment variable)
Default sandbox timeout in seconds
Additional options for sandbox creation
create
Create a new sandbox.
def create(
self,
timeout: Optional[int] = None,
metadata: Optional[Dict[str, Any]] = None
) -> SandboxSlot
Sandbox timeout in seconds (uses default if not specified)
Custom metadata to attach to sandbox
Wrapper containing sandbox instance and metadata
connect
Connect to an existing sandbox.
def connect(self, sandbox_id: str) -> SandboxSlot
ID of existing sandbox to connect to
Connected sandbox wrapper
shutdown
Shutdown a sandbox and clean up resources.
def shutdown(self, sandbox_id: str) -> Dict[str, Any]
ID of sandbox to shutdown
Status dict with “status”, “sandbox_id”, and “result” keys
High-level toolkit for sandbox operations.
class E2BToolkit(Toolkit):
def __init__(
self,
sandbox_manager: SandboxManager,
auto_create_default: bool = True,
global_workers: int = 10,
**kwargs
)
Automatically create a default sandbox on initialization
Number of worker threads for concurrent operations
Code Execution
run_python_code
Execute Python code synchronously in a sandbox.
def run_python_code(
self,
code: str,
sandbox_id: Optional[str] = None,
timeout: Optional[int] = None
) -> Dict[str, Any]
Sandbox ID (uses default if not specified)
Execution timeout in seconds
Execution result with status, results, logs, or error information
Example
toolkit.run_python_code(
code="print('Hello, world!')\nresult = 2 + 2",
timeout=30
)
# Returns: {"status": "success", "results": [{"logs": "Hello, world!\n"}]}
run_python_code_background
Execute Python code as a background job.
def run_python_code_background(
self,
code: str,
sandbox_id: Optional[str] = None,
job_id: Optional[str] = None
) -> Dict[str, Any]
Sandbox ID (uses default if not specified)
Custom job ID (auto-generated if not provided)
Dict with “status”: “accepted” and “job_id”
run_in_all_sandboxes
Run code in all managed sandboxes concurrently.
def run_in_all_sandboxes(
self,
code: str,
timeout_each: Optional[int] = None
) -> Dict[str, Any]
Dict mapping sandbox_id to result for each sandbox
Command Execution
run_command
Run a shell command in a sandbox.
def run_command(
self,
command: str,
sandbox_id: Optional[str] = None,
background: bool = False
) -> Dict[str, Any]
Sandbox ID (uses default if not specified)
Run as background job if True
Command output dict or job_id if background=True
Example
# Synchronous execution
toolkit.run_command("pip install requests")
# Background execution
result = toolkit.run_command("python server.py", background=True)
job_id = result["job_id"]
run_command_background
Run a shell command as a background job with process tracking.
def run_command_background(
self,
command: str,
sandbox_id: Optional[str] = None,
job_id: Optional[str] = None
) -> Dict[str, Any]
File Operations
upload_file
Upload a file from local filesystem to sandbox.
def upload_file(
self,
local_path: str,
sandbox_id: Optional[str] = None,
sandbox_path: Optional[str] = None
) -> Dict[str, Any]
Destination path in sandbox (defaults to filename)
download_file_from_sandbox
Download a file from sandbox to local filesystem.
def download_file_from_sandbox(
self,
sandbox_path: str,
sandbox_id: Optional[str] = None,
local_path: Optional[str] = None
) -> Dict[str, Any]
Destination local path (defaults to filename)
download_png_result
Download PNG image from code execution result.
def download_png_result(
self,
agent: Union[Agent, Team],
result_index: int = 0,
sandbox_id: Optional[str] = None,
output_path: Optional[str] = None
) -> Dict[str, Any]
download_chart_data
Download chart data from execution result.
def download_chart_data(
self,
agent: Agent,
result_index: int = 0,
sandbox_id: Optional[str] = None,
output_path: Optional[str] = None,
add_as_artifact: bool = True
) -> Dict[str, Any]
Server & Internet Access
get_public_url
Get public URL for a service running in the sandbox.
def get_public_url(
self,
port: int,
sandbox_id: Optional[str] = None
) -> Dict[str, Any]
Port number the service is listening on
Dict with “status”: “success” and “url” key containing public URL
run_server
Start a server in the sandbox and return its public URL.
def run_server(
self,
command: str,
port: int,
sandbox_id: Optional[str] = None,
wait_seconds: int = 2
) -> Dict[str, Any]
Command to start the server (e.g., “python -m http.server 8000”)
Port the server will listen on
Seconds to wait for server to start
Example
result = toolkit.run_server(
command="python -m http.server 8000",
port=8000
)
print(f"Server available at: {result['url']}")
Job Management
get_job_status
Check the status of a background job.
def get_job_status(self, job_id: str) -> Dict[str, Any]
Status dict with “status” key (“running”, “done”, “error”, “cancelled”, “not_found”)
kill_job
Cancel a running background job.
def kill_job(self, job_id: str) -> Dict[str, Any]
Sandbox Management
create_sandbox
def create_sandbox(
self,
timeout: Optional[int] = None,
metadata: Optional[Dict[str, Any]] = None,
set_as_default: bool = False
) -> Dict[str, Any]
list_managed_sandboxes
def list_managed_sandboxes(self) -> Dict[str, Any]
shutdown_sandbox
def shutdown_sandbox(self, sandbox_id: Optional[str] = None) -> Dict[str, Any]
shutdown_all_sandboxes
def shutdown_all_sandboxes(self) -> Dict[str, Any]
Example Usage
from tools.e2b_tools import SandboxManager, E2BToolkit
# Initialize
manager = SandboxManager(api_key="your_api_key", default_timeout=360)
toolkit = E2BToolkit(manager, auto_create_default=True)
# Execute Python code
result = toolkit.run_python_code(
code="""
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('chart.png')
"""
)
# Run a web server
server = toolkit.run_server(
command="python -m http.server 8000",
port=8000
)
print(f"Server URL: {server['url']}")
# Background job
job = toolkit.run_command_background("pip install pandas")
status = toolkit.get_job_status(job["job_id"])