跳到主要内容

智能体框架与 SDK

Pydantic AI

在 E2B 沙箱中运行 Pydantic AI 的 Shell 和 FileSystem 能力。原生的 E2BSandbox 工作区会在多次运行、暂停和 worker 重启之间保留文件。

维护方
Pydantic
集成方式
内置于 pydantic-ai-harness
软件包
pydantic-ai-harness[e2b]
语言
Python

配置

快速开始

将提示词粘贴到您的编程智能体中,或按以下步骤自行配置。

粘贴到您的编程智能体中

为这个 Pydantic AI 项目添加 E2B 沙箱。

  1. 1.使用项目的包管理器安装带 e2b 扩展的 pydantic-ai-harness("pydantic-ai-harness[e2b]")。需要 Python 3.11 或更高版本。
  2. 2.沙箱需要 E2B_API_KEY 环境变量。如果尚未设置,请向我索要 API 密钥(在 https://console.e2b.dev/?tab=keys 获取)。切勿将其硬编码。
  3. 3.按照 https://docs.e2b.dev/agents/pydantic-ai 上的 Pydantic AI 指南操作。创建一个 E2BSandboxBackend,为我的智能体添加 E2BSandbox、Shell 和 FileSystem 能力,将 backend 作为 workspace= 传入,并在 finally 块中销毁沙箱。
  4. 4.运行一次智能体,并展示来自沙箱的输出。

或自行配置

  1. 1. 安装 E2B 集成

    pip install "pydantic-ai-harness[e2b]>=0.54.0" "pydantic-ai-slim[openai]>=2.54.0"
  2. 2. 设置 API 密钥

    export E2B_API_KEY="your_e2b_api_key"
    export OPENAI_API_KEY="your_openai_api_key"
  3. 3. 为智能体提供 E2B 工作区

    from pydantic_ai import Agent
    from pydantic_ai_harness.e2b_sandbox import E2BSandbox, E2BSandboxBackend
    from pydantic_ai_harness.filesystem import FileSystem
    from pydantic_ai_harness.shell import Shell
    
    backend = E2BSandboxBackend(
        working_dir="/home/user/log-cli",
        sandbox_timeout=300,
        allow_internet_access=False,
    )
    
    agent = Agent(
        "openai:gpt-4.1-mini",
        capabilities=[
            E2BSandbox(),
            Shell(tools=["run_command"], default_timeout=20),
            FileSystem(tools=["read_file", "write_file", "edit_file"], content_hashes=False),
        ],
    )
  4. 4. 运行并清理

    import asyncio
    
    
    async def main():
        try:
            result = await agent.run(
                "Write log_stats.py that counts HTTP 500–599 responses in a log file, "
                "create a small sample log, and run the script on it.",
                workspace=backend,
            )
            print(result.output)
        finally:
            if backend.ref is not None:
                await E2BSandbox().destroy(backend.ref)
    
    
    asyncio.run(main())

安全

沙箱中运行的内容

命令和文件编辑在隔离的沙箱中运行;智能体循环和模型调用留在您的机器上。

  • 代码来自 Shell、FileSystem 和 Coder 能力的 Shell 命令与文件编辑。
  • 状态保存 result.workspace.ref,再将其作为 workspace= 传回即可重新连接。已暂停的沙箱恢复后文件仍在。
  • 生命周期沙箱默认生命周期为 3,600 秒,超时后暂停。Pydantic AI 从不删除沙箱;请调用 destroy(ref)。
  • 密钥API 密钥保留在运行智能体的进程中。沙箱不会继承您的环境变量。

已启动 30亿+ 个沙箱

为每个智能体 配一台机器