本文基于 Deep Agents 官方源码进行分析,深入剖析其架构设计、核心组件与技术实现,为开发者提供 LangChain 生态最高层抽象框架的技术参考。

一、背景

在 LangChain 生态不断演进的过程中,我们已经看到了明确的分层架构:

  • langchain-core:基础抽象(Message、Tool、Runnable)
  • LangGraph:底层编排引擎(StateGraph、Checkpoint)
  • LangChain v1:应用层框架(create_agent、Middleware)

然而,即使使用 LangChain v1 的 create_agent,开发者仍需自行配置工具、设计 prompt、实现上下文管理。

Deep Agents 的出现填补了这一空白——它是 LangChain 生态中的最高层抽象,提供一个可立即运行的完整智能体。


二、项目定位

2.1 官方定义

从 Deep Agents 官方 README 可以看到其核心定位:

The batteries-included agent harness.

关键词:batteries-included(开箱即用)。这意味着 Deep Agents 的设计目标是提供一个无需配置即可运行的完整 Agent,而非让开发者从零开始组装。

2.2 核心能力

Deep Agents 默认提供以下能力:

能力 工具/机制 说明
规划 write_todos / read_todos 任务拆解与进度追踪
文件系统 read_file, write_file, edit_file, ls, glob, grep 读写上下文和项目文件
Shell 执行 execute 运行命令(支持沙箱隔离)
子智能体 task 委托任务给隔离的子 Agent
上下文管理 自动摘要 对话过长时自动摘要压缩
智能默认 Prompt 模板 内置工具使用指南

2.3 项目结构

deepagents-master/
├── libs/
│   ├── deepagents/      # SDK 核心库
│   ├── cli/             # 命令行工具
│   ├── acp/             # Agent Context Protocol 支持
│   └── harbor/          # 评估/基准测试框架
├── examples/            # 示例代码
└── README.md

三、依赖关系分析

3.1 Deep Agents 对 LangChain 的依赖

查看 Deep Agents 的 pyproject.toml

dependencies = [
    "langchain-core>=1.2.7,<2.0.0",
    "langchain>=1.2.7,<2.0.0",        # 依赖 LangChain v1
    "langchain-anthropic>=1.3.1,<2.0.0",
    "langchain-google-genai>=4.2.0,<5.0.0",
    "wcmatch",
]

Deep Agents 强制依赖 LangChain v1,而 LangChain v1 又依赖 LangGraph。

3.2 完整依赖链

┌─────────────────────────────────────────────────────────────────────┐
│                      Deep Agents                                    │
│              create_deep_agent()                                    │
│  - 预置 Middleware 栈                                               │
│  - 内置工具集(文件、Shell、规划、子智能体)                          │
│  - 自动上下文管理                                                    │
└─────────────────────────────┬───────────────────────────────────────┘
                              │ 调用
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                      LangChain v1                                   │
│              create_agent()                                         │
│  - Middleware 系统                                                   │
│  - 结构化输出                                                        │
└─────────────────────────────┬───────────────────────────────────────┘
                              │ 依赖
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                      LangGraph                                      │
│              StateGraph / CompiledStateGraph                        │
│  - 状态管理、检查点、中断恢复                                         │
└─────────────────────────────┬───────────────────────────────────────┘
                              │ 依赖
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                      langchain-core                                 │
│  - BaseChatModel、BaseMessage、BaseTool                             │
└─────────────────────────────────────────────────────────────────────┘

四、核心源码分析

4.1 入口函数:create_deep_agent

create_deep_agent 是 Deep Agents 的核心入口,位于 deepagents/graph.py

def create_deep_agent(
    model: str | BaseChatModel | None = None,
    tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
    *,
    system_prompt: str | SystemMessage | None = None,
    middleware: Sequence[AgentMiddleware] = (),
    subagents: list[SubAgent | CompiledSubAgent] | None = None,
    skills: list[str] | None = None,
    memory: list[str] | None = None,
    response_format: ResponseFormat | None = None,
    checkpointer: Checkpointer | None = None,
    store: BaseStore | None = None,
    backend: BackendProtocol | BackendFactory | None = None,
    interrupt_on: dict[str, bool | InterruptOnConfig] | None = None,
    debug: bool = False,
    name: str | None = None,
    cache: BaseCache | None = None,
) -> CompiledStateGraph:

关键设计点

  1. 返回类型是 CompiledStateGraph:与 LangGraph 完全兼容,可直接使用流式、检查点等特性
  2. 默认模型:Claude Sonnet 4.5(claude-sonnet-4-5-20250929
  3. 支持字符串格式模型"openai:gpt-4o" 语法快速切换

4.2 默认 Middleware 栈

从源码可以看到,create_deep_agent 自动组装以下中间件:

deepagent_middleware: list[AgentMiddleware] = [
    TodoListMiddleware(),                        # 待办事项管理
]
if memory is not None:
    deepagent_middleware.append(MemoryMiddleware(backend=backend, sources=memory))
if skills is not None:
    deepagent_middleware.append(SkillsMiddleware(backend=backend, sources=skills))
deepagent_middleware.extend([
    FilesystemMiddleware(backend=backend),       # 文件系统工具
    SubAgentMiddleware(                          # 子智能体工具
        default_model=model,
        default_tools=tools,
        subagents=subagents if subagents is not None else [],
        default_middleware=subagent_middleware,
        general_purpose_agent=True,
    ),
    SummarizationMiddleware(                     # 自动摘要
        model=model,
        backend=backend,
        trigger=trigger,
        keep=keep,
    ),
    AnthropicPromptCachingMiddleware(),          # Claude 提示缓存
    PatchToolCallsMiddleware(),                  # 工具调用修补
])
if interrupt_on is not None:
    deepagent_middleware.append(HumanInTheLoopMiddleware(interrupt_on=interrupt_on))

最终调用 LangChain v1 的 create_agent

return create_agent(
    model,
    system_prompt=final_system_prompt,
    tools=tools,
    middleware=deepagent_middleware,
    response_format=response_format,
    context_schema=context_schema,
    checkpointer=checkpointer,
    store=store,
    debug=debug,
    name=name,
    cache=cache,
).with_config({"recursion_limit": 1000})

4.3 后端架构(Backends)

Deep Agents 使用可插拔的后端架构,定义在 backends/protocol.py

class BackendProtocol(Protocol):
    """Protocol for pluggable memory backends."""

    def ls_info(self, path: str) -> list[FileInfo]: ...
    def read(self, file_path: str, offset: int = 0, limit: int = 2000) -> str: ...
    def write(self, file_path: str, content: str) -> WriteResult: ...
    def edit(self, file_path: str, old_string: str, new_string: str) -> EditResult: ...
    def glob_info(self, pattern: str, path: str = "/") -> list[FileInfo]: ...
    def grep_raw(self, pattern: str, path: str | None = None) -> list[GrepMatch] | str: ...

可用后端实现:

后端类 说明 适用场景
StateBackend 基于 LangGraph 状态存储 默认,适合临时任务
FilesystemBackend 真实文件系统 需要持久化文件操作
StoreBackend 基于 LangGraph Store 跨会话持久化
CompositeBackend 组合多个后端 复杂场景
SandboxBackend 沙箱执行环境 安全执行代码

五、子智能体系统

5.1 设计理念

Deep Agents 的子智能体系统允许主 Agent 将任务委托给专门的子 Agent:

create_deep_agent(
    subagents=[
        SubAgent(
            name="researcher",
            description="Research topics and gather information",
            system_prompt="You are a research specialist...",
            tools=[search_tool],
        ),
        SubAgent(
            name="coder",
            description="Write and debug code",
            system_prompt="You are an expert programmer...",
        ),
    ]
)

5.2 实现机制

middleware/subagents.py 可以看到:

class SubAgent(TypedDict):
    """Specification for an agent."""
    name: str
    description: str
    system_prompt: str
    tools: NotRequired[Sequence[BaseTool | Callable | dict[str, Any]]]
    model: NotRequired[str | BaseChatModel]
    middleware: NotRequired[list[AgentMiddleware]]
    interrupt_on: NotRequired[dict[str, bool | InterruptOnConfig]]

子智能体通过 task 工具调用:

def task(
    description: Annotated[str, "A detailed description of the task..."],
    subagent_type: Annotated[str, "The type of subagent to use..."],
    runtime: ToolRuntime,
) -> Command:
    # 创建子智能体并执行任务
    subagent = _get_subagents(...)[subagent_type]
    result = subagent.invoke(state)
    return _return_command_with_state_update(result, tool_call_id)

关键特性

  • 子 Agent 有隔离的上下文窗口
  • 支持不同的模型和工具
  • 结果通过 ToolMessage 返回给主 Agent

六、文件系统中间件

6.1 工具集

FilesystemMiddleware 提供完整的文件操作工具:

工具 功能 参数
ls 列出目录内容 path
read_file 读取文件 file_path, offset, limit
write_file 写入新文件 file_path, content
edit_file 编辑现有文件 file_path, old_string, new_string
glob 模式匹配搜索 pattern, path
grep 文本搜索 pattern, path, glob
execute 执行命令 command

6.2 安全设计

从源码可以看到路径验证逻辑:

def _validate_path(path: str, *, allowed_prefixes: Sequence[str] | None = None) -> str:
    """Validate and normalize file path for security.

    Ensures paths are safe to use by preventing directory traversal attacks
    and enforcing consistent formatting.
    """
    # 防止目录遍历攻击
    # 强制使用绝对路径
    # 路径规范化

七、CLI 工具

7.1 安装与使用

# 安装
uv tool install deepagents-cli

# 运行
deepagents
deepagents --model gpt-4o
deepagents --auto-approve          # 自动批准工具调用
deepagents --sandbox modal         # 远程沙箱执行

7.2 模型自动检测

CLI 根据可用 API Key 自动选择模型:

优先级 API Key 默认模型
1 OPENAI_API_KEY gpt-5.2
2 ANTHROPIC_API_KEY claude-sonnet-4-5-20250929
3 GOOGLE_API_KEY gemini-3-pro-preview

7.3 附加功能

  • 会话恢复:支持中断后继续对话
  • 持久记忆:通过 AGENTS.md 文件存储偏好
  • 技能系统:可复用的工作流和领域知识
  • 远程沙箱:Modal、Runloop、Daytona

八、评估框架 Harbor

8.1 定位

libs/harbor 提供 Agent 评估能力,支持 Terminal Bench 2.0 基准测试:

Terminal Bench 2.0 is an evaluation benchmark that measures agent capabilities across several domains, testing how well an agent operates using a computer environment, primarily via the terminal.

8.2 使用示例

# 在 Docker 中运行 1 个任务
uv run harbor run \
  --agent-import-path deepagents_harbor:DeepAgentsWrapper \
  --dataset terminal-bench@2.0 \
  -n 1 \
  --env docker

# 在 Daytona 云端运行 10 个任务
uv run harbor run \
  --agent-import-path deepagents_harbor:DeepAgentsWrapper \
  --dataset terminal-bench@2.0 \
  -n 10 \
  --env daytona

8.3 LangSmith 集成

Harbor 与 LangSmith 深度集成,支持:

  • 轨迹追踪
  • 性能分析
  • 奖励评分(0.0 - 1.0)

九、与其他框架对比

9.1 对比表格

特性 Deep Agents LangChain v1 create_agent LangGraph
抽象层级 最高(开箱即用) 高(需配置中间件) 低(需自定义图)
内置工具 ✅ 完整工具集 ❌ 需自行配置 ❌ 需自行配置
子智能体 ✅ 内置 task 工具 ❌ 需自行实现 ❌ 需自行实现
规划能力 ✅ TodoList 中间件 ❌ 需手动添加 ❌ 需自行实现
上下文管理 ✅ 自动摘要 ❌ 需手动添加 ❌ 需自行实现
CLI ✅ deepagents ❌ 无 ✅ langgraph
评估框架 ✅ Harbor ❌ 无 ❌ 无
学习曲线 平缓 中等 陡峭
灵活性

9.2 选型建议

使用 Deep Agents 的场景

  • 快速构建 Coding Agent
  • 需要文件操作、Shell 命令、规划能力
  • 需要子智能体委托任务
  • CLI 交互场景
  • 追求开箱即用

使用 LangChain v1 create_agent 的场景

  • 需要自定义中间件栈
  • 不需要完整的文件系统能力
  • 需要更精细的控制

直接使用 LangGraph 的场景

  • 复杂的多 Agent 协作系统
  • 非标准工作流(复杂分支、循环)
  • 需要对编排层有完全控制

十、使用示例

10.1 快速开始

from deepagents import create_deep_agent

agent = create_deep_agent()
result = agent.invoke({
    "messages": [{"role": "user", "content": "Research LangGraph and write a summary"}]
})

10.2 自定义配置

from langchain.chat_models import init_chat_model
from deepagents import create_deep_agent

agent = create_deep_agent(
    model=init_chat_model("openai:gpt-4o"),
    tools=[my_custom_tool],
    system_prompt="You are a research assistant.",
    subagents=[
        {
            "name": "searcher",
            "description": "Search the web for information",
            "system_prompt": "You are a search specialist.",
            "tools": [search_tool],
        }
    ],
    skills=["/skills/"],
    memory=["/memory/AGENTS.md"],
    interrupt_on={"edit_file": True},  # 编辑文件前需人工确认
)

10.3 流式输出

for chunk in agent.stream(
    {"messages": [{"role": "user", "content": "Write a Python script"}]},
    stream_mode="messages",
):
    print(chunk, end="", flush=True)

十一、安全模型

Deep Agents 采用 “Trust the LLM” 安全模型:

Deep Agents follows a “trust the LLM” model. The agent can do anything its tools allow. Enforce boundaries at the tool/sandbox level, not by expecting the model to self-police.

核心理念:

  1. LLM 不负责安全:不依赖模型自我约束
  2. 工具层限制:通过工具实现和后端配置限制能力
  3. 沙箱隔离:敏感操作在沙箱环境执行

十二、总结

Deep Agents 是 LangChain 生态中的最高层抽象,其核心价值在于:

  1. 开箱即用:无需配置即可获得完整的 Agent 能力
  2. 能力完整:内置规划、文件系统、子智能体、上下文管理
  3. 生态兼容:返回 CompiledStateGraph,可无缝使用 LangGraph 特性
  4. 评估支持:Harbor 框架支持标准化基准测试
  5. CLI 工具:终端交互体验

对于需要快速构建 Coding Agent 的开发者,Deep Agents 是目前 LangChain 生态中最省力的选择。其设计理念清晰——在最高层提供开箱即用的体验,同时保留向下兼容的完整能力。

理解 Deep Agents 在 LangChain 生态中的定位,有助于开发者根据实际需求选择合适的抽象层级:追求快速开发选 Deep Agents,追求灵活控制选 LangGraph,追求平衡选 LangChain v1。


参考资料:

  • Deep Agents 源码:https://github.com/langchain-ai/deepagents
  • LangChain 文档:https://docs.langchain.com/oss/python/deepagents/overview
  • Terminal Bench 2.0:https://github.com/laude-institute/terminal-bench-2
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐