E2B 与云沙箱服务
面向代码解释器智能体的 E2B SDK、Daytona 和托管沙箱 API
E2B 与云沙箱服务 是 CoddyKit 上的免费 AI Agents 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
E2B 是什么?
E2B(构建环境)是一项专为 AI 代码代理设计的云沙盒服务。它通过简单的 Python/JS SDK 提供安全、隔离的环境,无需您自行管理 Docker 或 VM。
每个沙盒都是 E2B 云中的一个 Firecracker microVM。
# 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)在沙盒中运行代码
Sandbox 对象提供了一个 run_code() 方法,用于执行 Python,并返回包含标准输出、标准错误和丰富显示对象(图表、数据框)的结构化输出。
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 error处理错误和异常
如果代码引发异常,result.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)将文件上传到沙盒
使用 sandbox.files.write(),在运行分析代码之前将数据文件(CSV、JSON、图像)上传到沙盒文件系统。
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']"]从沙盒下载文件
计算完成后,使用 sandbox.files.read() 获取输出文件(报告、图表、处理后的数据)。该文件会以字节形式返回。
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}在运行时安装软件包
E2B 沙盒预装了 Python。通过 run_code() 运行 pip 命令来安装其他软件包,然后就可以在同一沙盒会话的后续调用中使用这些软件包。
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)持久沙盒与临时沙盒
E2B 支持两种沙盒生命周期模式:
- 临时:
with代码块退出时沙盒会被销毁。适合一次性代码执行。 - 持久:沙盒会在多个请求之间保持运行。适合需要在多轮代理交互中累积状态的场景。
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 cleanup重新连接正在运行的沙盒
如果代理进程重启,或沙盒 ID 被传递给其他服务,您可以使用该 ID 重新连接到现有沙盒,而不会丢失状态。
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 定价模式
E2B 根据沙盒秒数收费——计算沙盒处于运行状态的时间,而不仅仅是代码运行的时间。影响价格的主要因素包括:
- 如果沙盒是持久的,空闲时间仍会产生费用
- 临时沙盒从创建到销毁期间计费
- 网络出口流量可能单独计费
- 使用
timeout设置自动终止的截止时间
# 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 step在代理循环中使用 E2B
在多轮代理中,创建一次沙盒,并在循环中传递其 ID。每个由 LLM 生成的代码片段都会在同一会话中运行,因此变量和已安装的软件包会在各轮之间保留。
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.content其他云沙盒服务
E2B 不是唯一的选择。其他云沙盒服务包括:
- Modal:无服务器 GPU/CPU 沙盒、自定义 Docker 镜像
- AWS Lambda:每次调用都提供执行隔离(底层使用 Firecracker)
- Code Interpreter API:OpenAI 为 ChatGPT 工具内置的沙盒
- Daytona:支持 Git 集成的开发沙盒
临时 E2B 沙盒退出其上下文管理器后,变量会发生什么?
理解沙盒生命周期,对于在多轮代理对话中决定何时使用临时沙盒或持久沙盒至关重要。
E2B 云沙盒回顾
E2B 为云端托管的 Firecracker microVM 沙盒提供了简单的 SDK。主要模式包括:用于一次性代码执行的临时沙盒、用于多轮代理的持久沙盒、用于输入和输出数据的文件上传/下载,以及用于跨服务工作流的按 ID 重新连接。
始终显式调用 kill 来终止沙盒,以避免不必要的计费。
常见问题解答
「E2B 与云沙箱服务」课时是免费的吗?
是的 — 「E2B 与云沙箱服务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「E2B 与云沙箱服务」这节课中我会学到什么?
面向代码解释器智能体的 E2B SDK、Daytona 和托管沙箱 API 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「E2B 与云沙箱服务」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。