Haystack E2B 集成详解为 Agent 赋予安全云沙箱执行 bash 与文件操作能力【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystackHaystack 的 E2B 集成e2b-haystack通过E2BSandbox、E2BToolset及四个现成工具让 LLM Agent 在隔离的云端 Linux 沙箱中安全执行 bash 命令、读写文件、管理目录并支持完整的序列化往返。读完本文你将掌握如何安装配置、用 Agent 驱动沙箱、按需组合单个工具以及如何将沙箱工具接入 Pipeline 的 YAML 持久化流程。集成概览沙箱、工具与 Toolset 三层结构E2B 集成位于独立的 haystack-core-integrations。该集成由三个层次组成层次类职责沙箱管理E2BSandbox管理 E2B 云沙箱的生命周期建立连接、关闭、序列化单个工具RunBashCommandTool、ReadFileTool、WriteFileTool、ListDirectoryTool各自封装一项沙箱操作均继承自haystack.tools.Tool工具集合E2BToolset继承自haystack.tools.Toolset打包全部四个工具并统一管理沙箱生命周期核心设计理念是共享同一个E2BSandbox实例无论通过E2BToolset统一使用还是手动把同一个沙箱实例传给多个工具所有工具都在同一个实时沙箱进程中运行。这意味着WriteFileTool写入的文件在同一轮 Agent 运行中立刻可以被RunBashCommandTool执行、被ReadFileTool读回——写、跑、读形成一个连贯的闭环。在 Haystack 侧Tool是一个数据类定义name、description、JSON Schema 格式的parameters以及function/async_function见 haystack/tools/tool.pyAgent 会把工具的name、description、parameters组成的tool_spec交给 LLM由其决定何时以何种参数调用工具。Toolset则把多个相关工具组织为一个整体实现集合接口__iter__、__contains__、__len__、__getitem__可直接传给 Agent见 haystack/tools/toolset.py。安装与密钥配置安装集成包并设置 API 密钥pip install e2b-haystackexport E2B_API_KEYyour-e2b-api-keyapi_key是唯一必填参数默认通过Secret.from_env_var(E2B_API_KEY, strictTrue)从环境变量读取strict 模式意味着环境变量缺失会直接报错。密钥需要在 E2B 官网e2b.dev申请。按 docs-website/docs/tools/ready-made-tools/e2btoolset.mdx 的说明其余参数全部可选sandbox_template默认basetimeout默认120秒沙箱空闲超时environment_vars用于向沙箱进程注入环境变量。E2BSandbox共享沙箱的生命周期管理E2BSandbox负责与 E2B 云端的连接与资源释放。其实例化签名如下E2BSandbox( api_key: Secret Secret.from_env_var(E2B_API_KEY, strictTrue), sandbox_template: str base, timeout: int 120, environment_vars: dict[str, str] | None None, instance_id: str | None None, )各参数含义api_keyE2B API 密钥类型为Secret默认从E2B_API_KEY环境变量读取。sandbox_templateE2B 沙箱模板名默认base。不同模板预装了不同的运行环境可按任务需要切换。timeout沙箱空闲超时秒默认120。沙箱空闲超过该时间后云端资源会被回收避免闲置计费。environment_vars可选注入到沙箱进程的环境变量字典例如把 API Token、配置项传给沙箱内的命令。instance_id客户端侧稳定标识符在to_dict/from_dict序列化往返中被保留。省略时自动生成一个新的 UUID。共享同一E2BSandbox的工具都继承这个 id这正是它们序列化后仍能重新共享同一实例的机制。注意它与 E2B 云端在warm_up()时分配的云端沙箱 id 是两个不同的概念。warm_up 与 close手动管理生命周期生命周期方法定义如下API 参考见 docs-website/reference/integrations-api/e2b.mdwarm_up()建立与 E2B 沙箱的连接。该方法是幂等的——沙箱已在运行时重复调用不会产生副作用。如果沙箱创建失败会抛出RuntimeError。文档明确要求warm_up应可被多次调用因为它在 Pipeline/Agent 初始化期间可能被反复触发这与 haystack/tools/tool.py 中对Tool.warm_up()的约定一致。close()关闭沙箱并释放所有关联资源。用完务必调用避免留下空闲沙箱持续占用云端资源。在 Agent 或 Pipeline 中使用时生命周期由框架自动处理独立使用工具时则需手动管理sandbox E2BSandbox() sandbox.warm_up() # ... 使用工具 ... sandbox.close()序列化与共享实例还原to_dict()将沙箱配置序列化为字典from_dict()从字典还原。反序列化时有一个值得注意的进程级缓存机制多个在序列化前共享同一个E2BSandbox的工具反序列化后仍会共享同一个还原实例——每个工具的from_dict会查询以instance_id为键的进程级缓存。更重要的是安全设计只有完整序列化配置api_key、template、timeout、environment_vars与缓存条目完全匹配时缓存命中才生效。一份精心构造的 YAML 即使猜中了 id只要配置不同就会落入全新实例而永远观察不到缓存的那个。这个设计防止了反序列化时通过伪造 id 窃取其他实例状态的攻击面值得在自定义沙箱类时借鉴。四大沙箱工具详解四个工具都继承自haystack.tools.Tool构造函数统一接收一个E2BSandbox实例并各自实现to_dict/from_dict完成序列化。它们注册在haystack_integrations.tools.e2b模块下按模块划分见下表模块类工具名功能bash_toolRunBashCommandToolrun_bash_command执行 bash 命令返回合并的exit_code、stdout、stderrread_file_toolReadFileToolread_file读取沙箱文件系统中的文本文件write_file_toolWriteFileToolwrite_file写入文本文件自动创建父目录覆盖已有文件list_directory_toolListDirectoryToollist_directory列出指定路径下的文件与子目录每个工具的独立使用示例模式一致from haystack_integrations.tools.e2b import E2BSandbox, ReadFileTool sandbox E2BSandbox() agent Agent(chat_generator..., tools[ReadFileTool(sandboxsandbox)])把同一个sandbox实例传给多个工具它们即在同一沙箱中协同工作from haystack_integrations.tools.e2b import E2BSandbox, RunBashCommandTool, ReadFileTool sandbox E2BSandbox() agent Agent( chat_generator..., tools[ RunBashCommandTool(sandboxsandbox), ReadFileTool(sandboxsandbox), ], )RunBashCommandTool是整个集成中最核心的工具它让 Agent 拥有执行 shell 脚本、安装依赖如pip install、编译代码或执行任何系统级操作的能力并把exit_code、stdout、stderr合并返回给 LLM使模型能够根据执行结果决定下一步动作。文件三件套读、写、列目录则赋予 Agent 在沙箱内创建、检查、组织代码文件的能力。E2BToolset一行代码接入全部沙箱能力E2BToolset继承自haystack.tools.Toolset把四个沙箱工具打包成一个整体。它的优势在于Toolset 拥有沙箱生命周期——调用warm_up()启动沙箱序列化往返保留共享沙箱关系你无需手动管理E2BSandbox实例。E2BToolset( api_key: Secret Secret.from_env_var(E2B_API_KEY, strictTrue), sandbox_template: str base, timeout: int 120, environment_vars: dict[str, str] | None None, )参数语义与E2BSandbox完全一致。使用示例from haystack.components.generators.chat import OpenAIChatGenerator from haystack.components.agents import Agent from haystack_integrations.tools.e2b import E2BToolset agent Agent( chat_generatorOpenAIChatGenerator(modelgpt-4o), toolsE2BToolset(), )由于Toolset实现了集合接口见 haystack/tools/toolset.pyAgent 在每步迭代中会展开工具集并向 LLM 暴露tool_specwarm_up()被调用时会遍历并预热其中的工具to_dict()则按{type: ..., data: {tools: [...]}}结构序列化。这正是 E2BToolset 能无缝融入 Agent 与 Pipeline 序列化链路的原因。实战用 Agent 驱动沙箱完成写-跑-读任务下面是一个完整的可运行示例展示 Agent 如何借助E2BToolset完成写 Python 脚本 → 执行 → 读回文件的完整闭环源自 docs-website/docs/tools/ready-made-tools/e2btoolset.mdx 的示例from haystack.components.agents import Agent from haystack.components.generators.chat import OpenAIChatGenerator from haystack.dataclasses import ChatMessage from haystack_integrations.tools.e2b import E2BToolset agent Agent( chat_generatorOpenAIChatGenerator(modelgpt-4o-mini), toolsE2BToolset(), system_prompt( You are a helpful coding assistant with access to a live Linux sandbox. Use the available tools freely to explore, write files, and run commands. All tools operate inside the same sandbox environment, so files written with write_file are immediately available to run_bash_command and read_file. ), max_agent_steps15, ) response agent.run( messages[ ChatMessage.from_user( Write a Python script to /tmp/primes.py that prints all prime numbers up to 50, run it, and then read the file back so I can see both the script and its output., ), ], ) print(response[last_message].text)这段代码的运行链路如下Agent 的warm_up()调用warm_up_tools()进而触发E2BToolset.warm_up()启动云端沙箱见 haystack/components/agents/agent.py 与 haystack/tools/utils.pyLLM 依据工具描述依次调用write_file→run_bash_command→read_file因为共享沙箱/tmp/primes.py写入后立即可执行、可读回max_agent_steps15限制了 Agent 的最大迭代步数防止无限循环Agent 在满足退出条件后返回last_message其中包含最终的自然语言回答。按需组合单个工具如果只需要部分能力可以手动实例化工具并共享一个沙箱同时自定义超时等参数from haystack.components.agents import Agent from haystack.components.generators.chat import OpenAIChatGenerator from haystack_integrations.tools.e2b import ( E2BSandbox, ListDirectoryTool, ReadFileTool, RunBashCommandTool, WriteFileTool, ) sandbox E2BSandbox(sandbox_templatebase, timeout300) agent Agent( chat_generatorOpenAIChatGenerator(modelgpt-4o-mini), tools[ RunBashCommandTool(sandboxsandbox), ReadFileTool(sandboxsandbox), WriteFileTool(sandboxsandbox), ListDirectoryTool(sandboxsandbox), ], )将 E2B Agent 接入 Pipeline 与 YAML 持久化E2BToolset完全可序列化因此可以把使用它的 Agent 包装进Pipeline并保存为 YAML。序列化往返后四个工具依然共享同一个E2BSandbox实例——这正是instance_id缓存机制的设计目标。from haystack.components.agents import Agent from haystack.components.generators.chat import OpenAIChatGenerator from haystack.core.pipeline import Pipeline from haystack.dataclasses import ChatMessage from haystack_integrations.tools.e2b import E2BToolset agent Agent( chat_generatorOpenAIChatGenerator(modelgpt-4o-mini), toolsE2BToolset(sandbox_templatebase, timeout120), system_promptYou are a helpful coding assistant with access to a live Linux sandbox., max_agent_steps10, ) pipeline Pipeline() pipeline.add_component(agent, agent) # 序列化并还原——往返后四个工具仍然共享同一个 E2BSandbox yaml_str pipeline.dumps() restored Pipeline.loads(yaml_str) result restored.run( data{ agent: { messages: [ ChatMessage.from_user( Write a Python one-liner to /tmp/hello.py that prints Hello from E2B!, run it, then show me the output., ), ], }, }, ) print(result[agent][last_message].text)序列化链路的关键环节在于 haystack/tools/serde_utils.pyserialize_tools_or_toolset会把Toolset按{type: ..., data: ...}结构序列化保留 Tool/Toolset 边界deserialize_tools_or_toolset_inplace则通过import_class_by_name还原对应的类并调用其from_dict。Agent 自身的to_dict/from_dict也通过这两个工具函数处理tools参数见 haystack/components/agents/agent.py从而保证 Pipeline YAML 的完整往返。序列化安全与资源管理的注意事项从文档与源码可以归纳出三条实践要点显式关闭沙箱在 Agent/Pipeline 中生命周期由框架托管但独立使用工具或 Toolset 时务必在结束后调用close()释放云端资源避免空闲沙箱持续占用timeout参数是防止闲置资源堆积的兜底手段。instance_id缓存的安全语义from_dict的缓存命中要求完整配置api_key、template、timeout、environment_vars与缓存条目完全一致否则新建实例。这意味着反序列化恢复共享关系是配置校验通过前提下的行为不能通过伪造 id 访问缓存实例。幂等设计E2BSandbox.warm_up()与E2BToolset.warm_up()都是幂等的Agent 初始化与 Pipeline 预热阶段可能多次触发warm_up实现自定义沙箱类时应遵循同一约定。小结E2B 集成为 Haystack Agent 提供了生产可用的云端沙箱能力E2BSandbox负责连接与生命周期四个Tool子类分别封装 bash 执行与文件操作E2BToolset将这一切打包成可序列化的整体。无论你是想快速用E2BToolset开启 Agent 编码助手还是按需组合单个工具、或将沙箱 Agent 接入 Pipeline 的 YAML 持久化这套三层结构都能直接落地。进一步可参考API 参考docs-website/reference/integrations-api/e2b.md用户指南docs-website/docs/tools/ready-made-tools/e2btoolset.mdx框架侧 Tool 定义haystack/tools/tool.pyToolset 与序列化实现haystack/tools/toolset.py、haystack/tools/serde_utils.py【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考