第 04 章 · 沙箱执行与 Shell 工具
当智能体需要安装依赖、运行测试或调用 CLI 时,要执行 shell。sandbox backend 提供 execute 工具,把系统副作用关在隔离环境里。
机制与设计选择
deepagents.backends.LocalShellBackend 是本地 shell backend:它把 execute 工具限制在 root_dir,通过 timeout 与 max_output_bytes 控制爆炸半径。生产环境更常见的是 LangSmith/AgentCore/Daytona/E2B 等远程沙箱,需要额外凭据与网络可达。
示例
python
import os
from langchain_openai import ChatOpenAI
model = ChatOpenAI(
model=os.environ["MODEL_ID"],
api_key=os.environ["DEEPAGENT_API_KEY"],
base_url=os.environ.get("DEEPAGENT_BASE_URL", "https://api.openai.com/v1"),
)
import shutil, tempfile
from deepagents import create_deep_agent
from deepagents.backends import LocalShellBackend
root = tempfile.mkdtemp(prefix="deepagents-shell-")
try:
agent = create_deep_agent(
model=model,
backend=LocalShellBackend(root_dir=root, virtual_mode=True, timeout=60),
system_prompt="When asked to run a command, use the execute tool.",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "Run: echo hello-from-shell > out.txt and then cat out.txt."}]},
{"configurable": {"thread_id": "ch04"}},
)
print(result["messages"][-1].content)
finally:
shutil.rmtree(root, ignore_errors=True)运行与验收
需要 API Key。验收:最终消息包含 hello-from-shell,且临时目录被清理后没有残留文件。
容易踩的坑
execute 是系统级副作用,务必保留 sandbox 的 root/网络/凭据边界;不要让 execute 与声明式 permissions 互相替代。LocalShellBackend 在本机执行,适合学习或离线测试;生产环境用远程沙箱并单独审计。
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. execute 由谁提供?
2. LocalShellBackend 适合生产吗?
3. timeout 控制什么?
4. execute 可以绕过 permissions 吗?
动手实践
- 写一个失败命令(exit 1)并观察工具返回。
- 把 timeout 降到 5 秒并构造一个长任务。
- 对比本地与远程沙箱的凭据隔离差异。
官方参考
核验日期:2026-09-17,运行环境:Deep Agents 0.7.15。