Skip to content

从 examples 看 SDK 实战用法

CubeSandbox 提供了多个官方示例,覆盖从基础用法到 AI Agent 集成的典型场景。这篇文章拆解每个示例的核心代码和调用链路。


1. 示例全景


2. code-sandbox-quickstart:基础四步走

examples/code-sandbox-quickstart/ 展示了 SDK 的最基本用法。

2.1 完整流程

2.2 核心代码

python
# exec_code.py
from e2b_code_interpreter import Sandbox

template_id = os.environ["CUBE_TEMPLATE_ID"]

python_code = """
print("hello cube")
"""

with Sandbox.create(template=template_id) as sandbox:
    print(sandbox.run_code(python_code, on_stdout=lambda data: print(data)))

2.3 各示例文件

文件功能关键 API
create.py创建沙箱Sandbox.create()
exec_code.py执行代码sandbox.run_code()
read.py读取文件sandbox.files.read()
pause.py暂停沙箱sandbox.pause()
cmd.py执行命令sandbox.commands.run()
network_allowlist.py网络白名单metadata={"network-policy": ...}
network_denylist.py网络黑名单metadata={"network-policy": ...}
network_no_internet.py禁止外网metadata={"network-policy": ...}

3. openai-agents-code-interpreter:AI Agent 集成

examples/openai-agents-code-interpreter/ 展示了如何将 CubeSandbox 作为 OpenAI Agents 的代码执行后端。

3.1 架构

3.2 核心设计

PythonRunner Tool

python
# 将 LLM 生成的代码写入文件并执行
class PythonRunner:
    async def run(self, code: str):
        # 1. 写入 script.py
        await sandbox.files.write("/home/user/script.py", code)
        # 2. 执行
        result = await sandbox.commands.run("python -I -B script.py")
        # 3. 返回输出 + 新生成的文件列表
        return {"output": result.stdout, "files": new_files}

WorkspaceShell Tool

python
# 执行 shell 命令(ls、cat 等)
class WorkspaceShell:
    async def run(self, command: str):
        result = await sandbox.commands.run(command)
        return result.stdout

3.3 关键技巧

Root 用户适配:CubeSandbox 的 envd 默认使用 root 用户,但 E2B SDK 默认使用 user。示例通过 monkey-patch 强制使用 root:

python
# 强制所有文件操作使用 root 用户
_e2b_rpc.default_username = "root"

for _name in ("read", "write", "list", ...):
    _orig = getattr(_AsyncFS, _name)
    def _wrapper(self, *a, **kw):
        kw.setdefault("user", "root")
        return _orig(self, *a, **kw)
    setattr(_AsyncFS, _name, _wrapper)

实时输出流:通过 on_stdout 回调将沙箱输出实时打印到本地终端:

python
def _make_stream_handler(label, stream):
    def _handler(data):
        for line in str(data).splitlines():
            print(f"[{label}] {line}")
    return _handler

4. network-policy:网络策略配置

examples/network-policy/ 展示了如何通过 metadata 配置沙箱的网络访问策略。

4.1 三种策略

4.2 配置方式

python
# 白名单模式
sandbox = Sandbox.create(
    template=template_id,
    metadata={
        "network-policy": json.dumps({
            "allowOut": ["api.openai.com", "pypi.org"]
        })
    }
)

# 黑名单模式
sandbox = Sandbox.create(
    template=template_id,
    metadata={
        "network-policy": json.dumps({
            "denyOut": ["malicious-site.com"]
        })
    }
)

# 禁止外网
sandbox = Sandbox.create(
    template=template_id,
    allow_internet_access=False
)

5. browser-sandbox:浏览器沙箱

examples/browser-sandbox/ 展示了在沙箱中运行 headless browser。

场景

  • Web 自动化测试
  • 网页截图
  • 数据抓取

关键点

  • 模板中预装 Chromium
  • 通过端口映射暴露 CDP (Chrome DevTools Protocol)
  • 使用 Playwright/Puppeteer 连接

6. 各示例的调用链路对比

示例创建方式主要操作销毁方式
quickstartSandbox.create()run_code / files.readwith 自动 kill
agents-interpreterSandbox.create()commands.run / files.write手动 kill
network-policySandbox.create(metadata=...)commands.runwith 自动 kill
browser-sandboxSandbox.create()端口映射 + Playwright手动 kill

7. 快速开始模板

Python 最小示例

python
from cubesandbox import Sandbox

with Sandbox.create(template="my-template") as sb:
    result = sb.run_code("print('Hello CubeSandbox!')")
    print(result.text)  # "Hello CubeSandbox!"

Go 最小示例

go
client := cubesandbox.NewClient(cubesandbox.Config{...})
sandbox, _ := client.Create(ctx, cubesandbox.CreateOptions{TemplateID: "my-template"})
defer sandbox.Kill(ctx)

result, _ := sandbox.Commands.Run(ctx, "echo hello", cubesandbox.CommandOptions{})
fmt.Println(result.Stdout) // "hello\n"

延伸阅读