E2BTools 使 Agent 能够在一个安全的沙箱环境中执行代码,并支持 Python、文件操作和 Web 服务器功能。

前提条件

E2B 工具需要 e2b_code_interpreter Python 包和一个 E2B API 密钥。

pip install e2b_code_interpreter
export E2B_API_KEY=your_api_key

示例

以下示例演示了如何创建一个能够在安全沙箱中运行 Python 代码的 Agent:

cookbook/tools/e2b_tools.py
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.e2b import E2BTools

e2b_tools = E2BTools(
    timeout=600,  # 10 分钟超时(以秒为单位)
)

agent = Agent(
    name="代码执行沙箱",
    agent_id="e2b-sandbox",
    model=OpenAIChat(id="gpt-4o"),
    tools=[e2b_tools],
    markdown=True,
    show_tool_calls=True,
    instructions=[
        "你是使用安全 E2B 沙箱环境编写和验证 Python 代码的专家。",
        "你的主要目的是:",
        "1. 根据用户请求编写清晰、高效的 Python 代码",
        "2. 在 E2B 沙箱中执行和验证代码",
        "3. 与用户共享完整的代码,因为这是主要用例",
        "4. 详细解释代码的工作原理",
        "",
        "你可以使用这些工具:",
        "1. 运行 Python 代码 (run_python_code)",
        "2. 上传文件到沙箱 (upload_file)",
        "3. 从沙箱下载文件 (download_file_from_sandbox)",
        "4. 生成并添加可视化图表作为 ImageArtifact (download_png_result)",
        "5. 列出沙箱中的文件 (list_files)",
        "6. 读取和写入文件内容 (read_file_content, write_file_content)",
        "7. 启动 Web 服务器并获取公共 URL (run_server, get_public_url)",
        "8. 管理沙箱生命周期 (set_sandbox_timeout, get_sandbox_status, shutdown_sandbox)",
    ],
)

# 示例:生成斐波那契数列
agent.print_response(
    "编写 Python 代码生成前 10 个斐波那契数并计算它们的和与平均值"
)

Toolkit 参数

参数类型默认值描述
api_keystrNoneE2B API 密钥。如果未提供,则使用 E2B_API_KEY 环境变量。
run_codeboolTrue是否注册 run_code 函数
upload_fileboolTrue是否注册 upload_file 函数
download_resultboolTrue是否注册 download_result 函数
filesystemboolFalse是否注册文件系统操作
internet_accessboolFalse是否注册互联网访问函数
sandbox_managementboolFalse是否注册沙箱管理函数
timeoutint300沙箱的超时时间(秒)(默认:5 分钟)
sandbox_optionsdictNone要传递给 Sandbox 构造函数的附加选项
command_executionboolFalse是否注册命令执行函数

Toolkit 函数

代码执行

函数描述
run_python_code在 E2B 沙箱环境中运行 Python 代码

文件操作

函数描述
upload_file将文件上传到沙箱
download_png_result将 PNG 图片结果添加为 ImageArtifact 到 Agent
download_chart_data从结果中的交互式图表中提取图表数据
download_file_from_sandbox将文件从沙箱下载到本地系统

文件系统操作

函数描述
list_files列出沙箱中某个路径下的文件和目录
read_file_content从沙箱读取文件内容
write_file_content将文本内容写入沙箱中的文件
watch_directory监控指定目录在指定时长内的变化

命令执行

函数描述
run_command在沙箱环境中运行 shell 命令
stream_command运行 shell 命令并流式传输其输出
run_background_command在后台运行 shell 命令
kill_background_command终止后台命令

互联网访问

函数描述
get_public_url获取沙箱中正在运行的服务的公共 URL
run_server在沙箱中启动服务器并返回其公共 URL

沙箱管理

函数描述
set_sandbox_timeout更新沙箱的超时时间
get_sandbox_status获取沙箱的当前状态
shutdown_sandbox立即关闭沙箱
list_running_sandboxes列出所有正在运行的沙箱

开发者资源