deepagents-architecture
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDeep 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:
以下场景考虑替代方案:
| Scenario | Alternative | Why |
|---|---|---|
| Single LLM call | Direct API call | Deep Agents overhead not justified |
| Simple RAG pipeline | LangChain LCEL | Simpler abstraction |
| Custom graph control flow | LangGraph directly | More flexibility |
| No file operations needed | | Lighter weight |
| Stateless tool use | Function calling | No middleware needed |
| 场景 | 替代方案 | 原因 |
|---|---|---|
| 单次LLM调用 | 直接API调用 | Deep Agents的开销得不偿失 |
| 简单RAG流水线 | LangChain LCEL | 更简洁的抽象 |
| 自定义图控制流 | 直接使用LangGraph | 灵活性更高 |
| 无需文件操作 | | 更轻量化 |
| 无状态工具调用 | 函数调用 | 无需中间件 |
Backend Selection
后端选择
Backend Comparison
后端对比
| Backend | Persistence | Use Case | Requires |
|---|---|---|---|
| Ephemeral (per-thread) | Working files, temp data | Nothing (default) |
| Disk | Local development, real files | |
| Cross-thread | User preferences, knowledge bases | LangGraph |
| Mixed | Hybrid memory patterns | Multiple backends |
| 后端 | 持久化特性 | 使用场景 | 依赖条件 |
|---|---|---|---|
| 临时存储(单线程) | 工作文件、临时数据 | 无(默认) |
| 磁盘存储 | 本地开发、真实文件操作 | |
| 跨线程共享 | 用户偏好、知识库 | LangGraph |
| 混合存储 | 混合记忆模式 | 多个后端 |
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_agentpython
from deepagents import CompiledSubAgent, create_deep_agentUse 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:
- TodoListMiddleware - Task planning with /
write_todosread_todos - FilesystemMiddleware - File ops: ,
ls,read_file,write_file,edit_file,glob,grepexecute - SubAgentMiddleware - Delegation via tool
task - SummarizationMiddleware - Auto-summarizes at ~85% context or 170k tokens
- AnthropicPromptCachingMiddleware - Caches system prompts (Anthropic only)
- PatchToolCallsMiddleware - Fixes dangling tool calls from interruptions
- HumanInTheLoopMiddleware - Pauses for approval (if configured)
interrupt_on
Deep Agents 按以下顺序应用中间件:
- TodoListMiddleware - 通过/
write_todos实现任务规划read_todos - FilesystemMiddleware - 文件操作:、
ls、read_file、write_file、edit_file、glob、grepexecute - SubAgentMiddleware - 通过工具实现委托
task - SummarizationMiddleware - 上下文占用约85%或达到170k tokens时自动摘要
- AnthropicPromptCachingMiddleware - 缓存系统提示词(仅支持Anthropic)
- PatchToolCallsMiddleware - 修复中断导致的未完成工具调用
- 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 responsepython
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 responseCustom middleware added AFTER built-in stack
Custom middleware added AFTER built-in stack
agent = create_deep_agent(middleware=[MyMiddleware()])
undefinedagent = create_deep_agent(middleware=[MyMiddleware()])
undefinedMiddleware vs Tools Decision
中间件与工具的选择决策
| Need | Use Middleware | Use 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 in SubAgentMiddleware or per-subagent key.
default_middleware=[]middleware子代理默认会继承独立的中间件栈:
- TodoListMiddleware
- FilesystemMiddleware (shared backend)
- SummarizationMiddleware
- AnthropicPromptCachingMiddleware
- PatchToolCallsMiddleware
可通过SubAgentMiddleware中的或每个子代理的参数覆盖默认配置。
default_middleware=[]middlewareArchitecture Decision Checklist
架构决策检查清单
Before implementing:
- Is Deep Agents the right tool? (vs LangGraph directly, vs simpler agent)
- Backend strategy chosen?
- Ephemeral only → StateBackend (default)
- Need disk access → FilesystemBackend
- Need cross-thread persistence → StoreBackend or CompositeBackend
- Subagent strategy defined?
- Which tasks benefit from isolation?
- Custom subagents with specialized tools/prompts?
- Parallel execution opportunities identified?
- Human-in-the-loop points defined?
- Which tools need approval?
- Approval flow (approve/edit/reject)?
- Custom middleware needed?
- System prompt injection?
- Request/response transformation?
- Context management considered?
- Long conversations → summarization triggers
- Large file handling → use references
- Checkpointing strategy? (for persistence/resume)
实施前请确认:
- Deep Agents是否为合适的工具?(对比直接使用LangGraph或更简单的代理)
- 是否已选择后端策略?
- 仅需临时存储 → StateBackend(默认)
- 需要磁盘访问 → FilesystemBackend
- 需要跨线程持久化 → StoreBackend或CompositeBackend
- 是否已定义子代理策略?
- 哪些任务能从隔离执行中获益?
- 是否需要带专用工具/提示词的自定义子代理?
- 是否识别出并行执行的机会?
- 是否已定义人机协作节点?
- 哪些工具需要审批?
- 审批流程(批准/编辑/拒绝)?
- 是否需要自定义中间件?
- 是否需要注入系统提示词?
- 是否需要转换请求/响应?
- 是否已考虑上下文管理?
- 长对话 → 摘要触发机制
- 大文件处理 → 使用引用
- 是否已制定检查点策略?(用于持久化/恢复)