主题
子智能体
了解如何使用子智能体来委派工作并保持上下文整洁
深度智能体可以创建子智能体来委派工作。你可以在 subagents 参数中指定自定义子智能体。子智能体可用于上下文隔离(保持主智能体的上下文整洁)以及提供专门的说明。
本页介绍同步子智能体,即主管会阻塞直到子智能体完成。对于长时间运行的任务、并行工作流,或需要中途干预和取消的情况,请参阅异步子智能体。
graph TB
Main[Main Agent] --> |task tool| Sub[Subagent]
Sub --> Research[Research]
Sub --> Code[Code]
Sub --> General[General]
Research --> |isolated work| Result[Final Result]
Code --> |isolated work| Result
General --> |isolated work| Result
Result --> Main
为什么要使用子智能体?
子智能体解决了上下文膨胀问题。当智能体使用输出量很大的工具(网络搜索、文件读取、数据库查询)时,上下文窗口会很快被中间结果填满。子智能体隔离了这些细节工作——主智能体只收到最终结果,而不是产生该结果的那几十次工具调用。
何时使用子智能体:
- ✅ 会使主智能体上下文变得杂乱的多步骤任务
- ✅ 需要自定义说明或工具的专门领域
- ✅ 需要不同模型能力的任务
- ✅ 当你希望让主智能体专注于高层协调时
何时不应使用子智能体:
- ❌ 简单的单步任务
- ❌ 当你需要保留中间上下文时
- ❌ 当开销超过收益时
配置
subagents 应为一个字典列表或 CompiledSubAgent 对象列表。有两种类型:
默认子智能体
除非你已经提供了一个同名的同步子智能体,否则 Deep Agents 会自动添加一个同步的 general-purpose 子智能体。
general-purpose 子智能体默认具有文件系统工具,并可以通过额外的工具/中间件进行自定义。
- 要替换它,请传入你自己的名为
general-purpose的子智能体。 - 要重命名或重新提示自动添加的版本,请在激活的 harness 配置上设置
general_purpose_subagent=GeneralPurposeSubagentProfile(...)。 - 要禁用它,请参阅下面的在没有子智能体的情况下运行。
在没有子智能体的情况下运行
要在没有 task 工具的情况下运行智能体,请做两件事:
- 在激活的 harness 配置上设置
general_purpose_subagent=GeneralPurposeSubagentProfile(enabled=False)。 - 在
create_deep_agent上通过subagents=不传入任何同步子智能体。
Deep Agents 仅在至少存在一个同步子智能体时才会附加 SubAgentMiddleware(以及 task 工具)。既没有默认的,也没有调用方提供的时,智能体将在没有委派的情况下运行。
异步子智能体不受影响——它们通过自己独立的中间件和工具流转,详见异步子智能体。
TIP
这里不要使用 excluded_middleware——SubAgentMiddleware 是必需的脚手架,列出它会引发 ValueError。受支持的途径是使用 general_purpose_subagent.enabled = False 开关。
自定义子智能体
你可以使用 subagents 参数定义具有特定工具的专门子智能体。例如,用作代码审查者、网络研究者或测试运行器。
对于大多数用例,将子智能体定义为字典(参见 SubAgent 字典)。对于复杂的工作流,使用 CompiledSubAgent:
SubAgent(基于字典)
将子智能体定义为符合 SubAgent 规范的字典,包含以下字段:
| 字段 | 类型 | 描述 |
|---|---|---|
name | str | 必填。子智能体的唯一标识符。主智能体在调用 task() 工具时使用此名称。子智能体名称会成为 AIMessage 和流式传输的元数据,有助于区分不同的智能体。 |
description | str | 必填。描述该子智能体做什么。要具体且面向行动。主智能体用它来决定何时委派。 |
system_prompt | str | 对 mode: "isolated"(默认值)必填。子智能体的说明。自定义的隔离子智能体必须定义自己的说明。请包含工具使用指引和输出格式要求。不从主智能体继承。对于 mode: "fork",除非你需要仅用于分支的补充说明,否则请省略此字段。请参阅分支子智能体。 |
mode | "isolated" | "fork" | 可选。上下文模式。默认为 "isolated",此时子智能体只能看到委派的任务。设置为 "fork" 则改为继承父级的对话和系统提示词。请参阅分支子智能体。 |
tools | list[Callable] | 可选。子智能体可以使用的工具。保持精简,只包含所需的内容。 默认从主智能体继承。指定时会完全覆盖继承的工具。 |
model | str | BaseChatModel | 可选。覆盖主智能体的模型。省略则使用主智能体的模型。 默认从主智能体继承。你可以传入模型标识符字符串(如 'openai:gpt-5.5',使用 'provider:model' 格式)或 LangChain 聊天模型对象(init_chat_model("gpt-5.5") 或 ChatOpenAI(model="gpt-5.5"))。 |
middleware | list[Middleware] | 可选。用于自定义行为、日志或限流的附加中间件。 不从主智能体继承。会合并到同步子智能体技术栈: .name 与某个默认值匹配的实例会就地替换它,其他任何内容则落在最后一个核心中间件条目之后、profile、提示词缓存和记忆之前。请参阅覆盖默认中间件实例。例如,在此处包含一个带 tools 允许列表的 FilesystemMiddleware 实例,以独立于主智能体限制子智能体的文件系统工具。有关更多信息,请参阅虚拟文件系统访问下的"限制文件系统工具"章节。 |
interrupt_on | dict[str, bool | InterruptOnConfig] | 可选。为特定工具配置人在回路。选项:True、False,或带 allowed_decisions 的 InterruptOnConfig。需要检查点器。默认从主智能体继承。子智能体的值会覆盖默认值。 |
skills | list[str] | 可选。技能来源路径。指定后,子智能体会从这些目录加载技能(例如 ["/skills/researcher/"],一个子目录即技能的容器)。这让子智能体可以拥有与主智能体不同的技能集。不从主智能体继承。只有通用子智能体继承主智能体的技能。当子智能体拥有技能时,它会运行自己独立的 SkillsMiddleware 实例。技能状态完全隔离——子智能体已加载的技能对父级不可见,反之亦然。 |
response_format | ResponseFormat | 可选。子智能体的结构化输出 schema。设置后,父级会以 JSON 形式接收子智能体的结果,而不是自由格式文本。接受 Pydantic 模型、ToolStrategy(...)、ProviderStrategy(...) 或原始 schema 类型。请参阅结构化输出。 |
permissions | list[FilesystemPermission] | 可选。子智能体的文件系统权限规则。设置后会完全替换父智能体的权限。 默认从主智能体继承。 |
CompiledSubAgent
对于复杂的工作流,使用预构建的 LangGraph 图作为 CompiledSubAgent:
| 字段 | 类型 | 描述 |
|---|---|---|
name | str | 必填。子智能体的唯一标识符。子智能体名称会成为 AIMessage 和流式传输的元数据,有助于区分不同的智能体。 |
description | str | 必填。该子智能体做什么。 |
runnable | Runnable | 必填。一个已编译的 LangGraph 图(必须先调用 .compile())。 |
mode | "isolated" | "fork" | 可选。默认为 "isolated"。设置为 "fork" 以继承父级的消息历史。无论哪种方式,已编译的图都保留自己的系统提示词。请参阅分支子智能体。 |
使用 SubAgent
python
import os
from typing import Literal
from deepagents import create_deep_agent
from tavily import TavilyClient
tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
def internet_search(
query: str,
max_results: int = 5,
topic: Literal["general", "news", "finance"] = "general",
include_raw_content: bool = False,
):
"""Run a web search"""
return tavily_client.search(
query,
max_results=max_results,
include_raw_content=include_raw_content,
topic=topic,
)
research_subagent = {
"name": "research-agent",
"description": "Used to research more in depth questions",
"system_prompt": "You are a great researcher",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Optional override, defaults to main agent model
}
subagents = [research_subagent]
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
subagents=subagents,
)使用 CompiledSubAgent
对于更复杂的用例,你可以使用 CompiledSubAgent 提供自定义子智能体。 你可以使用 LangChain 的 create_agent 创建自定义子智能体,或使用图 API 创建自定义 LangGraph 图。
如果你正在创建自定义 LangGraph 图,请确保该图具有名为 "messages" 的状态键:
python
from deepagents import CompiledSubAgent, create_deep_agent
from langchain.agents import create_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
research_instructions = "You are a research coordinator."
your_model = "openai:gpt-5.5"
specialized_tools: list = []
# Create a custom agent graph
custom_graph = create_agent(
model=your_model,
tools=specialized_tools,
system_prompt="You are a specialized agent for data analysis...",
)
# Use it as a custom subagent
custom_subagent = CompiledSubAgent(
name="data-analyzer",
description="Specialized agent for complex data analysis tasks",
runnable=custom_graph,
)
subagents = [custom_subagent]
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
tools=[internet_search],
system_prompt=research_instructions,
subagents=subagents,
)python
from deepagents import CompiledSubAgent, create_deep_agent
from langchain.agents import create_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
research_instructions = "You are a research coordinator."
your_model = "openai:gpt-5.5"
specialized_tools: list = []
# Create a custom agent graph
custom_graph = create_agent(
model=your_model,
tools=specialized_tools,
system_prompt="You are a specialized agent for data analysis...",
)
# Use it as a custom subagent
custom_subagent = CompiledSubAgent(
name="data-analyzer",
description="Specialized agent for complex data analysis tasks",
runnable=custom_graph,
)
subagents = [custom_subagent]
agent = create_deep_agent(
model="openai:gpt-5.5",
tools=[internet_search],
system_prompt=research_instructions,
subagents=subagents,
)python
from deepagents import CompiledSubAgent, create_deep_agent
from langchain.agents import create_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
research_instructions = "You are a research coordinator."
your_model = "openai:gpt-5.5"
specialized_tools: list = []
# Create a custom agent graph
custom_graph = create_agent(
model=your_model,
tools=specialized_tools,
system_prompt="You are a specialized agent for data analysis...",
)
# Use it as a custom subagent
custom_subagent = CompiledSubAgent(
name="data-analyzer",
description="Specialized agent for complex data analysis tasks",
runnable=custom_graph,
)
subagents = [custom_subagent]
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
tools=[internet_search],
system_prompt=research_instructions,
subagents=subagents,
)python
from deepagents import CompiledSubAgent, create_deep_agent
from langchain.agents import create_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
research_instructions = "You are a research coordinator."
your_model = "openai:gpt-5.5"
specialized_tools: list = []
# Create a custom agent graph
custom_graph = create_agent(
model=your_model,
tools=specialized_tools,
system_prompt="You are a specialized agent for data analysis...",
)
# Use it as a custom subagent
custom_subagent = CompiledSubAgent(
name="data-analyzer",
description="Specialized agent for complex data analysis tasks",
runnable=custom_graph,
)
subagents = [custom_subagent]
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
tools=[internet_search],
system_prompt=research_instructions,
subagents=subagents,
)python
from deepagents import CompiledSubAgent, create_deep_agent
from langchain.agents import create_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
research_instructions = "You are a research coordinator."
your_model = "openai:gpt-5.5"
specialized_tools: list = []
# Create a custom agent graph
custom_graph = create_agent(
model=your_model,
tools=specialized_tools,
system_prompt="You are a specialized agent for data analysis...",
)
# Use it as a custom subagent
custom_subagent = CompiledSubAgent(
name="data-analyzer",
description="Specialized agent for complex data analysis tasks",
runnable=custom_graph,
)
subagents = [custom_subagent]
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
tools=[internet_search],
system_prompt=research_instructions,
subagents=subagents,
)python
from deepagents import CompiledSubAgent, create_deep_agent
from langchain.agents import create_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
research_instructions = "You are a research coordinator."
your_model = "openai:gpt-5.5"
specialized_tools: list = []
# Create a custom agent graph
custom_graph = create_agent(
model=your_model,
tools=specialized_tools,
system_prompt="You are a specialized agent for data analysis...",
)
# Use it as a custom subagent
custom_subagent = CompiledSubAgent(
name="data-analyzer",
description="Specialized agent for complex data analysis tasks",
runnable=custom_graph,
)
subagents = [custom_subagent]
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
tools=[internet_search],
system_prompt=research_instructions,
subagents=subagents,
)python
from deepagents import CompiledSubAgent, create_deep_agent
from langchain.agents import create_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
research_instructions = "You are a research coordinator."
your_model = "openai:gpt-5.5"
specialized_tools: list = []
# Create a custom agent graph
custom_graph = create_agent(
model=your_model,
tools=specialized_tools,
system_prompt="You are a specialized agent for data analysis...",
)
# Use it as a custom subagent
custom_subagent = CompiledSubAgent(
name="data-analyzer",
description="Specialized agent for complex data analysis tasks",
runnable=custom_graph,
)
subagents = [custom_subagent]
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
tools=[internet_search],
system_prompt=research_instructions,
subagents=subagents,
)分支子智能体
默认情况下,子智能体以 mode: "isolated" 运行:它只能看到你给它的任务描述,并且对导致此次委派的对话没有记忆。而分支子智能体(mode: "fork")则改为继承父级完整的对话历史和确切的系统提示词。
当子智能体的任务是继续父级已经启动的工作时,请使用分支子智能体,例如一个接手父级已诊断出的修复的工作智能体,或一个为事件调查起草事后复盘的子智能体。由于分支是你设置在子智能体本身上的模式,因此这是你在定义它时做出的决定。
%%{init: {"flowchart": {"subGraphTitleMargin": {"top": 12, "bottom": 4}}}}%%
graph TD
Message["'Review PR #482'"]
Analysis["Parent already found:<br/>tokens logged in plaintext,<br/>no expiry check on refresh"]
Delegate["Delegate: draft comments<br/>for the issues found"]
Message --> Analysis --> Delegate
subgraph Isolated["`**Isolated subagent**`"]
IOut["Sees only the task description<br/>starts from nothing, re-reviews the diff"]
end
subgraph Forked["`**Forked subagent**`"]
FOut["Sees parent history + continuation preamble<br/>already knows the issues, writes comments directly"]
end
Delegate -->|task description only| Isolated
Delegate -->|parent history + continuation preamble| Forked
classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:2px,color:#030710
classDef output fill:#F6FFDB,stroke:#6E8900,stroke-width:2px,color:#2E3900
class Message,Analysis,Delegate process
class IOut,FOut output
NOTE
子智能体分支需要 deepagents>=0.7.13。它处于测试版;API 和行为可能在不同版本之间发生变化。
配置分支子智能体
在 SubAgent 上设置 mode: "fork"(默认值为 mode: "isolated")。所有 SubAgent 字段都可用: name、description、tools、model、middleware、interrupt_on、permissions 和 response_format。
如果提供 skills 会被拒绝。system_prompt 是允许的,它会作为补充说明追加到父级继承的提示词中,但这样做通常会破坏提示词缓存,因此除非你有特定需求需要仅供分支使用的说明,否则请保持未设置。
python
from deepagents import create_deep_agent
def read_diff(path: str) -> str:
"""Read a file's diff."""
return f"diff for {path}"
comment_writer = {
"name": "comment-writer",
"description": "Continues an in-progress PR review and drafts review comments",
"mode": "fork",
"tools": [read_diff],
}
agent = create_deep_agent(
model="google_genai:gemini-3.7-flash",
tools=[read_diff],
subagents=[comment_writer],
)
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": "Review PR #482 and hand it off to comment-writer to draft comments for the issues found",
}
]
}
)View example trace
打开本示例的一个公开 LangSmith 运行记录。
工作原理
分支不会获得全新的任务描述。它得到的是父级自己的对话,只有一处变化:委派给它的那次末尾调用会被丢弃,并替换为一段简短的引言,标明上方的消息是延续而非新请求。当分支完成时,它的答案会作为普通工具结果返回,父级会从它中断的地方继续。
python
# What the parent has, right before delegating
[
HumanMessage("Review the changes in PR #482"),
AIMessage("", tool_calls=[{"name": "read_diff", "args": {"path": "src/auth/session.py"}}]),
ToolMessage("- session tokens are logged in plaintext\n- no expiry check on refresh", tool_call_id="1"),
AIMessage("Found two issues: session tokens are logged in plaintext, and there's no expiry check on refresh."),
HumanMessage("Good catch. Draft review comments for those."),
AIMessage("", tool_calls=[{"name": "task", "args": {"subagent_type": "comment-writer", "description": "Draft review comments for the two issues found above."}}]),
]
# What the fork actually sees
[
HumanMessage("Review the changes in PR #482"),
AIMessage("", tool_calls=[{"name": "read_diff", "args": {"path": "src/auth/session.py"}}]),
ToolMessage("- session tokens are logged in plaintext\n- no expiry check on refresh", tool_call_id="1"),
AIMessage("Found two issues: session tokens are logged in plaintext, and there's no expiry check on refresh."),
HumanMessage("Good catch. Draft review comments for those."),
HumanMessage("Continuing as the subagent that was just invoked. Draft review comments for the two issues found above."),
]复用父级确切的前缀也意味着分支可以复用父级的提示词缓存,而不是冷启动,尽管与父级不同的工具使用仍会未命中缓存。
CompiledSubAgent 也支持 mode: "fork",不过由于图已经构建,它会保留自己的系统提示词。
何时使用分支
从以下维度比较隔离模式和分支模式:
| 维度 | 隔离(默认) | 分支 |
|---|---|---|
| 上下文 | 仅你传入的任务描述 | 父级完整的对话历史和系统提示词 |
| 系统提示词和技能 | 你在子智能体上设置它们 | 技能不可设置;系统提示词会追加到父级的提示词上(破坏缓存,因此通常保持未设置) |
| 调用其他子智能体 | 可以使用 task 工具 | 不能使用 task;必须自己完成工作 |
| 最适用于 | 需要较少先前上下文的聚焦工作 | 继续父级已经启动的调查 |
动态子智能体
默认情况下,主智能体通过 task 工具调用来委派给子智能体(它可以在单轮中发出多个调用来并行运行它们)。附加解释器后,智能体可以改为从代码中派发子智能体——使用循环、分支和并行批次将工作扇出到多个条目上,并以编程方式综合结果。这称为动态子智能体。
当工作跨越许多独立单元(审查目录中的每个文件、对一批工单进行分诊)、需要多个视角,或受益于递归分析时,请使用动态子智能体。
WARNING
动态子智能体使用解释器运行时,它处于测试版。API 和生命周期行为可能在不同版本之间发生变化。
启用动态子智能体
一旦智能体同时拥有子智能体和解释器中间件,动态子智能体就会可用。安装 QuickJS 解释器包,然后将 CodeInterpreterMiddleware 添加到你的智能体中。
bash
pip install -U "deepagents[quickjs]"bash
uv add "deepagents[quickjs]"python
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
subagents=[{
"name": "reviewer",
"description": "Reviews code for security issues, citing lines and severity",
"system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware=[CodeInterpreterMiddleware()],
)python
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
agent = create_deep_agent(
model="openai:gpt-5.5",
subagents=[{
"name": "reviewer",
"description": "Reviews code for security issues, citing lines and severity",
"system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware=[CodeInterpreterMiddleware()],
)python
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
subagents=[{
"name": "reviewer",
"description": "Reviews code for security issues, citing lines and severity",
"system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware=[CodeInterpreterMiddleware()],
)python
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
subagents=[{
"name": "reviewer",
"description": "Reviews code for security issues, citing lines and severity",
"system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware=[CodeInterpreterMiddleware()],
)python
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
subagents=[{
"name": "reviewer",
"description": "Reviews code for security issues, citing lines and severity",
"system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware=[CodeInterpreterMiddleware()],
)python
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
subagents=[{
"name": "reviewer",
"description": "Reviews code for security issues, citing lines and severity",
"system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware=[CodeInterpreterMiddleware()],
)python
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
subagents=[{
"name": "reviewer",
"description": "Reviews code for security issues, citing lines and severity",
"system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware=[CodeInterpreterMiddleware()],
)NOTE
只要智能体拥有子智能体和解释器中间件,动态子智能体派发就会默认开启。传入 CodeInterpreterMiddleware(subagents=False) 以要求通过普通的 task 工具路径进行派发。解释器需要 langchain-quickjs>=0.2.0 和 Python 3.11 或更高版本。
触发动态编排
动态派发是隐式的:智能体根据任务的形态决定是否从代码中扇出工作,而不是通过每次调用的标志。
TIP
“workflow” 这个词是一个有用的触发器。 内置的解释器系统提示词会将 “workflow” 视为一种信号,表示应通过解释器来组织工作——从代码中用 task() 派发子智能体。将请求表述为 “workflow” 是你可以主动拉动的一个杠杆,用来选择动态编排:当你想让智能体从代码中扇出工作时就包含它。对于单次直接委派,请改为平实地表述请求。
例如,将请求表述为 “workflow” 会选择从代码中扇出:
python
result = agent.invoke({
"messages": [{"role": "user", "content": "Run a workflow that reviews every file in src/routes/ and summarizes the top risks."}]
})有关配置、高级编排模式和安全注意事项,请参阅动态子智能体。
与编码智能体一起使用
尝试动态子智能体最快的方式是使用 dcode,它是构建在 Deep Agent 之上的 LangChain 终端编码智能体。它自带已启用的代码解释器,因此动态子智能体开箱即用,无需任何配置。
安装 dcode:
bash
curl -LsSf https://langch.in/dcode | bash运行它:
bash
dcode要触发动态子智能体,请要求一个 “workflow”。智能体不会自己苦干这项工作,也不会通过其原生 task 工具来管理扇出,而是会编写一个编排脚本,调用内置的 task() 全局函数并在代码解释器中运行它。例如:“运行一个工作流来审查 src/ 中的每个文件是否存在 SQL 注入。”
随着子智能体被派生,dcode 会在动态子智能体面板中实时显示它们,并按派发阶段分组。

dcode 是尝试这一功能最快的方式,但你也可以通过 ACP 在你选择的编码智能体中使用动态子智能体(例如 Zed)。
流式传输
Deep Agents 支持从协调器和每个被委派的子智能体流式传输更新。
使用 stream_events 获取类型化投影——为子智能体、消息、工具调用和值提供独立的迭代器——这样你就可以独立消费每一个。
流式输出子智能体进度
最简单的模式是迭代 stream.subagents,以在每个被委派任务启动、运行和完成时进行追踪。每个子智能体句柄都暴露 .name、.messages、.tool_calls 和 .output。
python
from deepagents import (
create_deep_agent
)
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
system_prompt=(
"You are a project coordinator with no research knowledge. "
"For every user request, you must call the task() tool with "
"subagent_type set to research-agent. Never answer research "
"questions yourself."
),
subagents=[
{
"name": "research-agent",
"description": (
"Delegate research to this subagent. Give one topic at a time."
),
"system_prompt": (
"You are a great researcher. Return a brief summary."
),
},
],
name="main-agent",
)
if __name__ == "__main__":
stream = agent.stream_events(
{
"messages": [
{
"role": "user",
"content": "Research one recent advance in quantum computing.",
}
]
},
version="v3",
)
coordinator_messages: list[str] = []
subagent_handles = []
for name, item in stream.interleave("messages", "subagents"):
if name == "messages":
print("[coordinator]", item.text)
coordinator_messages.append(item.text)
else:
print(f"[{item.name}] started")
subagent_handles.append(item)
for message in item.messages:
print(f"[{item.name}]", message.text)
print(f"[{item.name}] status: {item.status}")python
from deepagents import (
create_deep_agent
)
agent = create_deep_agent(
model="openai:gpt-5.5",
system_prompt=(
"You are a project coordinator with no research knowledge. "
"For every user request, you must call the task() tool with "
"subagent_type set to research-agent. Never answer research "
"questions yourself."
),
subagents=[
{
"name": "research-agent",
"description": (
"Delegate research to this subagent. Give one topic at a time."
),
"system_prompt": (
"You are a great researcher. Return a brief summary."
),
},
],
name="main-agent",
)
if __name__ == "__main__":
stream = agent.stream_events(
{
"messages": [
{
"role": "user",
"content": "Research one recent advance in quantum computing.",
}
]
},
version="v3",
)
coordinator_messages: list[str] = []
subagent_handles = []
for name, item in stream.interleave("messages", "subagents"):
if name == "messages":
print("[coordinator]", item.text)
coordinator_messages.append(item.text)
else:
print(f"[{item.name}] started")
subagent_handles.append(item)
for message in item.messages:
print(f"[{item.name}]", message.text)
print(f"[{item.name}] status: {item.status}")python
from deepagents import (
create_deep_agent
)
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
system_prompt=(
"You are a project coordinator with no research knowledge. "
"For every user request, you must call the task() tool with "
"subagent_type set to research-agent. Never answer research "
"questions yourself."
),
subagents=[
{
"name": "research-agent",
"description": (
"Delegate research to this subagent. Give one topic at a time."
),
"system_prompt": (
"You are a great researcher. Return a brief summary."
),
},
],
name="main-agent",
)
if __name__ == "__main__":
stream = agent.stream_events(
{
"messages": [
{
"role": "user",
"content": "Research one recent advance in quantum computing.",
}
]
},
version="v3",
)
coordinator_messages: list[str] = []
subagent_handles = []
for name, item in stream.interleave("messages", "subagents"):
if name == "messages":
print("[coordinator]", item.text)
coordinator_messages.append(item.text)
else:
print(f"[{item.name}] started")
subagent_handles.append(item)
for message in item.messages:
print(f"[{item.name}]", message.text)
print(f"[{item.name}] status: {item.status}")python
from deepagents import (
create_deep_agent
)
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
system_prompt=(
"You are a project coordinator with no research knowledge. "
"For every user request, you must call the task() tool with "
"subagent_type set to research-agent. Never answer research "
"questions yourself."
),
subagents=[
{
"name": "research-agent",
"description": (
"Delegate research to this subagent. Give one topic at a time."
),
"system_prompt": (
"You are a great researcher. Return a brief summary."
),
},
],
name="main-agent",
)
if __name__ == "__main__":
stream = agent.stream_events(
{
"messages": [
{
"role": "user",
"content": "Research one recent advance in quantum computing.",
}
]
},
version="v3",
)
coordinator_messages: list[str] = []
subagent_handles = []
for name, item in stream.interleave("messages", "subagents"):
if name == "messages":
print("[coordinator]", item.text)
coordinator_messages.append(item.text)
else:
print(f"[{item.name}] started")
subagent_handles.append(item)
for message in item.messages:
print(f"[{item.name}]", message.text)
print(f"[{item.name}] status: {item.status}")python
from deepagents import (
create_deep_agent
)
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
system_prompt=(
"You are a project coordinator with no research knowledge. "
"For every user request, you must call the task() tool with "
"subagent_type set to research-agent. Never answer research "
"questions yourself."
),
subagents=[
{
"name": "research-agent",
"description": (
"Delegate research to this subagent. Give one topic at a time."
),
"system_prompt": (
"You are a great researcher. Return a brief summary."
),
},
],
name="main-agent",
)
if __name__ == "__main__":
stream = agent.stream_events(
{
"messages": [
{
"role": "user",
"content": "Research one recent advance in quantum computing.",
}
]
},
version="v3",
)
coordinator_messages: list[str] = []
subagent_handles = []
for name, item in stream.interleave("messages", "subagents"):
if name == "messages":
print("[coordinator]", item.text)
coordinator_messages.append(item.text)
else:
print(f"[{item.name}] started")
subagent_handles.append(item)
for message in item.messages:
print(f"[{item.name}]", message.text)
print(f"[{item.name}] status: {item.status}")python
from deepagents import (
create_deep_agent
)
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
system_prompt=(
"You are a project coordinator with no research knowledge. "
"For every user request, you must call the task() tool with "
"subagent_type set to research-agent. Never answer research "
"questions yourself."
),
subagents=[
{
"name": "research-agent",
"description": (
"Delegate research to this subagent. Give one topic at a time."
),
"system_prompt": (
"You are a great researcher. Return a brief summary."
),
},
],
name="main-agent",
)
if __name__ == "__main__":
stream = agent.stream_events(
{
"messages": [
{
"role": "user",
"content": "Research one recent advance in quantum computing.",
}
]
},
version="v3",
)
coordinator_messages: list[str] = []
subagent_handles = []
for name, item in stream.interleave("messages", "subagents"):
if name == "messages":
print("[coordinator]", item.text)
coordinator_messages.append(item.text)
else:
print(f"[{item.name}] started")
subagent_handles.append(item)
for message in item.messages:
print(f"[{item.name}]", message.text)
print(f"[{item.name}] status: {item.status}")python
from deepagents import (
create_deep_agent
)
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
system_prompt=(
"You are a project coordinator with no research knowledge. "
"For every user request, you must call the task() tool with "
"subagent_type set to research-agent. Never answer research "
"questions yourself."
),
subagents=[
{
"name": "research-agent",
"description": (
"Delegate research to this subagent. Give one topic at a time."
),
"system_prompt": (
"You are a great researcher. Return a brief summary."
),
},
],
name="main-agent",
)
if __name__ == "__main__":
stream = agent.stream_events(
{
"messages": [
{
"role": "user",
"content": "Research one recent advance in quantum computing.",
}
]
},
version="v3",
)
coordinator_messages: list[str] = []
subagent_handles = []
for name, item in stream.interleave("messages", "subagents"):
if name == "messages":
print("[coordinator]", item.text)
coordinator_messages.append(item.text)
else:
print(f"[{item.name}] started")
subagent_handles.append(item)
for message in item.messages:
print(f"[{item.name}]", message.text)
print(f"[{item.name}] status: {item.status}")View example trace
打开本示例的一个公开 LangSmith 运行记录。
LangSmith 追踪
当你的深度智能体运行时,由子智能体或协调器执行的所有运行都会在其元数据中的 lc_agent_name 键下带有智能体名称——例如 {'lc_agent_name': 'research-agent'}。这让你可以在 LangSmith 中按子智能体识别和筛选运行。

TIP
在 LangSmith 中打开该运行,以将协调器追踪与每个子智能体运行进行比较。按照可观测性快速入门进行设置。我们还建议你设置 LangSmith Engine,它会监控你的追踪、检测问题并提出修复建议。
在 LangSmith 中按子智能体筛选
由于每个子智能体的 name 都会写入它产生的每次运行的 lc_agent_name 元数据键,因此你可以使用 LangSmith 的元数据筛选来隔离来自某个特定子智能体的所有运行——这对于调试、监控或随时间比较子智能体行为很有用。
在 LangSmith UI 中筛选
- 在 LangSmith 中打开你的追踪项目。
- 在 Tracing project 页面将视图切换到 Runs,以查看各个 span。
- 点击 Add filter 并选择 Metadata。
- 将 Key 设为
lc_agent_name,将 Value 设为子智能体名称,例如coordinator。

这只会显示该子智能体产生的运行。你可以将筛选器保存为命名视图以便复用。有关筛选选项的完整参考,请参阅 Filter traces。
使用 SDK 以编程方式筛选
使用 LangSmith 筛选查询语言中的 has 比较器,按元数据键值对匹配运行:
python
from langsmith import Client
client = Client()
runs = client.list_runs(
project_name="<your-project>",
filter='has(metadata, \'{"lc_agent_name": "research-agent"}\')',
)
for run in runs:
print(run.name, run.start_time, run.status)要获取来自任意命名子智能体的运行(排除主智能体),请筛选出完全具有 lc_agent_name 键的运行:
python
runs = client.list_runs(
project_name="<your-project>",
filter="has(metadata, 'lc_agent_name')",
)有关筛选查询语言的完整参考,请参阅 Trace query syntax。
结构化输出
子智能体支持结构化输出,因此父智能体收到的是可预测、可解析的 JSON,而不是自由形式的文本。
NOTE
子智能体的结构化输出需要 deepagents>=0.5.3。
在子智能体配置上传入 response_format。当子智能体完成时,其结构化响应会被 JSON 序列化,并作为 ToolMessage 内容返回给父智能体。该 schema 接受 create_agent 所支持的任何内容:Pydantic 模型、ToolStrategy(...)、ProviderStrategy(...) 或原始 schema 类型。
python
import asyncio
from pydantic import BaseModel, Field
from deepagents import create_deep_agent
def web_search(query: str) -> str:
"""Search the web."""
return f"web results for {query}"
class ResearchFindings(BaseModel):
"""Structured findings from a research task."""
summary: str = Field(description="Summary of findings")
confidence: float = Field(description="Confidence score from 0 to 1")
sources: list[str] = Field(description="List of source URLs")
research_subagent = {
"name": "researcher",
"description": "Researches topics and returns structured findings",
"system_prompt": "Research the given topic thoroughly. Return your findings.",
"tools": [web_search],
"response_format": ResearchFindings,
}
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
subagents=[research_subagent],
)
async def main():
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Research recent advances in quantum computing"}]}
)
return result
result = asyncio.run(main())
# The parent's ToolMessage contains JSON-serialized structured data:
# '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'python
import asyncio
from pydantic import BaseModel, Field
from deepagents import create_deep_agent
def web_search(query: str) -> str:
"""Search the web."""
return f"web results for {query}"
class ResearchFindings(BaseModel):
"""Structured findings from a research task."""
summary: str = Field(description="Summary of findings")
confidence: float = Field(description="Confidence score from 0 to 1")
sources: list[str] = Field(description="List of source URLs")
research_subagent = {
"name": "researcher",
"description": "Researches topics and returns structured findings",
"system_prompt": "Research the given topic thoroughly. Return your findings.",
"tools": [web_search],
"response_format": ResearchFindings,
}
agent = create_deep_agent(
model="openai:gpt-5.5",
subagents=[research_subagent],
)
async def main():
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Research recent advances in quantum computing"}]}
)
return result
result = asyncio.run(main())
# The parent's ToolMessage contains JSON-serialized structured data:
# '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'python
import asyncio
from pydantic import BaseModel, Field
from deepagents import create_deep_agent
def web_search(query: str) -> str:
"""Search the web."""
return f"web results for {query}"
class ResearchFindings(BaseModel):
"""Structured findings from a research task."""
summary: str = Field(description="Summary of findings")
confidence: float = Field(description="Confidence score from 0 to 1")
sources: list[str] = Field(description="List of source URLs")
research_subagent = {
"name": "researcher",
"description": "Researches topics and returns structured findings",
"system_prompt": "Research the given topic thoroughly. Return your findings.",
"tools": [web_search],
"response_format": ResearchFindings,
}
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
subagents=[research_subagent],
)
async def main():
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Research recent advances in quantum computing"}]}
)
return result
result = asyncio.run(main())
# The parent's ToolMessage contains JSON-serialized structured data:
# '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'python
import asyncio
from pydantic import BaseModel, Field
from deepagents import create_deep_agent
def web_search(query: str) -> str:
"""Search the web."""
return f"web results for {query}"
class ResearchFindings(BaseModel):
"""Structured findings from a research task."""
summary: str = Field(description="Summary of findings")
confidence: float = Field(description="Confidence score from 0 to 1")
sources: list[str] = Field(description="List of source URLs")
research_subagent = {
"name": "researcher",
"description": "Researches topics and returns structured findings",
"system_prompt": "Research the given topic thoroughly. Return your findings.",
"tools": [web_search],
"response_format": ResearchFindings,
}
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
subagents=[research_subagent],
)
async def main():
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Research recent advances in quantum computing"}]}
)
return result
result = asyncio.run(main())
# The parent's ToolMessage contains JSON-serialized structured data:
# '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'python
import asyncio
from pydantic import BaseModel, Field
from deepagents import create_deep_agent
def web_search(query: str) -> str:
"""Search the web."""
return f"web results for {query}"
class ResearchFindings(BaseModel):
"""Structured findings from a research task."""
summary: str = Field(description="Summary of findings")
confidence: float = Field(description="Confidence score from 0 to 1")
sources: list[str] = Field(description="List of source URLs")
research_subagent = {
"name": "researcher",
"description": "Researches topics and returns structured findings",
"system_prompt": "Research the given topic thoroughly. Return your findings.",
"tools": [web_search],
"response_format": ResearchFindings,
}
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
subagents=[research_subagent],
)
async def main():
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Research recent advances in quantum computing"}]}
)
return result
result = asyncio.run(main())
# The parent's ToolMessage contains JSON-serialized structured data:
# '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'python
import asyncio
from pydantic import BaseModel, Field
from deepagents import create_deep_agent
def web_search(query: str) -> str:
"""Search the web."""
return f"web results for {query}"
class ResearchFindings(BaseModel):
"""Structured findings from a research task."""
summary: str = Field(description="Summary of findings")
confidence: float = Field(description="Confidence score from 0 to 1")
sources: list[str] = Field(description="List of source URLs")
research_subagent = {
"name": "researcher",
"description": "Researches topics and returns structured findings",
"system_prompt": "Research the given topic thoroughly. Return your findings.",
"tools": [web_search],
"response_format": ResearchFindings,
}
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
subagents=[research_subagent],
)
async def main():
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Research recent advances in quantum computing"}]}
)
return result
result = asyncio.run(main())
# The parent's ToolMessage contains JSON-serialized structured data:
# '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'python
import asyncio
from pydantic import BaseModel, Field
from deepagents import create_deep_agent
def web_search(query: str) -> str:
"""Search the web."""
return f"web results for {query}"
class ResearchFindings(BaseModel):
"""Structured findings from a research task."""
summary: str = Field(description="Summary of findings")
confidence: float = Field(description="Confidence score from 0 to 1")
sources: list[str] = Field(description="List of source URLs")
research_subagent = {
"name": "researcher",
"description": "Researches topics and returns structured findings",
"system_prompt": "Research the given topic thoroughly. Return your findings.",
"tools": [web_search],
"response_format": ResearchFindings,
}
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
subagents=[research_subagent],
)
async def main():
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "Research recent advances in quantum computing"}]}
)
return result
result = asyncio.run(main())
# The parent's ToolMessage contains JSON-serialized structured data:
# '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'若不使用 response_format,父智能体会按原样收到子智能体的最后一条消息文本。若使用它,父智能体总能得到符合 schema 的有效 JSON,这在父智能体需要以编程方式处理结果或将其传递给下游工具时很有用。
有关 schema 类型和策略(工具调用与原生服务商)的完整细节,请参阅 Structured output。
通用子智能体
除了任何用户定义的子智能体外,每个深度智能体在任何时候都可以访问一个 general-purpose 子智能体。该子智能体:
- 使用自己的默认系统提示词并应用了 profile 覆盖层
- 可访问所有相同的工具
- 使用相同的模型(除非被覆盖)
- 从主智能体继承技能(在配置了技能时)
覆盖通用子智能体
在你的 subagents 列表中包含一个 name="general-purpose" 的子智能体即可替换默认值。用它来为通用子智能体配置不同的模型、工具或系统提示词:
python
from deepagents import create_deep_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
# Main agent uses Gemini; general-purpose subagent uses GPT
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
tools=[internet_search],
subagents=[
{
"name": "general-purpose",
"description": "General-purpose agent for research and multi-step tasks",
"system_prompt": "You are a general-purpose assistant.",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Different model for delegated tasks
},
],
)python
from deepagents import create_deep_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
# Main agent uses Gemini; general-purpose subagent uses GPT
agent = create_deep_agent(
model="openai:gpt-5.5",
tools=[internet_search],
subagents=[
{
"name": "general-purpose",
"description": "General-purpose agent for research and multi-step tasks",
"system_prompt": "You are a general-purpose assistant.",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Different model for delegated tasks
},
],
)python
from deepagents import create_deep_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
# Main agent uses Gemini; general-purpose subagent uses GPT
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
tools=[internet_search],
subagents=[
{
"name": "general-purpose",
"description": "General-purpose agent for research and multi-step tasks",
"system_prompt": "You are a general-purpose assistant.",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Different model for delegated tasks
},
],
)python
from deepagents import create_deep_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
# Main agent uses Gemini; general-purpose subagent uses GPT
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
tools=[internet_search],
subagents=[
{
"name": "general-purpose",
"description": "General-purpose agent for research and multi-step tasks",
"system_prompt": "You are a general-purpose assistant.",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Different model for delegated tasks
},
],
)python
from deepagents import create_deep_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
# Main agent uses Gemini; general-purpose subagent uses GPT
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
tools=[internet_search],
subagents=[
{
"name": "general-purpose",
"description": "General-purpose agent for research and multi-step tasks",
"system_prompt": "You are a general-purpose assistant.",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Different model for delegated tasks
},
],
)python
from deepagents import create_deep_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
# Main agent uses Gemini; general-purpose subagent uses GPT
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
tools=[internet_search],
subagents=[
{
"name": "general-purpose",
"description": "General-purpose agent for research and multi-step tasks",
"system_prompt": "You are a general-purpose assistant.",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Different model for delegated tasks
},
],
)python
from deepagents import create_deep_agent
def internet_search(query: str) -> str:
"""Run a web search."""
return f"search results for {query}"
# Main agent uses Gemini; general-purpose subagent uses GPT
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
tools=[internet_search],
subagents=[
{
"name": "general-purpose",
"description": "General-purpose agent for research and multi-step tasks",
"system_prompt": "You are a general-purpose assistant.",
"tools": [internet_search],
"model": "openai:gpt-5.5", # Different model for delegated tasks
},
],
)当你为子智能体提供 general-purpose 名称时,不会添加默认的通用子智能体。你的 spec 会完全替换它。
要完全移除内置的通用子智能体而不是替换它,请将活动 harness profile 的通用子智能体 enabled 标志设置为 False。
何时使用它
通用子智能体非常适合在无专门行为的情况下做上下文隔离。主智能体可以将复杂的多步任务委派给这个子智能体,并在不因中间工具调用而膨胀的情况下拿回简洁的结果。
Example
主智能体不必自己执行 10 次网络搜索并用结果填满自己的上下文,而是委派给通用子智能体:task(name="general-purpose", task="Research quantum computing trends")。该子智能体在内部执行所有搜索,只返回一份摘要。
技能继承
使用 create_deep_agent 配置技能时:
- 通用子智能体:自动从主智能体继承技能
- 自定义子智能体:默认不继承技能——使用
skills参数给它们自己的技能
NOTE
只有配置了技能的子智能体才会获得 SkillsMiddleware 实例——没有 skills 参数的自定义子智能体则不会。当存在时,技能状态在两个方向上都是完全隔离的:父级的技能对子级不可见,子级的技能也不会传播回父级。
python
from deepagents import create_deep_agent
research_subagent = {
"name": "researcher",
"description": "Research assistant with specialized skills",
"system_prompt": "You are a researcher.",
"tools": [web_search],
"skills": ["/skills/researcher/"], # Subagent-specific skills
}
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
skills=["/skills/main/"], # Main agent and GP subagent get these
subagents=[research_subagent], # Researcher gets only its own skills
)最佳实践
编写清晰的描述
主智能体使用描述来决定调用哪个子智能体。要具体:
✅ 好: "分析财务数据并生成带有置信度评分的投资洞察"
❌ 差: "做一些财务方面的事情"
保持系统提示词详尽
包含关于如何使用工具和格式化输出的具体指导:
python
research_subagent = {
"name": "research-agent",
"description": "Conducts in-depth research using web search and synthesizes findings",
"system_prompt": """You are a thorough researcher. Your job is to:
1. Break down the research question into searchable queries
2. Use internet_search to find relevant information
3. Synthesize findings into a comprehensive but concise summary
4. Cite sources when making claims
Output format:
- Summary (2-3 paragraphs)
- Key findings (bullet points)
- Sources (with URLs)
Keep your response under 500 words to maintain clean context.""",
"tools": [internet_search],
}尽量减少工具集
只给子智能体它们需要的工具。这能提升专注度和安全性:
python
# ✅ Good: Focused tool set
email_agent = {
"name": "email-sender",
"tools": [send_email, validate_email], # Only email-related
}python
# ❌ Bad: Too many tools
email_agent = {
"name": "email-sender",
"tools": [send_email, web_search_tool, database_query, format_document], # Unfocused
}按任务选择模型
不同的模型擅长不同的任务:
python
subagents = [
{
"name": "contract-reviewer",
"description": "Reviews legal documents and contracts",
"system_prompt": "You are an expert legal reviewer...",
"tools": [read_document, analyze_contract],
"model": "google_genai:gemini-3.6-flash", # Large context for long documents
},
{
"name": "financial-analyst",
"description": "Analyzes financial data and market trends",
"system_prompt": "You are an expert financial analyst...",
"tools": [get_stock_price, analyze_fundamentals],
"model": "openai:gpt-5.5", # Better for numerical analysis
},
]返回简洁的结果
指示子智能体返回摘要,而不是原始数据:
python
data_analyst = {
"system_prompt": """Analyze the data and return:
1. Key insights (3-5 bullet points)
2. Overall confidence score
3. Recommended next actions
Do NOT include:
- Raw data
- Intermediate calculations
- Detailed tool outputs
Keep response under 300 words."""
}常见模式
多个专门化的子智能体
为不同领域创建专门化的子智能体:
python
from deepagents import create_deep_agent
subagents = [
{
"name": "data-collector",
"description": "Gathers raw data from various sources",
"system_prompt": "Collect comprehensive data on the topic",
"tools": [web_search_tool, api_call, database_query],
},
{
"name": "data-analyzer",
"description": "Analyzes collected data for insights",
"system_prompt": "Analyze data and extract key insights",
"tools": [statistical_analysis],
},
{
"name": "report-writer",
"description": "Writes polished reports from analysis",
"system_prompt": "Create professional reports from insights",
"tools": [format_document],
},
]
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents=subagents,
)python
from deepagents import create_deep_agent
subagents = [
{
"name": "data-collector",
"description": "Gathers raw data from various sources",
"system_prompt": "Collect comprehensive data on the topic",
"tools": [web_search_tool, api_call, database_query],
},
{
"name": "data-analyzer",
"description": "Analyzes collected data for insights",
"system_prompt": "Analyze data and extract key insights",
"tools": [statistical_analysis],
},
{
"name": "report-writer",
"description": "Writes polished reports from analysis",
"system_prompt": "Create professional reports from insights",
"tools": [format_document],
},
]
agent = create_deep_agent(
model="openai:gpt-5.5",
system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents=subagents,
)python
from deepagents import create_deep_agent
subagents = [
{
"name": "data-collector",
"description": "Gathers raw data from various sources",
"system_prompt": "Collect comprehensive data on the topic",
"tools": [web_search_tool, api_call, database_query],
},
{
"name": "data-analyzer",
"description": "Analyzes collected data for insights",
"system_prompt": "Analyze data and extract key insights",
"tools": [statistical_analysis],
},
{
"name": "report-writer",
"description": "Writes polished reports from analysis",
"system_prompt": "Create professional reports from insights",
"tools": [format_document],
},
]
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents=subagents,
)python
from deepagents import create_deep_agent
subagents = [
{
"name": "data-collector",
"description": "Gathers raw data from various sources",
"system_prompt": "Collect comprehensive data on the topic",
"tools": [web_search_tool, api_call, database_query],
},
{
"name": "data-analyzer",
"description": "Analyzes collected data for insights",
"system_prompt": "Analyze data and extract key insights",
"tools": [statistical_analysis],
},
{
"name": "report-writer",
"description": "Writes polished reports from analysis",
"system_prompt": "Create professional reports from insights",
"tools": [format_document],
},
]
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents=subagents,
)python
from deepagents import create_deep_agent
subagents = [
{
"name": "data-collector",
"description": "Gathers raw data from various sources",
"system_prompt": "Collect comprehensive data on the topic",
"tools": [web_search_tool, api_call, database_query],
},
{
"name": "data-analyzer",
"description": "Analyzes collected data for insights",
"system_prompt": "Analyze data and extract key insights",
"tools": [statistical_analysis],
},
{
"name": "report-writer",
"description": "Writes polished reports from analysis",
"system_prompt": "Create professional reports from insights",
"tools": [format_document],
},
]
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents=subagents,
)python
from deepagents import create_deep_agent
subagents = [
{
"name": "data-collector",
"description": "Gathers raw data from various sources",
"system_prompt": "Collect comprehensive data on the topic",
"tools": [web_search_tool, api_call, database_query],
},
{
"name": "data-analyzer",
"description": "Analyzes collected data for insights",
"system_prompt": "Analyze data and extract key insights",
"tools": [statistical_analysis],
},
{
"name": "report-writer",
"description": "Writes polished reports from analysis",
"system_prompt": "Create professional reports from insights",
"tools": [format_document],
},
]
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents=subagents,
)python
from deepagents import create_deep_agent
subagents = [
{
"name": "data-collector",
"description": "Gathers raw data from various sources",
"system_prompt": "Collect comprehensive data on the topic",
"tools": [web_search_tool, api_call, database_query],
},
{
"name": "data-analyzer",
"description": "Analyzes collected data for insights",
"system_prompt": "Analyze data and extract key insights",
"tools": [statistical_analysis],
},
{
"name": "report-writer",
"description": "Writes polished reports from analysis",
"system_prompt": "Create professional reports from insights",
"tools": [format_document],
},
]
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents=subagents,
)工作流:
- 主智能体创建高层计划
- 将数据收集委派给 data-collector
- 将结果传递给 data-analyzer
- 将洞察发送给 report-writer
- 编译最终输出
每个子智能体都在只专注于自身任务的干净上下文中工作。
上下文管理
当你使用运行时上下文调用父智能体时,该上下文会自动传播到所有子智能体。每次子智能体运行都会收到与你在父级 invoke / ainvoke 调用中传入的相同运行时上下文。
这意味着在任何子智能体内运行的工具都可以访问你提供给父级的相同上下文值:
python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
session_id: str
@tool
def get_user_data(query: str, runtime: ToolRuntime[Context]) -> str:
"""Fetch data for the current user."""
user_id = runtime.context.user_id
return f"Data for user {user_id}: {query}"
research_subagent = {
"name": "researcher",
"description": "Conducts research for the current user",
"system_prompt": "You are a research assistant.",
"tools": [get_user_data],
}
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
subagents=[research_subagent],
context_schema=Context,
)
# Context flows to the researcher subagent and its tools automatically
result = agent.invoke(
{"messages": [HumanMessage("Look up my recent activity")]},
context=Context(user_id="user-123", session_id="abc"),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
session_id: str
@tool
def get_user_data(query: str, runtime: ToolRuntime[Context]) -> str:
"""Fetch data for the current user."""
user_id = runtime.context.user_id
return f"Data for user {user_id}: {query}"
research_subagent = {
"name": "researcher",
"description": "Conducts research for the current user",
"system_prompt": "You are a research assistant.",
"tools": [get_user_data],
}
agent = create_deep_agent(
model="openai:gpt-5.5",
subagents=[research_subagent],
context_schema=Context,
)
# Context flows to the researcher subagent and its tools automatically
result = agent.invoke(
{"messages": [HumanMessage("Look up my recent activity")]},
context=Context(user_id="user-123", session_id="abc"),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
session_id: str
@tool
def get_user_data(query: str, runtime: ToolRuntime[Context]) -> str:
"""Fetch data for the current user."""
user_id = runtime.context.user_id
return f"Data for user {user_id}: {query}"
research_subagent = {
"name": "researcher",
"description": "Conducts research for the current user",
"system_prompt": "You are a research assistant.",
"tools": [get_user_data],
}
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
subagents=[research_subagent],
context_schema=Context,
)
# Context flows to the researcher subagent and its tools automatically
result = agent.invoke(
{"messages": [HumanMessage("Look up my recent activity")]},
context=Context(user_id="user-123", session_id="abc"),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
session_id: str
@tool
def get_user_data(query: str, runtime: ToolRuntime[Context]) -> str:
"""Fetch data for the current user."""
user_id = runtime.context.user_id
return f"Data for user {user_id}: {query}"
research_subagent = {
"name": "researcher",
"description": "Conducts research for the current user",
"system_prompt": "You are a research assistant.",
"tools": [get_user_data],
}
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
subagents=[research_subagent],
context_schema=Context,
)
# Context flows to the researcher subagent and its tools automatically
result = agent.invoke(
{"messages": [HumanMessage("Look up my recent activity")]},
context=Context(user_id="user-123", session_id="abc"),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
session_id: str
@tool
def get_user_data(query: str, runtime: ToolRuntime[Context]) -> str:
"""Fetch data for the current user."""
user_id = runtime.context.user_id
return f"Data for user {user_id}: {query}"
research_subagent = {
"name": "researcher",
"description": "Conducts research for the current user",
"system_prompt": "You are a research assistant.",
"tools": [get_user_data],
}
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
subagents=[research_subagent],
context_schema=Context,
)
# Context flows to the researcher subagent and its tools automatically
result = agent.invoke(
{"messages": [HumanMessage("Look up my recent activity")]},
context=Context(user_id="user-123", session_id="abc"),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
session_id: str
@tool
def get_user_data(query: str, runtime: ToolRuntime[Context]) -> str:
"""Fetch data for the current user."""
user_id = runtime.context.user_id
return f"Data for user {user_id}: {query}"
research_subagent = {
"name": "researcher",
"description": "Conducts research for the current user",
"system_prompt": "You are a research assistant.",
"tools": [get_user_data],
}
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
subagents=[research_subagent],
context_schema=Context,
)
# Context flows to the researcher subagent and its tools automatically
result = agent.invoke(
{"messages": [HumanMessage("Look up my recent activity")]},
context=Context(user_id="user-123", session_id="abc"),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
session_id: str
@tool
def get_user_data(query: str, runtime: ToolRuntime[Context]) -> str:
"""Fetch data for the current user."""
user_id = runtime.context.user_id
return f"Data for user {user_id}: {query}"
research_subagent = {
"name": "researcher",
"description": "Conducts research for the current user",
"system_prompt": "You are a research assistant.",
"tools": [get_user_data],
}
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
subagents=[research_subagent],
context_schema=Context,
)
# Context flows to the researcher subagent and its tools automatically
result = agent.invoke(
{"messages": [HumanMessage("Look up my recent activity")]},
context=Context(user_id="user-123", session_id="abc"),
)每个子智能体的上下文
所有子智能体都接收相同的父级上下文。要传递特定于某个子智能体的配置,请在一个扁平的 context 映射中使用带命名空间的键(用子智能体名称作为键前缀,例如 researcher:max_depth),或者将这些设置建模为你的上下文类型上的独立字段:
python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def verify_claim(claim: str, runtime: ToolRuntime[Context]) -> str:
"""Verify a factual claim."""
strict_mode = runtime.context.fact_checker_strict_mode or False
if strict_mode:
return strict_verification(claim)
return basic_verification(claim)
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
subagents=[
{
"name": "fact-checker",
"description": "Verifies factual claims",
"system_prompt": "You verify claims carefully.",
"tools": [verify_claim],
},
],
context_schema=Context,
)
result = agent.invoke(
{"messages": [HumanMessage("Research this and verify the claims")]},
context=Context(
user_id="user-123",
researcher_max_depth=3,
fact_checker_strict_mode=True,
),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def verify_claim(claim: str, runtime: ToolRuntime[Context]) -> str:
"""Verify a factual claim."""
strict_mode = runtime.context.fact_checker_strict_mode or False
if strict_mode:
return strict_verification(claim)
return basic_verification(claim)
agent = create_deep_agent(
model="openai:gpt-5.5",
subagents=[
{
"name": "fact-checker",
"description": "Verifies factual claims",
"system_prompt": "You verify claims carefully.",
"tools": [verify_claim],
},
],
context_schema=Context,
)
result = agent.invoke(
{"messages": [HumanMessage("Research this and verify the claims")]},
context=Context(
user_id="user-123",
researcher_max_depth=3,
fact_checker_strict_mode=True,
),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def verify_claim(claim: str, runtime: ToolRuntime[Context]) -> str:
"""Verify a factual claim."""
strict_mode = runtime.context.fact_checker_strict_mode or False
if strict_mode:
return strict_verification(claim)
return basic_verification(claim)
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
subagents=[
{
"name": "fact-checker",
"description": "Verifies factual claims",
"system_prompt": "You verify claims carefully.",
"tools": [verify_claim],
},
],
context_schema=Context,
)
result = agent.invoke(
{"messages": [HumanMessage("Research this and verify the claims")]},
context=Context(
user_id="user-123",
researcher_max_depth=3,
fact_checker_strict_mode=True,
),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def verify_claim(claim: str, runtime: ToolRuntime[Context]) -> str:
"""Verify a factual claim."""
strict_mode = runtime.context.fact_checker_strict_mode or False
if strict_mode:
return strict_verification(claim)
return basic_verification(claim)
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
subagents=[
{
"name": "fact-checker",
"description": "Verifies factual claims",
"system_prompt": "You verify claims carefully.",
"tools": [verify_claim],
},
],
context_schema=Context,
)
result = agent.invoke(
{"messages": [HumanMessage("Research this and verify the claims")]},
context=Context(
user_id="user-123",
researcher_max_depth=3,
fact_checker_strict_mode=True,
),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def verify_claim(claim: str, runtime: ToolRuntime[Context]) -> str:
"""Verify a factual claim."""
strict_mode = runtime.context.fact_checker_strict_mode or False
if strict_mode:
return strict_verification(claim)
return basic_verification(claim)
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
subagents=[
{
"name": "fact-checker",
"description": "Verifies factual claims",
"system_prompt": "You verify claims carefully.",
"tools": [verify_claim],
},
],
context_schema=Context,
)
result = agent.invoke(
{"messages": [HumanMessage("Research this and verify the claims")]},
context=Context(
user_id="user-123",
researcher_max_depth=3,
fact_checker_strict_mode=True,
),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def verify_claim(claim: str, runtime: ToolRuntime[Context]) -> str:
"""Verify a factual claim."""
strict_mode = runtime.context.fact_checker_strict_mode or False
if strict_mode:
return strict_verification(claim)
return basic_verification(claim)
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
subagents=[
{
"name": "fact-checker",
"description": "Verifies factual claims",
"system_prompt": "You verify claims carefully.",
"tools": [verify_claim],
},
],
context_schema=Context,
)
result = agent.invoke(
{"messages": [HumanMessage("Research this and verify the claims")]},
context=Context(
user_id="user-123",
researcher_max_depth=3,
fact_checker_strict_mode=True,
),
)python
from dataclasses import dataclass
from deepagents import create_deep_agent
from langchain.messages import HumanMessage
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def verify_claim(claim: str, runtime: ToolRuntime[Context]) -> str:
"""Verify a factual claim."""
strict_mode = runtime.context.fact_checker_strict_mode or False
if strict_mode:
return strict_verification(claim)
return basic_verification(claim)
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
subagents=[
{
"name": "fact-checker",
"description": "Verifies factual claims",
"system_prompt": "You verify claims carefully.",
"tools": [verify_claim],
},
],
context_schema=Context,
)
result = agent.invoke(
{"messages": [HumanMessage("Research this and verify the claims")]},
context=Context(
user_id="user-123",
researcher_max_depth=3,
fact_checker_strict_mode=True,
),
)识别是哪个子智能体调用了工具
当同一个工具在父级和多个子智能体之间共享时,你可以使用 lc_agent_name 元数据(与流式输出中使用的值相同)来确定是哪个智能体发起了该调用:
python
# :snippet-start: subagents-shared-lookup-py
from langchain.tools import ToolRuntime, tool
@tool
def shared_lookup(query: str, runtime: ToolRuntime) -> str:
"""Look up information."""
agent_name = runtime.config.get("metadata", {}).get("lc_agent_name")
if agent_name == "fact-checker":
return strict_lookup(query)
return general_lookup(query)你可以组合两种模式——在分支工具行为时,从 runtime.context 读取智能体专属设置,并从 runtime.config 元数据读取 lc_agent_name。
python
from dataclasses import dataclass
from langchain.tools import ToolRuntime, tool
@dataclass
class Context:
user_id: str
researcher_max_depth: int | None = None
fact_checker_strict_mode: bool | None = None
@tool
def flexible_search(query: str, runtime: ToolRuntime[Context]) -> str:
"""Search with agent-specific settings."""
agent_name = runtime.config.get("metadata", {}).get("lc_agent_name", "unknown")
ctx = runtime.context
if agent_name == "researcher":
max_results = ctx.researcher_max_depth or 5
else:
max_results = 5
include_raw = False
return perform_search(query, max_results=max_results, include_raw=include_raw)故障排查
子智能体未被调用
问题:主智能体试图自己完成工作,而不是委派。
解决方案:
让描述更具体:
python# ✅ Good good_subagent = { "name": "research-specialist", "description": "Conducts in-depth research on specific topics using web search. Use when you need detailed information that requires multiple searches.", }python# ❌ Bad bad_subagent = { "name": "helper", "description": "helps with stuff", }指示主智能体进行委派:
python
from deepagents import create_deep_agent
agent = create_deep_agent(
model="google_genai:gemini-3.6-flash",
system_prompt="""...your instructions...
IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
This keeps your context clean and improves results.""",
subagents=[
{
"name": "research-agent",
"description": "Conducts research",
"system_prompt": "You are a researcher.",
},
],
)python
from deepagents import create_deep_agent
agent = create_deep_agent(
model="openai:gpt-5.5",
system_prompt="""...your instructions...
IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
This keeps your context clean and improves results.""",
subagents=[
{
"name": "research-agent",
"description": "Conducts research",
"system_prompt": "You are a researcher.",
},
],
)python
from deepagents import create_deep_agent
agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
system_prompt="""...your instructions...
IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
This keeps your context clean and improves results.""",
subagents=[
{
"name": "research-agent",
"description": "Conducts research",
"system_prompt": "You are a researcher.",
},
],
)python
from deepagents import create_deep_agent
agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
system_prompt="""...your instructions...
IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
This keeps your context clean and improves results.""",
subagents=[
{
"name": "research-agent",
"description": "Conducts research",
"system_prompt": "You are a researcher.",
},
],
)python
from deepagents import create_deep_agent
agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
system_prompt="""...your instructions...
IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
This keeps your context clean and improves results.""",
subagents=[
{
"name": "research-agent",
"description": "Conducts research",
"system_prompt": "You are a researcher.",
},
],
)python
from deepagents import create_deep_agent
agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
system_prompt="""...your instructions...
IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
This keeps your context clean and improves results.""",
subagents=[
{
"name": "research-agent",
"description": "Conducts research",
"system_prompt": "You are a researcher.",
},
],
)python
from deepagents import create_deep_agent
agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
system_prompt="""...your instructions...
IMPORTANT: For complex tasks, delegate to your subagents using the task() tool.
This keeps your context clean and improves results.""",
subagents=[
{
"name": "research-agent",
"description": "Conducts research",
"system_prompt": "You are a researcher.",
},
],
)上下文仍然在膨胀
问题:尽管使用了子智能体,上下文仍被填满。
解决方案:
指示子智能体返回简洁的结果:
pythonsystem_prompt = """... IMPORTANT: Return only the essential summary. Do NOT include raw data, intermediate search results, or detailed tool outputs. Your response should be under 500 words."""对大数据使用文件系统:
pythonsystem_prompt = """When you gather large amounts of data: 1. Save raw data to /data/raw_results.txt 2. Process and analyze the data 3. Return only the analysis summary This keeps context clean."""
选择了错误的子智能体
问题:主智能体为该任务调用了不合适的子智能体。
解决方案:在描述中清晰区分各子智能体:
python
subagents = [
{
"name": "quick-researcher",
"description": "For simple, quick research questions that need 1-2 searches. Use when you need basic facts or definitions.",
"system_prompt": "You are the quick-researcher subagent.",
},
{
"name": "deep-researcher",
"description": "For complex, in-depth research requiring multiple searches, synthesis, and analysis. Use for comprehensive reports.",
"system_prompt": "You are the deep-researcher subagent.",
},
]