代理代码

人工智能 社区

技能解读

当前原文的自动摘译,尚未人工审校。

0.5.x 中的新增内容(在构建之前值得了解)

异步子代理是一流的 - 子代理现在可以是 async def 可调用并与 await agent.ainvoke(...) 端到端运行。在同一个subagents=[...]列表中混合同步和异步子代理。 model=None 在 create_deep_agent (0.5.3) 中已弃用。始终传递显式模型,例如init_chat_model("anthropic:claude-sonnet-4-6")。文件系统权限系统 (0.5.2) — CompositeBackend 上的路由范围读/写规则;沙箱现在是默认执行方式。权限路径必须以/开头;路径遍历引发ValueError。

DeepAgents 到底是什么

create_deep_agent(...)是create_agent(...)的薄包装,预装了三个中间件:FilesystemMiddleware(虚拟FS + read_file/write_file/edit_file/ls/glob/grep), SubAgentMiddleware(带有命名子代理的task工具)和TodoListMiddleware(write_todos规划工具)。您可以在顶部堆叠其他中间件。这意味着:您所知道的关于代理中间件的一切都适用。请参阅 langchain-agents-middleware 了解生产堆栈 — DeepAgents 项目从中受益,就像普通的 create_agent 项目一样。

文件系统后端 - 故意选择用于生产

默认的 FilesystemMiddleware 使用内存中的虚拟 FS,它会在调用之间重置,除非您通过检查指针。对于生产,选择一个后端:后端 · 范围 · 默认时(内存中) · 单次调用 · 开发、测试 StateBackend · 单线程(带检查点) · 仅对话内存 StoreBackend(namespace=(assistant_id, user_id)) · 每用户持久 · 生产:每个用户获得独立的文件

沙盒 shell 执行 - 在添加工具执行之前阅读此内容

对于运行真实 shell 命令的工具,请使用带有沙盒执行策略的ShellToolMiddleware(Daytona 是主要支持的沙盒)。两种生命周期模式: 线程范围(最常见):每个会话都有新容器,在 TTL 上清理。助理范围:跨对话共享,保留已安装的包/克隆的存储库。文档仅顺便提及的关键规则:切勿将原始 API 密钥传递到沙箱中。代理可以read_file沙箱可以访问的任何文件。使用身份验证代理在调用时注入凭据。将沙箱视为对抗环境。

子代理设计经验规则

子代理提示是模板——父代理的task工具填写{description}。保持提示通用;家长决定具体细节。 instructions=适用于顶级代理,不适用于下级代理。每个子代理都有自己的prompt字段。每个子代理的范围工具。 researcher子代理很少需要send_email。每个子代理tools键缩小了表面并提高了可靠性。

流狐档案 运行与权限由流狐静态检查推断,不代表作者声明或实际测试结果。
领域
人工智能
作者声明的智能体
未找到明确声明;不据此推断已兼容或已测试
静态检查
88 / 100 · 启发式扫描,不代表运行安全
运行环境证据
未执行;当前没有隔离运行测试证据
作者 / 版本 / 许可证
@tomevault-io · 未声明许可证
上下文用量评级
低消耗
接入复杂程度
需简单配置
是否需要外部接口密钥
不需要
兼容的系统
未声明(默认跨平台)
运行环境要求
Python
检测到的文件与系统行为
  • 只读
  • 允许写入 / 修改
  • 命令执行
网络行为
允许外网请求
安装命令数
无(仅作为资料)

需要注意: 未声明工具权限范围;实际权限由运行环境决定。

作者说明文件(原文) SKILL.md

# DeepAgents: editorial guidance

Targets `deepagents>=0.5.3`. For API reference (signatures, kwargs, full middleware list), use the **`mcpdoc` MCP tools**: `fetch_docs("https://docs.langchain.com/oss/python/deepagents/...")`. This skill is the *opinions* layer.

## What's new in 0.5.x (worth knowing before you build)

- **Async sub-agents** are first-class — sub-agents can now be `async def` callables and run with `await agent.ainvoke(...)` end-to-end. Mix sync and async sub-agents in the same `subagents=[...]` list.
- **`model=None` is deprecated** in `create_deep_agent` (0.5.3). Always pass an explicit model, e.g. `init_chat_model("anthropic:claude-sonnet-4-6")`.
- **Filesystem permissions system** (0.5.2) — route-scoped read/write rules on `CompositeBackend`; sandbox is now the default for execution. Permission paths must start with `/`; path-traversal raises `ValueError`.
- **Structured sub-agent responses** (0.5.3) — declare a Pydantic schema on a sub-agent and the parent receives a typed object instead of free text. Use this for "researcher returns a `Findings` object" patterns.
- **Legacy subagents API removed** (0.5.0). If you're upgrading from 0.4.x, the old kwargs are gone — see `subagents=[...]` with the new `SubAgent` shape.

## What DeepAgents actually is

`create_deep_agent(...)` is a thin wrapper over `create_agent(...)` that pre-installs three middlewares: `FilesystemMiddleware` (virtual FS + `read_file`/`write_file`/`edit_file`/`ls`/`glob`/`grep`), `SubAgentMiddleware` (the `task` tool with named sub-agents), and `TodoListMiddleware` (the `write_todos` planning tool). You can stack additional middlewares on top.

The implication: **everything you know about agentic middleware applies.** See `langchain-agents-middleware` for the production stack — DeepAgents projects benefit from it just like plain `create_agent` projects do.

## Filesystem backend — pick deliberately for production

The default `FilesystemMiddleware` uses an **in-memory virtual FS** that resets between invocations unless you pass a checkpointer. For production, choose a backend:

| Backend | Scope | When |
|---|---|---|
| Default (in-memory) | Single invocation | Dev, tests |
| `StateBackend` | Single thread (with checkpointer) | Conversation memory only |
| `StoreBackend(namespace=(assistant_id, user_id))` | Per-user persistent | Production: each user gets isolated files |
| `CompositeBackend` | Mix scopes | E.g. ephemeral scratch + persistent `/memories/` |

**`StoreBackend` namespaced by user is the production default.** Don't ship a multi-user agent with the in-memory default — files would leak across users.

**Filesystem permissions (0.5.2+)** — on `CompositeBackend` you can scope read/write/exec permissions per route, with sandbox as the default. Permission paths must start with `/` (a leading `./` or path-traversal raises `ValueError`). Use this to make `/memories/` read-only to a sub-agent that should only consume past notes, or to forbid writes outside `/scratch/`.

## Sandboxed shell execution — read this before adding tool execution

For tools that run real shell commands, use `ShellToolMiddleware` with a sandboxed execution policy (Daytona is the primary supported sandbox). Two lifecycle patterns:
- **Thread-scoped** (most common): fresh container per conversation, cleaned up on TTL.
- **Assistant-scoped**: shared across conversations, preserves installed packages / cloned repos.

**Critical rule the docs only mention in passing:** never pass raw API keys into a sandbox. The agent can `read_file` any file the sandbox can. Use the auth proxy to inject credentials at call time. Treat sandboxes as adversarial environments.

## Sub-agent design rules of thumb

- **Sub-agent prompts are templates** — the parent's `task` tool fills in `{description}`. Keep prompts generic; the parent decides the specifics.
- **`instructions=` is for the top-level agent**, not for sub-agents. Each sub-agent has its own `prompt` field.
- **Scope tools per sub-agent.** A `researcher` sub-agent rarely needs `send_email`. The per-subagent `tools` key narrows the surface and improves reliability.
- **Don't nest sub-agents more than one level deep.** Two-level nesting works; three-level becomes hard to reason about and hard to trace.
- **Use async sub-agents (0.5+) when sub-agents do I/O** — network fetches, vector store reads, MCP calls. Define the sub-agent function as `async def`, drive the parent with `await agent.ainvoke(...)`, and the runtime parallelises sibling sub-agent calls automatically. Don't make a sub-agent async if its body is pure CPU.
- **Return structured outputs (0.5.3+) for downstream consumption.** Attach a Pydantic `response_format` to a sub-agent and the parent's `task` tool returns a typed object — much more reliable than parsing free-text findings.

```python
# Async sub-agent with structured output
from pydantic import BaseModel

class Findings(BaseModel):
    summary: str
    sources: list[str]

async def research(state, runtime):
    # ... do async I/O (web search, mcp calls) ...
    return state

subagents = [
    {
        "name": "researcher",
        "description": "Researches a topic and returns structured findings.",
        "prompt": "Research {description} and return findings.",
        "tools": [web_search],
        "response_format": Findings,
        "callable": research,    # async def is supported
    },
]
```

## When to compose extra middlewares (almost always)

`create_deep_agent` accepts a `middleware=[...]` parameter that adds to (not replaces) the built-in three. For any production DeepAgent, layer the production stack on top:

```python
from deepagents import create_deep_agent
from langchain.agents.middleware import (
    ModelCallLimitMiddleware, ToolCallLimitMiddleware,
    ModelRetryMiddleware, ToolRetryMiddleware,
    ModelFallbackMiddleware, SummarizationMiddleware,
    HumanInTheLoopMiddleware, PIIMiddleware,
)

agent = create_deep_agent(
    model="claude-sonnet-4-6",   # required as of 0.5.3 — `model=None` is deprecated
    tools=TOOLS,
    subagents=SUBAGENTS,
    instructions=PROMPT,
    middleware=[
        ModelCallLimitMiddleware(run_limit=50),
        ToolCallLimitMiddleware(run_limit=200),
        ModelRetryMiddleware(max_retries=3),
        ToolRetryMiddleware(max_retries=3),
        ModelFallbackMiddleware("openai:gpt-4o-mini"),
        SummarizationMiddleware(model="claude-haiku-4-5", trigger=("tokens", 8000), keep=("messages", 20)),
        # HITL on irreversible tools — requires checkpointer
        HumanInTheLoopMiddleware(interrupt_on={"send_email": {"allowed_decisions": ["approve","edit","reject"]}}),
        PIIMiddleware("email", strategy="redact", apply_to_input=True),
    ],
)
```

## Things the docs won't warn you about

- The virtual FS persists across `agent.invoke(...)` calls within a single LangGraph run, but resets between runs unless you pass a checkpointer with a stable `thread_id`.
- Adding `HumanInTheLoopMiddleware` requires a checkpointer at compile time. `create_deep_agent` accepts a `checkpointer=` parameter for this.
- Sub-agents share the parent's tool registry by default. If a sub-agent should NOT see a tool, scope explicitly.
- `interrupt_on={...}` set on the parent **inherits to sub-agents** (fixed in 0.5.0). If you want sub-agents to bypass HITL gates, override on the sub-agent definition.
- Async sub-agents only run async if the parent is invoked with `ainvoke/astream` — calling `agent.invoke(...)` on an async sub-agent runs it in a sync wrapper and you lose the parallelism benefit.

## Doc URLs to fetch with mcpdoc

- `https://docs.langchain.com/oss/python/deepagents/index.md` — overview
- `https://docs.langchain.com/oss/python/deepagents/going-to-production.md` — backends, sandboxes, deployment
- `https://docs.langchain.com/oss/python/deepagents/memory.md` — filesystem backends in depth
- `https://docs.langchain.com/oss/python/deepagents/human-in-the-loop.md` — HITL patterns

---
> Source: [cwijayasundara/agent_cli_langchain](https://github.com/cwijayasundara/agent_cli_langchain) — distributed by [TomeVault](https://tomevault.io).
<!-- tomevault:4.0:skill_md:2026-05-23 -->

讨论

基于 GitHub Discussions。登录 GitHub 即可参与讨论、点赞、订阅更新。