简介
E2B Code Interpreter SDK 给 AI agent 一个托管的类 Jupyter 环境,能跑 Python、上传文件、渲染图表、跨 cell 保留状态。~150ms 冷启动,底下是完整 Linux。适合在自己产品里搭 ChatGPT 风格的 code interpreter、数据分析 agent、需要跑自己代码的自主编码 agent。Python SDK 和 JS SDK 都有。装机时间 2 分钟。
从 agent 跑代码
from e2b_code_interpreter import Sandbox
with Sandbox.create() as sandbox:
# 上传 CSV
sandbox.files.write("/data/sales.csv", open("sales.csv", "rb").read())
# 执行代码
execution = sandbox.run_code('''
import pandas as pd
df = pd.read_csv('/data/sales.csv')
df.groupby('region')['amount'].sum().plot(kind='bar')
''')
# 拿文本输出
print(execution.text)
# 拿图(自动抽取为 PNG)
for chart in execution.results:
if chart.png:
with open(f"chart-{chart.id}.png", "wb") as f:
f.write(chart.png)跨调用持久状态
sandbox = Sandbox.create()
# 第一次调用定义函数
sandbox.run_code('''
def analyze_sales(region):
return df[df.region == region]['amount'].sum()
''')
# 第二次调用使用函数 —— 状态保留
result = sandbox.run_code("analyze_sales('US')")
print(result.text) # 函数返回的内容接到 Claude / GPT 的工具使用
from anthropic import Anthropic
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create()
tools = [{
"name": "run_python",
"description": "Run Python code in a sandbox. Persistent state across calls.",
"input_schema": {
"type": "object",
"properties": {"code": {"type": "string"}},
"required": ["code"]
}
}]
response = anthropic.messages.create(
model="claude-3-5-sonnet-20241022",
tools=tools,
messages=[{"role": "user", "content": "Plot the FAANG stock prices over 2024"}],
)
# Claude 调 run_python 时,在 sandbox 里执行并返回输出FAQ
Q: E2B 免费吗? A: 免费 —— 大方的免费档(每月约 100 小时 sandbox 时间)。付费档加更长会话、更高并发、持久磁盘。E2B 的开源 firecracker 运行时也能自托管。
Q: 跟在 Modal Sandbox 里跑代码啥区别? A: E2B 优化 交互式 代码执行(Jupyter cell、持久 kernel 状态、图自动抽取)。Modal Sandbox 是通用 Linux。要 ChatGPT 风格 code interpreter 体验,E2B 更直接。
Q: 跑不可信代码安全吗? A: 安全 —— E2B 用 Firecracker microVM(跟 AWS Lambda 一样的技术)做隔离。每个 sandbox 有独立 kernel / 文件系统 / 网络命名空间。E2B 就是为防 sandbox 之间或 sandbox 到 host 提权设计的。