deepagents-architecture

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Deep Agents Architecture Decisions

Deep Agents 架构决策指南

When to Use Deep Agents

何时使用Deep Agents

Use Deep Agents When You Need:

以下场景建议使用Deep Agents:

  • Long-horizon tasks - Complex workflows spanning dozens of tool calls
  • Planning capabilities - Task decomposition before execution
  • Filesystem operations - Reading, writing, and editing files
  • Subagent delegation - Isolated task execution with separate context windows
  • Persistent memory - Long-term storage across conversations
  • Human-in-the-loop - Approval gates for sensitive operations
  • Context management - Auto-summarization for long conversations
  • 长周期任务 - 涉及数十次工具调用的复杂工作流
  • 规划能力 - 执行前的任务拆解
  • 文件系统操作 - 读取、写入和编辑文件
  • 子代理委托 - 独立上下文窗口中的隔离任务执行
  • 持久化记忆 - 跨对话的长期存储
  • 人机协作 - 敏感操作的审批关卡
  • 上下文管理 - 长对话的自动摘要

Consider Alternatives When:

以下场景考虑替代方案:

ScenarioAlternativeWhy
Single LLM callDirect API callDeep Agents overhead not justified
Simple RAG pipelineLangChain LCELSimpler abstraction
Custom graph control flowLangGraph directlyMore flexibility
No file operations needed
create_react_agent
Lighter weight
Stateless tool useFunction callingNo middleware needed
场景替代方案原因
单次LLM调用直接API调用Deep Agents的开销得不偿失
简单RAG流水线LangChain LCEL更简洁的抽象
自定义图控制流直接使用LangGraph灵活性更高
无需文件操作
create_react_agent
更轻量化
无状态工具调用函数调用无需中间件

Backend Selection

后端选择

Backend Comparison

后端对比

BackendPersistenceUse CaseRequires
StateBackend
Ephemeral (per-thread)Working files, temp dataNothing (default)
FilesystemBackend
DiskLocal development, real files
root_dir
path
StoreBackend
Cross-threadUser preferences, knowledge basesLangGraph
store
CompositeBackend
MixedHybrid memory patternsMultiple backends
后端持久化特性使用场景依赖条件
StateBackend
临时存储(单线程)工作文件、临时数据无(默认)
FilesystemBackend
磁盘存储本地开发、真实文件操作
root_dir
路径
StoreBackend
跨线程共享用户偏好、知识库LangGraph
store
CompositeBackend
混合存储混合记忆模式多个后端

Backend Decision Tree

后端决策树

Need real disk access?
├─ Yes → FilesystemBackend(root_dir="/path")
└─ No
   └─ Need persistence across conversations?
      ├─ Yes → Need mixed ephemeral + persistent?
      │  ├─ Yes → CompositeBackend
      │  └─ No → StoreBackend
      └─ No → StateBackend (default)
Need real disk access?
├─ Yes → FilesystemBackend(root_dir="/path")
└─ No
   └─ Need persistence across conversations?
      ├─ Yes → Need mixed ephemeral + persistent?
      │  ├─ Yes → CompositeBackend
      │  └─ No → StoreBackend
      └─ No → StateBackend (default)

CompositeBackend Routing

CompositeBackend 路由配置

Route different paths to different storage backends:
python
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, StoreBackend

agent = create_deep_agent(
    backend=CompositeBackend(
        default=StateBackend(),  # Working files (ephemeral)
        routes={
            "/memories/": StoreBackend(store=store),    # Persistent
            "/preferences/": StoreBackend(store=store), # Persistent
        },
    ),
)
将不同路径路由到不同存储后端:
python
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, StoreBackend

agent = create_deep_agent(
    backend=CompositeBackend(
        default=StateBackend(),  # Working files (ephemeral)
        routes={
            "/memories/": StoreBackend(store=store),    # Persistent
            "/preferences/": StoreBackend(store=store), # Persistent
        },
    ),
)

Subagent Architecture

子代理架构

When to Use Subagents

何时使用子代理

Use subagents when:
  • Task is complex, multi-step, and can run independently
  • Task requires heavy context that would bloat the main thread
  • Multiple independent tasks can run in parallel
  • You need isolated execution (sandboxing)
  • You only care about the final result, not intermediate steps
Don't use subagents when:
  • Task is trivial (few tool calls)
  • You need to see intermediate reasoning
  • Splitting adds latency without benefit
  • Task depends on main thread state mid-execution
以下场景使用子代理:
  • 任务复杂、多步骤且可独立执行
  • 任务需要大量上下文,会导致主线程膨胀
  • 多个独立任务可并行执行
  • 需要隔离执行(沙箱环境)
  • 仅关注最终结果,无需中间步骤
以下场景不建议使用子代理:
  • 任务简单(仅需少量工具调用)
  • 需要查看中间推理过程
  • 拆分任务会增加延迟且无收益
  • 任务执行过程中依赖主线程状态

Subagent Patterns

子代理模式

Pattern 1: Parallel Research

模式1:并行研究

         ┌─────────────┐
         │  Orchestrator│
         └──────┬──────┘
    ┌──────────┼──────────┐
    ▼          ▼          ▼
┌──────┐  ┌──────┐  ┌──────┐
│Task A│  │Task B│  │Task C│
└──┬───┘  └──┬───┘  └──┬───┘
   └──────────┼──────────┘
      ┌─────────────┐
      │  Synthesize │
      └─────────────┘
Best for: Research on multiple topics, parallel analysis, batch processing.
         ┌─────────────┐
         │  Orchestrator│
         └──────┬──────┘
    ┌──────────┼──────────┐
    ▼          ▼          ▼
┌──────┐  ┌──────┐  ┌──────┐
│Task A│  │Task B│  │Task C│
└──┬───┘  └──┬───┘  └──┬───┘
   └──────────┼──────────┘
      ┌─────────────┐
      │  Synthesize │
      └─────────────┘
最适合:多主题研究、并行分析、批量处理。

Pattern 2: Specialized Agents

模式2:专业领域代理

python
research_agent = {
    "name": "researcher",
    "description": "Deep research on complex topics",
    "system_prompt": "You are an expert researcher...",
    "tools": [web_search, document_reader],
}

coder_agent = {
    "name": "coder",
    "description": "Write and review code",
    "system_prompt": "You are an expert programmer...",
    "tools": [code_executor, linter],
}

agent = create_deep_agent(subagents=[research_agent, coder_agent])
Best for: Domain-specific expertise, different tool sets per task type.
python
research_agent = {
    "name": "researcher",
    "description": "Deep research on complex topics",
    "system_prompt": "You are an expert researcher...",
    "tools": [web_search, document_reader],
}

coder_agent = {
    "name": "coder",
    "description": "Write and review code",
    "system_prompt": "You are an expert programmer...",
    "tools": [code_executor, linter],
}

agent = create_deep_agent(subagents=[research_agent, coder_agent])
最适合:特定领域专业能力、不同任务类型使用不同工具集。

Pattern 3: Pre-compiled Subagents

模式3:预编译子代理

python
from deepagents import CompiledSubAgent, create_deep_agent
python
from deepagents import CompiledSubAgent, create_deep_agent

Use existing LangGraph graph as subagent

Use existing LangGraph graph as subagent

custom_graph = create_react_agent(model=..., tools=...)
agent = create_deep_agent( subagents=[CompiledSubAgent( name="custom-workflow", description="Runs specialized workflow", runnable=custom_graph )] )

Best for: Reusing existing LangGraph graphs, complex custom workflows.
custom_graph = create_react_agent(model=..., tools=...)
agent = create_deep_agent( subagents=[CompiledSubAgent( name="custom-workflow", description="Runs specialized workflow", runnable=custom_graph )] )

最适合:复用现有LangGraph图、复杂自定义工作流。

Middleware Architecture

中间件架构

Built-in Middleware Stack

内置中间件栈

Deep Agents applies middleware in this order:
  1. TodoListMiddleware - Task planning with
    write_todos
    /
    read_todos
  2. FilesystemMiddleware - File ops:
    ls
    ,
    read_file
    ,
    write_file
    ,
    edit_file
    ,
    glob
    ,
    grep
    ,
    execute
  3. SubAgentMiddleware - Delegation via
    task
    tool
  4. SummarizationMiddleware - Auto-summarizes at ~85% context or 170k tokens
  5. AnthropicPromptCachingMiddleware - Caches system prompts (Anthropic only)
  6. PatchToolCallsMiddleware - Fixes dangling tool calls from interruptions
  7. HumanInTheLoopMiddleware - Pauses for approval (if
    interrupt_on
    configured)
Deep Agents 按以下顺序应用中间件:
  1. TodoListMiddleware - 通过
    write_todos
    /
    read_todos
    实现任务规划
  2. FilesystemMiddleware - 文件操作:
    ls
    read_file
    write_file
    edit_file
    glob
    grep
    execute
  3. SubAgentMiddleware - 通过
    task
    工具实现委托
  4. SummarizationMiddleware - 上下文占用约85%或达到170k tokens时自动摘要
  5. AnthropicPromptCachingMiddleware - 缓存系统提示词(仅支持Anthropic)
  6. PatchToolCallsMiddleware - 修复中断导致的未完成工具调用
  7. HumanInTheLoopMiddleware - 暂停等待审批(若配置了
    interrupt_on

Custom Middleware Placement

自定义中间件部署

python
from langchain.agents.middleware import AgentMiddleware

class MyMiddleware(AgentMiddleware):
    tools = [my_custom_tool]

    def transform_request(self, request):
        # Modify system prompt, inject context
        return request

    def transform_response(self, response):
        # Post-process, log, filter
        return response
python
from langchain.agents.middleware import AgentMiddleware

class MyMiddleware(AgentMiddleware):
    tools = [my_custom_tool]

    def transform_request(self, request):
        # Modify system prompt, inject context
        return request

    def transform_response(self, response):
        # Post-process, log, filter
        return response

Custom middleware added AFTER built-in stack

Custom middleware added AFTER built-in stack

agent = create_deep_agent(middleware=[MyMiddleware()])
undefined
agent = create_deep_agent(middleware=[MyMiddleware()])
undefined

Middleware vs Tools Decision

中间件与工具的选择决策

NeedUse MiddlewareUse Tools
Inject system prompt content
Add tools dynamically
Transform requests/responses
Standalone capability
User-invokable action
需求使用中间件使用工具
注入系统提示词内容
动态添加工具
转换请求/响应
独立功能
用户可调用操作

Subagent Middleware Inheritance

子代理中间件继承

Subagents receive their own middleware stack by default:
  • TodoListMiddleware
  • FilesystemMiddleware (shared backend)
  • SummarizationMiddleware
  • AnthropicPromptCachingMiddleware
  • PatchToolCallsMiddleware
Override with
default_middleware=[]
in SubAgentMiddleware or per-subagent
middleware
key.
子代理默认会继承独立的中间件栈:
  • TodoListMiddleware
  • FilesystemMiddleware (shared backend)
  • SummarizationMiddleware
  • AnthropicPromptCachingMiddleware
  • PatchToolCallsMiddleware
可通过SubAgentMiddleware中的
default_middleware=[]
或每个子代理的
middleware
参数覆盖默认配置。

Architecture Decision Checklist

架构决策检查清单

Before implementing:
  1. Is Deep Agents the right tool? (vs LangGraph directly, vs simpler agent)
  2. Backend strategy chosen?
    • Ephemeral only → StateBackend (default)
    • Need disk access → FilesystemBackend
    • Need cross-thread persistence → StoreBackend or CompositeBackend
  3. Subagent strategy defined?
    • Which tasks benefit from isolation?
    • Custom subagents with specialized tools/prompts?
    • Parallel execution opportunities identified?
  4. Human-in-the-loop points defined?
    • Which tools need approval?
    • Approval flow (approve/edit/reject)?
  5. Custom middleware needed?
    • System prompt injection?
    • Request/response transformation?
  6. Context management considered?
    • Long conversations → summarization triggers
    • Large file handling → use references
  7. Checkpointing strategy? (for persistence/resume)
实施前请确认:
  1. Deep Agents是否为合适的工具?(对比直接使用LangGraph或更简单的代理)
  2. 是否已选择后端策略?
    • 仅需临时存储 → StateBackend(默认)
    • 需要磁盘访问 → FilesystemBackend
    • 需要跨线程持久化 → StoreBackend或CompositeBackend
  3. 是否已定义子代理策略?
    • 哪些任务能从隔离执行中获益?
    • 是否需要带专用工具/提示词的自定义子代理?
    • 是否识别出并行执行的机会?
  4. 是否已定义人机协作节点?
    • 哪些工具需要审批?
    • 审批流程(批准/编辑/拒绝)?
  5. 是否需要自定义中间件?
    • 是否需要注入系统提示词?
    • 是否需要转换请求/响应?
  6. 是否已考虑上下文管理?
    • 长对话 → 摘要触发机制
    • 大文件处理 → 使用引用
  7. 是否已制定检查点策略?(用于持久化/恢复)