Resource / Python

DeepAgents
Cheatsheet

整理 create_deep_agent、Filesystem、Backend、Skills、Memory、 Subagents、Human-in-the-loop 和 Middleware 等常用能力,重点说明默认行为、适用边界和生产环境需要注意的问题。

参考版本
DeepAgents 0.7.13
语言范围
Python · SDK
MODELreason
TOOLSact
TASKdelegate
FILEScontext
STATEpersist
Deep Agents 在标准 Agent Loop 上加入文件系统、上下文管理、子 Agent 与运行控制,并继续使用 LangGraph Runtime 执行。
一句话理解

Deep Agents 是一套有明确默认配置的 Agent Harness。它不是新的底层 Runtime,而是在 LangChain Agent 与 LangGraph 之上,把复杂任务常用的文件系统、上下文管理、子 Agent、Memory 和人工审批组合成一套可直接使用的 Agent 运行结构。

01 / BOOT

安装与最小 Agent

当前 Python 包名是 deepagents,要求 Python 3.11+。 使用具体模型时,还需要安装对应的 LangChain 模型集成。

terminalBash
pip install -U deepagents
terminal · OpenAIBash
pip install -U "langchain[openai]"
minimal_agent.pyPython
from deepagents import create_deep_agent
 
def get_weather(city: str) -> str:
    """查询指定城市的天气。"""
    return f"{city}: sunny"
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    tools=[get_weather],
    system_prompt="你负责回答天气相关问题。",
)
 
result = agent.invoke({
    "messages": [
        {"role": "user", "content": "北京天气怎么样?"}
    ]
})
 
print(result["messages"][-1].content)

02 / MODEL

Deep Agents 解决什么问题

普通 Agent Loop 解决的是“模型调用工具,再根据工具结果继续推理”。 Deep Agents 重点处理的是这类循环运行时间变长以后经常出现的问题: 上下文越来越大、需要操作文件、需要把子任务隔离出去、需要长期记忆, 以及某些工具不能直接执行。

Execution

工具、虚拟文件系统、Sandbox 和可选代码执行环境。

Context

Skills、Memory、摘要、结果卸载和 Prompt Cache。

Delegation

通过 task 工具把独立任务交给 Subagent。

Steering

使用 Interrupt 和权限规则控制高风险操作。

三层分别负责什么
主要职责什么时候直接使用
LangChain Agent标准模型与 Tool Calling AgentAgent 较简单,不需要完整 Harness
Deep Agents带 Filesystem、Subagent、Memory 等能力的 Agent Harness复杂、多步骤、长时间运行的 Agent
LangGraphState、Graph、Persistence、Interrupt 与 Durable Runtime需要自定义整个执行图和状态机

03 / CREATE

create_deep_agent 是主要入口

大多数 Deep Agents 应用都从 create_deep_agent() 开始。 不要一开始就修改内部 Middleware Stack,先确认默认 Harness 是否已经覆盖需求。

agent.pyPython
from deepagents import create_deep_agent
 
agent = create_deep_agent(
    model=model,
    tools=[search, fetch_page],
    system_prompt="你是一个技术研究 Agent。",
    memory=["./AGENTS.md"],
    skills=["./skills/"],
    subagents=[researcher],
    backend=backend,
    permissions=permissions,
    interrupt_on={
        "write_file": {
            "allowed_decisions": ["approve", "edit", "reject"]
        }
    },
    middleware=[...],
    response_format=Report,
    checkpointer=checkpointer,
    store=store,
)
常用配置项
参数用途
model模型字符串或 BaseChatModel
tools业务工具
system_prompt应用自己的行为约束和任务说明
backend虚拟文件系统的数据来源与持久范围
skills按需加载的 Agent Skills
memory启动时加载的 AGENTS.md 类长期信息
subagents声明可委派任务的专用 Subagent
permissions文件系统路径级访问控制
interrupt_on指定需要人工审核的 Tool Call
middleware增加或覆盖 Middleware 行为
response_format结构化最终输出
checkpointer线程状态、Interrupt 和恢复
store跨 Thread 数据持久化

04 / TOOLS

Model 与 Tools

如果只需要使用默认模型参数,可以直接传provider:model。需要配置 temperature、timeout、 max_retries 等参数时,先创建模型实例,再传给 Deep Agents。

model.pyPython
from langchain.chat_models import init_chat_model
from deepagents import create_deep_agent
 
model = init_chat_model(
    "openai:gpt-5.5",
    temperature=0,
)
 
agent = create_deep_agent(model=model)

业务能力仍然使用标准 LangChain Tool。普通 Python 函数、使用@tool 声明的工具,以及 MCP 提供的工具都可以加入tools

tools.pyPython
from langchain.tools import tool
from deepagents import create_deep_agent
 
@tool
def search_docs(query: str) -> str:
    """搜索内部技术文档。"""
    return search_service.search(query)
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    tools=[search_docs],
)

05 / FILESYSTEM

Filesystem 与 Backend

文件系统是 Deep Agents 最重要的默认能力之一。Agent 可以把长结果和中间材料放到文件里,不必持续占用消息上下文。

当前内置 Filesystem Tools
Tool用途
ls列出目录
read_file读取文件,可按 offset / limit 分段
write_file创建或覆盖文件
edit_file精确替换文件内容
delete删除文件或目录
glob按模式查找文件
grep搜索文件内容
execute执行 Shell;仅支持该能力的 Backend 提供

默认 Backend 是 StateBackend。文件放在 LangGraph State 中,因此它们属于当前 Thread;配置 Checkpointer 后可以跨 Turn 保存,但不会自动跨 Thread 共享。

local_filesystem.pyPython
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend
 
backend = FilesystemBackend(
    root_dir="/workspace",
)
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    backend=backend,
)

需要跨 Thread 时使用 StoreBackend

store_backend.pyPython
from deepagents import create_deep_agent
from deepagents.backends import StoreBackend
from langgraph.store.memory import InMemoryStore
 
backend = StoreBackend(
    namespace=lambda runtime: (
        runtime.server_info.user.identity,
    ),
)
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    backend=backend,
    store=InMemoryStore(),  # 仅适合本地开发
)

短期文件和长期 Memory 可以使用不同 Backend

composite_backend.pyPython
from deepagents import create_deep_agent
from deepagents.backends import (
    CompositeBackend,
    StateBackend,
    StoreBackend,
)
 
backend = CompositeBackend(
    default=StateBackend(),
    routes={
        "/memories/": StoreBackend(
            namespace=lambda runtime: (
                runtime.server_info.user.identity,
                "memories",
            )
        ),
    },
)
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    backend=backend,
    store=store,
)

这类结构很适合实际 Agent:普通工作文件留在 Thread State,/memories/ 再路由到跨 Thread Store。

06 / SECURITY

权限边界必须落到 Tool 和执行环境

Deep Agents 提供 Filesystem Permission Rules。规则按声明顺序匹配, 第一个匹配项生效;如果没有任何规则匹配,默认允许访问。

permissions.pyPython
from deepagents import create_deep_agent
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    permissions=[
        {
            "operations": ["read", "write"],
            "paths": ["/workspace/**"],
            "mode": "allow",
        },
        {
            "operations": ["read", "write"],
            "paths": ["/workspace/.env"],
            "mode": "deny",
        },
    ],
)

只读 Agent 不要只靠 Prompt 约束

readonly_agent.pyPython
from deepagents import create_deep_agent
from deepagents.middleware import FilesystemMiddleware
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    middleware=[
        FilesystemMiddleware(
            backend=backend,
            tools=["read_file", "ls", "glob", "grep"],
        )
    ],
)

FilesystemMiddleware 的工具 allowlist 可以直接把write_fileedit_filedelete等工具从模型可见范围中移除。read_file 必须保留。

07 / CONTEXT

Skills 与 Memory 不要混成一件事

ON DEMAND

Skills

任务需要时才加载完整内容,适合流程、规范、领域知识和可复用操作方法。

AT STARTUP

Memory

Agent 启动时进入上下文,适合长期偏好、项目约定和持续生效的规则。

Skill 使用渐进式加载

projectText
skills/
└── code-review/
    ├── SKILL.md
    ├── scripts/
    │   └── check.py
    ├── references/
    │   └── rules.md
    └── assets/
        └── template.md
skills/code-review/SKILL.mdMarkdown
---
name: code-review
description: Review Python code for correctness, maintainability, and security.
---
 
# Code Review
 
检查顺序:
 
1. 正确性
2. 异常处理
3. API 边界
4. 安全问题
5. 可维护性
 
只有任务涉及代码审查时才使用本 Skill。

Deep Agents 的 Skills 遵循 Agent Skills 目录形式。启动时主要读取 Skill 元信息,只有命中任务时才进一步读取SKILL.md 和 supporting files。

Memory 使用文件保存长期上下文

memory.pyPython
from deepagents import create_deep_agent
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    memory=[
        "./AGENTS.md",
        "./memory/project.md",
    ],
)

08 / DELEGATE

Subagents 用来隔离任务,不是为了增加 Agent 数量

Deep Agents 默认提供一个同步的general-purpose Subagent,并通过task 工具执行委派。一次 Subagent 调用拥有独立上下文, 完成后只把最终结果交回主 Agent。

subagents.pyPython
from deepagents import create_deep_agent
 
researcher = {
    "name": "researcher",
    "description": (
        "负责需要独立检索和交叉核验的技术研究任务。"
        "当问题需要阅读多份资料后再给出结论时使用。"
    ),
    "system_prompt": (
        "你负责技术研究。优先使用一手资料,"
        "返回简洁、可验证的研究结论。"
    ),
    "tools": [search_docs, fetch_page],
}
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    subagents=[researcher],
)
Description 决定什么时候调用

不要只写“研究 Agent”。说明它处理什么任务,以及什么情况下应该委派。

工具越少越容易稳定

专用 Subagent 只给完成任务所需的 Tool,不要机械继承整个主 Agent 工具集。

返回结果要压缩

Subagent 的价值之一就是隔离 Context。如果把全部中间过程重新返回主 Agent, 就失去了隔离意义。

09 / PLAN

Task Planning 在 0.7 中改为按需启用

旧版本 Deep Agents 默认带 Todo Planning。0.7 开始不再默认加入,确实需要显式任务清单时再添加TodoListMiddleware

planning.pyPython
from deepagents import create_deep_agent
from langchain.agents.middleware import TodoListMiddleware
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    middleware=[
        TodoListMiddleware(),
    ],
)

Todo 更适合长任务、多步骤研究,或者前端需要持续展示任务状态的应用。 简单问答或两三步就能完成的 Agent 没必要为了“更 Agentic”强行生成计划。

10 / REVIEW

Human-in-the-loop 用在真正有风险的 Tool Call

对发送邮件、删除数据、修改生产配置、写外部系统等操作,可以通过interrupt_on 在 Tool 真正执行前暂停。

human_review.pyPython
from deepagents import create_deep_agent
from langgraph.checkpoint.memory import MemorySaver
 
checkpointer = MemorySaver()
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    tools=[send_email],
    interrupt_on={
        "send_email": {
            "allowed_decisions": [
                "approve",
                "edit",
                "reject",
            ]
        }
    },
    checkpointer=checkpointer,
)

Human-in-the-loop 依赖 LangGraph Interrupt,因此必须配置 Checkpointer, 并在恢复时继续使用相同的 thread_id

resume.pyPython
from langgraph.types import Command
 
config = {
    "configurable": {
        "thread_id": "review-1",
    }
}
 
result = agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "给 team@example.com 发送通知",
            }
        ]
    },
    config=config,
    version="v2",
)
 
if result.interrupts:
    result = agent.invoke(
        Command(
            resume={
                "decisions": [
                    {"type": "approve"}
                ]
            }
        ),
        config=config,
        version="v2",
    )
常见人工决策
Decision语义
approve按原参数继续执行
edit修改 Tool Call 后执行
reject拒绝当前操作
respond由人工给出替代响应

11 / EXTEND

Middleware 用于修改 Agent 行为,不要替代业务 Tool

Deep Agents 本身就是一组预配置 Middleware 组合。 需要增加日志、Guardrail、动态模型选择、Prompt 调整或上下文处理时,再增加 LangChain Agent Middleware。

传入的 Middleware 如果名称与内置 Middleware 相同,会替换对应实例; 其他 Middleware 会被合并到 Deep Agents Stack 中。

最终结果需要固定结构时使用 response_format

structured_output.pyPython
from pydantic import BaseModel
from deepagents import create_deep_agent
 
class ResearchResult(BaseModel):
    summary: str
    findings: list[str]
    risks: list[str]
 
agent = create_deep_agent(
    model="openai:gpt-5.5",
    response_format=ResearchResult,
)

12 / RUNTIME

持久化和 Streaming 仍然来自 LangGraph Runtime

create_deep_agent() 返回的是可执行的 LangGraph CompiledStateGraph,因此仍然使用invoke()stream()、Checkpointer、 Store 和 Interrupt 这一套运行模型。

stream.pyPython
for chunk in agent.stream(
    {
        "messages": [
            {"role": "user", "content": "分析这个项目"}
        ]
    },
    config=config,
    stream_mode=["messages", "updates"],
):
    print(chunk)

长时间任务应优先使用 Streaming 暴露模型输出、Tool 调用和 Subagent 进度,而不是让客户端一直等待最终字符串。

13 / VERSION

0.7 系列需要特别注意的变化

旧写法与当前行为
项目当前行为
Task Planning0.7 起默认关闭,需要显式添加 TodoListMiddleware
delete0.7 起加入 Filesystem Tool Surface
Filesystem allowlist0.7 起可通过 FilesystemMiddleware.tools 限制暴露的文件工具
backend=lambda ...旧式 callable Backend 已弃用,应直接传 Backend 实例
StateBackend(runtime)改为直接使用 StateBackend()
Forked Subagent0.7.13 提供,当前仍为 Beta

14 / DEBUG

常见误区与排查方法

症状、原因与处理方向
现象常见原因先检查
Agent 不调用 ToolTool description 模糊或模型 Tool Calling 能力不足Tool 名称、Schema、docstring 和模型能力
主 Agent Context 仍然很大没有正确委派,或 Subagent 返回过多中间材料任务边界和 Subagent 返回格式
Subagent 总是选错description 互相重叠描述是否明确说明适用任务
Memory 无法跨会话仍在使用 thread-scoped StateBackendStoreBackend、Store 与 namespace
不同用户看到相同数据Store namespace 未隔离user / tenant namespace
Interrupt 无法继续没有 Checkpointer 或换了 thread_id首次调用与 resume 的 config
只读 Agent 仍能写文件只在 Prompt 中禁止,没有限制 Tool SurfaceFilesystemMiddleware.tools 与 Backend 权限
文件权限看似失效Sandbox execute 绕过虚拟文件 ToolSandbox / OS 层安全边界
升级 0.7 后 Backend 报错仍使用 callable backend 或旧 Runtime 构造方式是否直接传 Backend 实例

15 / SHIP

生产检查清单

  • 模型明确支持 Tool Calling,并针对实际 Tool Schema 做过测试。
  • 业务 Tool 名称、参数和说明清晰,不把多个无关操作合成一个 Tool。
  • System Prompt 只负责行为与业务约束,真正的安全边界放在 Tool、Backend 和 Sandbox。
  • 普通工作文件与长期 Memory 明确区分 StateBackend 和 StoreBackend。
  • 多用户 Store 使用稳定的 user / tenant namespace 隔离数据。
  • 敏感路径明确 deny;只读 Agent 从 Tool Surface 移除写入、编辑和删除能力。
  • 具有 execute 能力的 Sandbox 在容器、网络、凭据和文件系统层面做独立隔离。
  • Skills 保持单一职责;大型参考资料不要全部写入 SKILL.md。
  • 持续生效的信息放 Memory,按任务加载的信息放 Skills,大型知识库使用 Retrieval。
  • Subagent description 明确说明适用任务,专用 Subagent 只保留必要工具。
  • 没有实际规划需求时不添加 TodoListMiddleware。
  • 发送、删除、发布、部署、扣费等高风险 Tool 使用 interrupt_on 或更底层权限控制。
  • Human-in-the-loop 配置持久化 Checkpointer,并稳定传递 thread_id。
  • 长任务通过 Streaming 暴露 Tool、Agent 与 Subagent 进度。
  • 生产环境不用 InMemoryStore / MemorySaver 作为最终持久层。
  • LangSmith Trace 至少覆盖模型调用、Tool Call、Subagent、错误和耗时。
  • 升级 Deep Agents 前检查 Changelog,尤其关注 Middleware、Backend 与 Subagent 行为变化。

16 / SOURCES

官方资料与参考范围

本页 API、默认行为和版本说明以 LangChain 官方 Deep Agents 文档与当前 PyPI 稳定版本为准。