E2B and Cloud Sandbox Services
E2B SDK, Daytona, and managed sandbox APIs for code interpreter agents.
E2B and Cloud Sandbox Services is a free AI Agents lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is E2B?
E2B (Environments to Build) is a cloud sandbox service designed specifically for AI code agents. It provides secure, isolated environments accessible via a simple Python/JS SDK without managing Docker or VMs yourself.
Each sandbox is a Firecracker microVM in E2B's cloud.
# Install the SDK
# pip install e2b-code-interpreter
from e2b_code_interpreter import Sandbox
sandbox = Sandbox() # creates a new cloud sandbox
print('Sandbox ID:', sandbox.sandbox_id)Running Code in a Sandbox
The Sandbox object provides a run_code() method that executes Python and returns structured output including stdout, stderr, and rich display objects (plots, dataframes).
from e2b_code_interpreter import Sandbox
with Sandbox() as sandbox:
result = sandbox.run_code('print(2 ** 10)')
print(result.logs.stdout) # ['1024']
print(result.error) # None if no errorHandling Errors and Exceptions
If the code raises an exception, result.error is populated with the traceback. The sandbox itself keeps running — you can send follow-up code to fix the error.
from e2b_code_interpreter import Sandbox
with Sandbox() as sandbox:
result = sandbox.run_code('1 / 0')
if result.error:
print('Error name:', result.error.name) # ZeroDivisionError
print('Traceback:', result.error.traceback)
else:
print(result.logs.stdout)Uploading Files to the Sandbox
Use sandbox.files.write() to upload data files (CSV, JSON, images) into the sandbox filesystem before running analysis code.
from e2b_code_interpreter import Sandbox
csv_content = 'name,score\nAlice,95\nBob,87\nCarol,92'
with Sandbox() as sandbox:
sandbox.files.write('/home/user/data.csv', csv_content.encode())
result = sandbox.run_code(
'import csv\n'
'rows = list(csv.DictReader(open("/home/user/data.csv")))\n'
'print([r["name"] for r in rows])'
)
print(result.logs.stdout) # ["['Alice', 'Bob', 'Carol']"]Downloading Files from the Sandbox
After computation, retrieve output files (reports, charts, processed data) with sandbox.files.read(). The file is returned as bytes.
from e2b_code_interpreter import Sandbox
import json
with Sandbox() as sandbox:
sandbox.run_code(
'import json\n'
'result = {"mean": 91.3, "max": 95}\n'
'json.dump(result, open("/home/user/output.json", "w"))'
)
data = sandbox.files.read('/home/user/output.json')
parsed = json.loads(data)
print(parsed) # {'mean': 91.3, 'max': 95}Installing Packages at Runtime
E2B sandboxes come with Python pre-installed. Install additional packages with run_code() by running a pip command, then use the package in subsequent calls within the same sandbox session.
from e2b_code_interpreter import Sandbox
with Sandbox() as sandbox:
# Install pandas inside the sandbox
sandbox.run_code('import subprocess; subprocess.run(["pip", "install", "pandas", "-q"])')
# Now use pandas
result = sandbox.run_code(
'import pandas as pd\n'
'df = pd.DataFrame({"x": [1,2,3], "y": [4,5,6]})\n'
'print(df.describe())'
)
print(result.logs.stdout)Persistent vs Ephemeral Sandboxes
E2B supports two sandbox lifecycle modes:
- Ephemeral: sandbox is destroyed when the
withblock exits. Use for one-shot code execution. - Persistent: sandbox stays alive across multiple requests. Use when state needs to accumulate across agent turns.
from e2b_code_interpreter import Sandbox
# Ephemeral (default context manager)
with Sandbox() as sb:
sb.run_code('x = 42')
# Sandbox destroyed here
# Persistent: keep alive for N seconds
sb = Sandbox(timeout=300) # keep alive 5 minutes
try:
sb.run_code('import numpy as np') # expensive import cached
sb.run_code('arr = np.arange(1000)')
result = sb.run_code('print(arr.mean())')
print(result.logs.stdout)
finally:
sb.kill() # explicit cleanupReconnecting to a Running Sandbox
If your agent process restarts or the sandbox_id is passed to another service, you can reconnect to an existing sandbox using its ID without losing state.
from e2b_code_interpreter import Sandbox
# First session
sb1 = Sandbox(timeout=300)
sb1.run_code('accumulated_data = []')
sandbox_id = sb1.sandbox_id
print('Created:', sandbox_id)
# Later — different process, same sandbox
sb2 = Sandbox.connect(sandbox_id)
result = sb2.run_code('accumulated_data.append(1); print(accumulated_data)')
print(result.logs.stdout) # '[1]' — state preserved
sb2.kill()E2B Pricing Model
E2B charges based on sandbox-seconds — the time a sandbox is alive, not just when code is running. Key pricing factors:
- Idle time still costs if sandbox is persistent
- Ephemeral sandboxes billed from creation to destruction
- Network egress may be billed separately
- Use
timeoutto set an auto-kill deadline
# Cost-optimization patterns:
# 1. Use short timeouts for one-shot executions
with Sandbox(timeout=60) as sb:
result = sb.run_code('print("done")')
# Auto-kills after 60s if not killed first
# 2. Kill immediately after use
sb = Sandbox()
try:
sb.run_code('process_data()')
finally:
sb.kill() # don't wait for timeout
# 3. Share one sandbox across multiple agent steps
# instead of creating a new one per stepUsing E2B in an Agent Loop
In a multi-turn agent, create the sandbox once and pass its ID through the loop. Each LLM-generated code snippet runs in the same session, so variables and installed packages persist across turns.
from e2b_code_interpreter import Sandbox
import openai
client = openai.OpenAI(api_key='YOUR_OPENAI_KEY')
def run_agent(user_question: str):
with Sandbox(timeout=120) as sb:
messages = [{'role': 'user', 'content': user_question}]
for _ in range(5): # max 5 turns
resp = client.chat.completions.create(
model='gpt-4o', messages=messages,
tools=[{'type': 'function', 'function': {
'name': 'run_python',
'description': 'Execute Python in a secure sandbox',
'parameters': {'type': 'object',
'properties': {'code': {'type': 'string'}},
'required': ['code']}
}}]
)
msg = resp.choices[0].message
if msg.tool_calls:
code = eval(msg.tool_calls[0].function.arguments)['code']
result = sb.run_code(code)
messages.append({'role': 'tool',
'tool_call_id': msg.tool_calls[0].id,
'content': str(result.logs.stdout)})
else:
return msg.contentAlternative Cloud Sandbox Services
E2B is not the only option. Other cloud sandbox services:
- Modal: serverless GPU/CPU sandboxes, custom Docker images
- AWS Lambda: execution isolation per invocation (Firecracker under the hood)
- Code Interpreter API: OpenAI's built-in sandbox for ChatGPT tools
- Daytona: development sandboxes with Git integration
What happens to variables when an ephemeral E2B sandbox exits its context manager?
Understanding the sandbox lifecycle is critical for deciding when to use ephemeral vs persistent sandboxes in multi-turn agent conversations.
E2B Cloud Sandboxes Recap
E2B provides a simple SDK for cloud-hosted Firecracker microVM sandboxes. Key patterns: ephemeral sandboxes for one-shot code, persistent sandboxes for multi-turn agents, file upload/download for data in and out, and reconnect by ID for cross-service workflows.
Always kill sandboxes explicitly to avoid unnecessary billing.
Frequently asked questions
Is the “E2B and Cloud Sandbox Services” lesson free?
Yes — the full text of “E2B and Cloud Sandbox Services” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “E2B and Cloud Sandbox Services”?
E2B SDK, Daytona, and managed sandbox APIs for code interpreter agents. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “E2B and Cloud Sandbox Services” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Docker-Based Agent Sandboxes
- VM Isolation for High-Security Code Agents
- E2B and Cloud Sandbox Services
- Security Policies for Code Execution