subagents 参数中指定自定义子智能体。子智能体适用于 上下文隔离(保持主智能体的上下文纯净)以及提供专门指令的场景。
本页面介绍 同步 子智能体,即监督者会等待子智能体完成操作才会继续。对于长时间运行的任务、并行工作流或需要中途调整和取消的情况,请参考 异步子智能体。
为什么使用子智能体?
子智能体解决上下文膨胀问题。当智能体使用具有大输出的工具(网络搜索、文件读取、数据库查询)时,上下文窗口会迅速被中间结果填满。子智能体隔离了这项详细工作——主智能体只接收最终结果,而不是产生它的几十个工具调用。 何时使用子智能体:- ✅ 多步骤任务,会弄乱主智能体的上下文
- ✅ 需要自定义指令或工具的专业领域
- ✅ 需要不同模型能力的任务
- ✅ 当你想让主智能体专注于高级协调时
- ❌ 简单的单步骤任务
- ❌ 当你需要维护中间上下文
- ❌ 当开销大于收益
配置
subagents 应该是一个字典列表或 @[CompiledSubAgent] 对象。有两种类型:
默认子智能体
Deep Agents 自动添加一个同步general-purpose 子智能体,除非你已经提供了一个同名的同步子智能体。
general-purpose 子智能体默认具有文件系统工具,可以通过额外的工具/中间件进行自定义。
- 要替换它,请传递你自己的名为
general-purpose的子智能体。 - 要重命名或重新提示自动添加的版本,请在活动的 harness profile 上设置
general_purpose_subagent=GeneralPurposeSubagentProfile(...)。 - 要禁用它,请参阅下文的 不使用子智能体。
不使用子智能体
要运行一个不使用task 工具的智能体,请做两件事:
- 在活动的 harness profile 上设置
general_purpose_subagent=GeneralPurposeSubagentProfile(enabled=False)。 - 通过
subagents=在create_deep_agent上传递无同步子智能体。
SubAgentMiddleware](以及 task 工具)。如果没有默认的或调用者提供的,智能体将无代理运行。
异步子智能体不受影响——它们通过自己的中间件和工具运行,如 异步子智能体 中所述。
不要在这里使用
excluded_middleware——SubAgentMiddleware 是必需的框架结构,列出它会导致 ValueError。general_purpose_subagent.enabled = False 旋钮是支持路径。自定义子智能体
你可以使用subagents 参数定义具有特定工具的专用子智能体,例如作为代码审查员、网络研究员或测试运行器。
对于大多数用例,将子智能体定义为 子智能体字典 中的字典。对于复杂的工作流程,使用一个 CompiledSubAgent:
子智能体(基于字典)
将子智能体定义为与 @[SubAgent] 规范匹配的字典,包含以下字段:
:::python
| 字段 | 类型 | 描述 |
|---|---|---|
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 与默认匹配的实例会替换它,任何其他内容都会位于最后一个核心中间件条目之后,以及配置、提示缓存和记忆之前。参见 覆盖默认中间件实例。例如,在此处包含一个 @[FilesystemMiddleware] 实例,具有 tools 允许列表,以独立于主智能体限制子智能体的文件系统工具。更多信息,请参阅 虚拟文件系统访问 下的“限制文件系统工具”部分。 |
interrupt_on | dict[str, bool | InterruptOnConfig] | 可选。为特定工具配置 人机交互。选项:True、False 或一个 InterruptOnConfig,其中包含 allowed_decisions。需要检查点。默认继承自主智能体。子智能体值覆盖默认值。 |
skills | list[str] | 可选。技能 源路径。指定时,子智能体从这些目录(例如,["/skills/researcher/"],其子目录是技能的容器)加载技能。这允许子智能体具有与主智能体不同的技能集。不继承自主智能体。仅通用子智能体继承主智能体的技能。当子智能体具有技能时,它运行自己的独立 @[ SkillsMiddleware] 实例。技能状态完全隔离——子智能体加载的技能对父智能体不可见,反之亦然。 |
response_format | ResponseFormat | 可选。结构化输出 模式。设置时,父智能体将接收子智能体的结果作为 JSON 而不是自由文本。接受 Pydantic 模型、ToolStrategy(...)、ProviderStrategy(...) 或原始模式类型。参见 结构化输出。 |
permissions | list[FilesystemPermission] | 可选。文件系统权限规则。设置时,完全替换父智能体的权限。 默认继承自主智能体。 |
| 字段 | 类型 | 描述 |
|---|---|---|
name | string | 必填项。子智能体的唯一标识符。主智能体通过此名称调用 task() 工具。子智能体名称会成为 AIMessage 的元数据,并在流式输出中帮助区分智能体。 |
description | string | 必填项。子智能体的功能描述。需具体且行动导向。主智能体据此决定何时委派任务。 |
systemPrompt | string | 必填项(默认值 mode: "isolated")。子智能体的指令。自定义隔离子智能体需自行定义。包含工具使用指导和输出格式要求。不继承主智能体。对于 mode: "fork",除非需要分支专用补充说明,否则无需此字段。参见 分支子智能体。 |
mode | "isolated" | "fork" | 可选。上下文模式。默认为 "isolated"(子智能体仅可见委派任务)。设为 "fork" 以继承父智能体的对话和系统提示。参见 分支子智能体。 |
tools | StructuredTool[] | 可选。子智能体可调用的工具。需保持精简,仅包含必要工具。 默认继承主智能体工具。明确指定时将完全覆盖继承工具。 |
model | LanguageModelLike | string | 可选。覆盖主智能体的模型。省略则使用主智能体模型。 默认继承主智能体模型。可传入类似 'openai:gpt-5.5'(使用 'provider:model' 格式)的模型标识字符串,或 LangChain 对话模型对象(await initChatModel("gpt-5.5") 或 new ChatOpenAI({ model: "gpt-5.5" }))。 |
middleware | AgentMiddleware[] | 可选。自定义中间件(如日志、限流)。 不继承主智能体。附加到 同步子智能体栈。 |
interruptOn | Record<string, boolean | InterruptOnConfig> | 可选。针对特定工具配置 人工介入。选项: True、False。或包含 InterruptOnConfig 的 allowed_decisions。需检查点器。默认继承主智能体。子智能体值将覆盖默认设置。 |
skills | string[] | 可选。技能 源路径。指定后子智能体将从这些目录加载技能(如 ["/skills/research/", "/skills/web-search/"])。此功能使子智能体能拥有与主智能体不同的技能集。不继承主智能体。通用型子智能体继承主智能体技能。当子智能体包含技能时,独立运行自己的 @[ SkillsMiddleware] 实例。技能状态完全隔离——子智能体的加载技能对父智能体不可见,反之亦然。 |
responseFormat | ResponseFormat | 可选。结构化输出 模式。启用后父智能体以 JSON 格式接收子智能体结果而非自由文本。支持 Zod схемы、JSON schema 对象、 toolStrategy(...) 或 providerStrategy(...)。参见 结构化输出。 |
permissions | FilesystemPermission[] | 可选。文件系统权限规则。启用后 完全替换 父智能体的权限。 默认继承主智能体权限。 |
编译子智能体
对于复杂工作流,使用预构建的 LangGraph 图作为 @[CompiledSubAgent]:
| 字段 | 类型 | 描述 |
|---|---|---|
name | str | 必填项。子智能体的唯一标识符。子智能体名称会成为 AIMessage 的元数据,并在流式输出中帮助区分智能体。 |
description | str | 必填项。子智能体的功能描述。 |
runnable | Runnable | 必填项。需先调用 .compile() 的编译 LangGraph 图。 |
mode | "isolated" | "fork" | 可选。默认为 "isolated"。设为 "fork" 以继承父智能体的消息历史。编译图无论何种模式均保持自身系统提示。参见 分支子智能体。 |
使用子智能体
:::pythonimport 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,
)
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";
const internetSearch = tool(
async ({
query,
maxResults = 5,
topic = "general",
includeRawContent = false,
}: {
query: string;
maxResults?: number;
topic?: "general" | "news" | "finance";
includeRawContent?: boolean;
}) => {
const tavilySearch = new TavilySearch({
maxResults,
tavilyApiKey: process.env.TAVILY_API_KEY,
includeRawContent,
topic,
});
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
}),
},
);
const researchSubagent: SubAgent = {
name: "research-agent",
description: "Used to research more in depth questions",
systemPrompt: "You are a great researcher",
tools: [internetSearch],
model: "google:gemini-3.6-flash", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents,
});
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";
const internetSearch = tool(
async ({
query,
maxResults = 5,
topic = "general",
includeRawContent = false,
}: {
query: string;
maxResults?: number;
topic?: "general" | "news" | "finance";
includeRawContent?: boolean;
}) => {
const tavilySearch = new TavilySearch({
maxResults,
tavilyApiKey: process.env.TAVILY_API_KEY,
includeRawContent,
topic,
});
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
}),
},
);
const researchSubagent: SubAgent = {
name: "research-agent",
description: "Used to research more in depth questions",
systemPrompt: "You are a great researcher",
tools: [internetSearch],
model: "openai:gpt-5.5", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents,
});
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";
const internetSearch = tool(
async ({
query,
maxResults = 5,
topic = "general",
includeRawContent = false,
}: {
query: string;
maxResults?: number;
topic?: "general" | "news" | "finance";
includeRawContent?: boolean;
}) => {
const tavilySearch = new TavilySearch({
maxResults,
tavilyApiKey: process.env.TAVILY_API_KEY,
includeRawContent,
topic,
});
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
}),
},
);
const researchSubagent: SubAgent = {
name: "research-agent",
description: "Used to research more in depth questions",
systemPrompt: "You are a great researcher",
tools: [internetSearch],
model: "anthropic:claude-sonnet-5", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents,
});
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";
const internetSearch = tool(
async ({
query,
maxResults = 5,
topic = "general",
includeRawContent = false,
}: {
query: string;
maxResults?: number;
topic?: "general" | "news" | "finance";
includeRawContent?: boolean;
}) => {
const tavilySearch = new TavilySearch({
maxResults,
tavilyApiKey: process.env.TAVILY_API_KEY,
includeRawContent,
topic,
});
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
}),
},
);
const researchSubagent: SubAgent = {
name: "research-agent",
description: "Used to research more in depth questions",
systemPrompt: "You are a great researcher",
tools: [internetSearch],
model: "openrouter:z-ai/glm-5.2", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents,
});
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";
const internetSearch = tool(
async ({
query,
maxResults = 5,
topic = "general",
includeRawContent = false,
}: {
query: string;
maxResults?: number;
topic?: "general" | "news" | "finance";
includeRawContent?: boolean;
}) => {
const tavilySearch = new TavilySearch({
maxResults,
tavilyApiKey: process.env.TAVILY_API_KEY,
includeRawContent,
topic,
});
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
}),
},
);
const researchSubagent: SubAgent = {
name: "research-agent",
description: "Used to research more in depth questions",
systemPrompt: "You are a great researcher",
tools: [internetSearch],
model: "fireworks:accounts/fireworks/models/glm-5p2", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents,
});
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";
const internetSearch = tool(
async ({
query,
maxResults = 5,
topic = "general",
includeRawContent = false,
}: {
query: string;
maxResults?: number;
topic?: "general" | "news" | "finance";
includeRawContent?: boolean;
}) => {
const tavilySearch = new TavilySearch({
maxResults,
tavilyApiKey: process.env.TAVILY_API_KEY,
includeRawContent,
topic,
});
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
}),
},
);
const researchSubagent: SubAgent = {
name: "research-agent",
description: "Used to research more in depth questions",
systemPrompt: "You are a great researcher",
tools: [internetSearch],
model: "baseten:zai-org/GLM-5.2", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents,
});
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";
const internetSearch = tool(
async ({
query,
maxResults = 5,
topic = "general",
includeRawContent = false,
}: {
query: string;
maxResults?: number;
topic?: "general" | "news" | "finance";
includeRawContent?: boolean;
}) => {
const tavilySearch = new TavilySearch({
maxResults,
tavilyApiKey: process.env.TAVILY_API_KEY,
includeRawContent,
topic,
});
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
}),
},
);
const researchSubagent: SubAgent = {
name: "research-agent",
description: "Used to research more in depth questions",
systemPrompt: "You are a great researcher",
tools: [internetSearch],
model: "ollama:north-mini-code-1.0", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents,
});
使用编译子智能体
对于更复杂场景,可通过 @[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,
)
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,
)
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,
)
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,
)
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,
)
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,
)
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,
)
import { CompiledSubAgent, createDeepAgent } from "deepagents";
import { createAgent } from "langchain";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
const researchInstructions = "You are a research coordinator.";
const yourModel = "google:gemini-3.6-flash";
const specializedTools: never[] = [];
// Create a custom agent graph
const customGraph = createAgent({
model: yourModel,
tools: specializedTools,
prompt: "You are a specialized agent for data analysis...",
});
// Use it as a custom subagent
const customSubagent: CompiledSubAgent = {
name: "data-analyzer",
description: "Specialized agent for complex data analysis tasks",
runnable: customGraph,
};
const subagents = [customSubagent];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
tools: [internetSearch],
systemPrompt: researchInstructions,
subagents: subagents,
});
import { CompiledSubAgent, createDeepAgent } from "deepagents";
import { createAgent } from "langchain";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
const researchInstructions = "You are a research coordinator.";
const yourModel = "google:gemini-3.6-flash";
const specializedTools: never[] = [];
// Create a custom agent graph
const customGraph = createAgent({
model: yourModel,
tools: specializedTools,
prompt: "You are a specialized agent for data analysis...",
});
// Use it as a custom subagent
const customSubagent: CompiledSubAgent = {
name: "data-analyzer",
description: "Specialized agent for complex data analysis tasks",
runnable: customGraph,
};
const subagents = [customSubagent];
const agent = createDeepAgent({
model: "openai:gpt-5.5",
tools: [internetSearch],
systemPrompt: researchInstructions,
subagents: subagents,
});
import { CompiledSubAgent, createDeepAgent } from "deepagents";
import { createAgent } from "langchain";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
const researchInstructions = "You are a research coordinator.";
const yourModel = "google:gemini-3.6-flash";
const specializedTools: never[] = [];
// Create a custom agent graph
const customGraph = createAgent({
model: yourModel,
tools: specializedTools,
prompt: "You are a specialized agent for data analysis...",
});
// Use it as a custom subagent
const customSubagent: CompiledSubAgent = {
name: "data-analyzer",
description: "Specialized agent for complex data analysis tasks",
runnable: customGraph,
};
const subagents = [customSubagent];
const agent = createDeepAgent({
model: "anthropic:claude-sonnet-5",
tools: [internetSearch],
systemPrompt: researchInstructions,
subagents: subagents,
});
import { CompiledSubAgent, createDeepAgent } from "deepagents";
import { createAgent } from "langchain";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
const researchInstructions = "You are a research coordinator.";
const yourModel = "google:gemini-3.6-flash";
const specializedTools: never[] = [];
// Create a custom agent graph
const customGraph = createAgent({
model: yourModel,
tools: specializedTools,
prompt: "You are a specialized agent for data analysis...",
});
// Use it as a custom subagent
const customSubagent: CompiledSubAgent = {
name: "data-analyzer",
description: "Specialized agent for complex data analysis tasks",
runnable: customGraph,
};
const subagents = [customSubagent];
const agent = createDeepAgent({
model: "openrouter:z-ai/glm-5.2",
tools: [internetSearch],
systemPrompt: researchInstructions,
subagents: subagents,
});
import { CompiledSubAgent, createDeepAgent } from "deepagents";
import { createAgent } from "langchain";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
const researchInstructions = "You are a research coordinator.";
const yourModel = "google:gemini-3.6-flash";
const specializedTools: never[] = [];
// Create a custom agent graph
const customGraph = createAgent({
model: yourModel,
tools: specializedTools,
prompt: "You are a specialized agent for data analysis...",
});
// Use it as a custom subagent
const customSubagent: CompiledSubAgent = {
name: "data-analyzer",
description: "Specialized agent for complex data analysis tasks",
runnable: customGraph,
};
const subagents = [customSubagent];
const agent = createDeepAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [internetSearch],
systemPrompt: researchInstructions,
subagents: subagents,
});
import { CompiledSubAgent, createDeepAgent } from "deepagents";
import { createAgent } from "langchain";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
const researchInstructions = "You are a research coordinator.";
const yourModel = "google:gemini-3.6-flash";
const specializedTools: never[] = [];
// Create a custom agent graph
const customGraph = createAgent({
model: yourModel,
tools: specializedTools,
prompt: "You are a specialized agent for data analysis...",
});
// Use it as a custom subagent
const customSubagent: CompiledSubAgent = {
name: "data-analyzer",
description: "Specialized agent for complex data analysis tasks",
runnable: customGraph,
};
const subagents = [customSubagent];
const agent = createDeepAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [internetSearch],
systemPrompt: researchInstructions,
subagents: subagents,
});
import { CompiledSubAgent, createDeepAgent } from "deepagents";
import { createAgent } from "langchain";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
const researchInstructions = "You are a research coordinator.";
const yourModel = "google:gemini-3.6-flash";
const specializedTools: never[] = [];
// Create a custom agent graph
const customGraph = createAgent({
model: yourModel,
tools: specializedTools,
prompt: "You are a specialized agent for data analysis...",
});
// Use it as a custom subagent
const customSubagent: CompiledSubAgent = {
name: "data-analyzer",
description: "Specialized agent for complex data analysis tasks",
runnable: customGraph,
};
const subagents = [customSubagent];
const agent = createDeepAgent({
model: "ollama:north-mini-code-1.0",
tools: [internetSearch],
systemPrompt: researchInstructions,
subagents: subagents,
});
分叉子智能体
默认情况下,子智能体以mode: "isolated" 运行:它只能看到你给它的任务描述,并且没有关于导致委派之前的对话的记忆。一个 分叉子智能体(mode: "fork")会继承父智能体的对话历史和状态。
当子智能体的任务是继续父智能体已经开始的工作时,请使用分叉子智能体,例如一个接手父智能体已经诊断出的修复工作的工人智能体,或者一个为事件调查起草事后总结的子智能体。由于分叉是设置在子智能体本身的模式,所以这是你在定义它时做出的决定。
:::python
子智能体分叉需要
deepagents>=0.7.13。它处于 beta 状态;API 和行为可能在版本之间发生变化。子智能体分叉需要
deepagents>=1.13.3。它处于 beta 状态;API 和行为可能在版本之间发生变化。配置分叉子智能体
:::python 在 @[SubAgent] 上设置 mode: "fork"(默认值为 mode: "isolated")。你可以配置这些 @[SubAgent] 字段:
name、description、tools、model、middleware、interrupt_on、permissions 和 response_format。
分叉会继承传递给父智能体的 create_deep_agent 中的自定义中间件。子智能体的 middleware 列表中的中间件会替换继承的相同 .name 的实例。其他实例会被添加到子智能体的默认中间件堆栈中。
默认情况下,分叉会继承传递给父智能体的所有工具。设置 tools 以替换这些工具,而不是添加它们。例如,一个包含一个工具的列表会替换继承的列表为那个工具。文件系统和其他由中间件提供的工具会单独添加。
如果提供 skills,则会被拒绝。system_prompt 会被追加到父智能体继承的提示词中作为补充。除非你需要仅适用于分叉的指令,否则请保持它未设置。
一个 wrap_model_call 钩子通过 request.system_message 接收分叉继承的提示词。它可以使用 request.override(system_message=...) 重新编写分叉的传出请求,而不会改变父智能体的提示词。这与 system_prompt 不同,后者会追加指令。
避免重写共享继承前缀或修改工具定义,除非你接受缓存复用率降低和潜在模型成本上升。例如,此钩子片段会在继承前缀前添加文本,从而防止该前缀被复用:
from langchain.messages import SystemMessage
rewritten = SystemMessage(content=[
{"type": "text", "text": "You are a security auditor.\n"},
*request.system_message.content_blocks,
])
return handler(request.override(system_message=rewritten))
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 运行。
mode: "fork" 为 @[SubAgent](默认是 mode: "isolated")。您可配置这些 @[SubAgent] 字段:
name, description, tools, model, middleware, interruptOn, permissions, 和 responseFormat。
分支继承父节点的技能;设置 skills 不受支持。
留空 systemPrompt 以使用父节点的提示词。若设置,其指令将追加到父节点提示词后,缩短跨服务提供商提示缓存中共享前缀的长度。因此,除非分支需要额外指令,否则不建议设置分支特定的系统提示。
默认情况下,分支继承父节点传递的所有工具。设置 tools 以替换而非追加这些工具。例如,包含单个工具的列表将替换继承的列表为该工具。文件系统和其他中间件提供的工具将单独追加。
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const readDiff = tool(
async ({ path }: { path: string }) => `diff for ${path}`,
{
name: "read_diff",
description: "Read a file's diff",
schema: z.object({ path: z.string() }),
},
);
const commentWriter = {
name: "comment-writer",
description: "Continues an in-progress PR review and drafts review comments",
mode: "fork" as const,
tools: [readDiff],
};
const agent = await createDeepAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [readDiff],
subagents: [commentWriter],
});
const result = await 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 运行。
工作原理
分支接收父节点的有效对话历史和委托任务描述。Deep Agents 会移除末尾的委托调用,并将任务描述与延续前导语附加。若父节点已压缩历史,分支将接收该压缩上下文,而非所有原始消息。 此处分支(forking)指继承委托工作的上下文,而非复制持久化线程的检查点历史。子智能体将接收为其调用的准备好的状态,且排除父节点独有字段。完成工作时,其回答作为普通工具结果返回,父节点继续处理。 :::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."),
]
// What the parent has, right before delegating
[
new HumanMessage("Review the changes in PR #482"),
new AIMessage({ content: "", tool_calls: [{ name: "read_diff", args: { path: "src/auth/session.py" } }] }),
new ToolMessage({ content: "- session tokens are logged in plaintext\n- no expiry check on refresh", tool_call_id: "1" }),
new AIMessage("Found two issues: session tokens are logged in plaintext, and there's no expiry check on refresh."),
new HumanMessage("Good catch. Draft review comments for those."),
new AIMessage({ content: "", tool_calls: [{ name: "task", args: { subagentType: "comment-writer", description: "Draft review comments for the two issues found above." } }] }),
]
// What the fork actually sees
[
new HumanMessage("Review the changes in PR #482"),
new AIMessage({ content: "", tool_calls: [{ name: "read_diff", args: { path: "src/auth/session.py" } }] }),
new ToolMessage({ content: "- session tokens are logged in plaintext\n- no expiry check on refresh", tool_call_id: "1" }),
new AIMessage("Found two issues: session tokens are logged in plaintext, and there's no expiry check on refresh."),
new HumanMessage("Good catch. Draft review comments for those."),
new HumanMessage("Continuing as the subagent that was just invoked. Draft review comments for the two issues found above."),
]
CompiledSubAgent] 支持 mode: "fork",尽管它保留自己的系统提示,因为图已构建。
何时使用分支
从以下维度对比独立模式(默认)和分支模式:| 维度 | 独立模式(默认) | 分支模式 |
|---|---|---|
| 上下文 | 仅您传入的任务描述 | 父节点的有效对话历史、继承状态和任务描述 |
| 系统提示和技能 | 您在子智能体上设置 | 继承技能和父节点基础提示。可选系统提示可追加指令并减少缓存复用 |
| 调用其他子智能体 | 可使用 task 工具 | 不能使用 task;必须自行完成任务 |
| 适用场景 | 需要少量先验上下文的工作 | 继续父节点已启动的调查 |
动态子智能体
默认情况下,主智能体通过task 工具调用委托子智能体(可单次调用并行执行多个)。附加 解释器 后,智能体可通过代码分发子智能体——使用循环、分支和并行批次将工作分散到多个项并程序化合成结果。这称为 动态子智能体。
当工作跨越多个独立单元(如审查目录下所有文件、分批处理工单)、需要多视角或受益于递归分析时,应使用动态子智能体。
动态子智能体使用解释器运行时,该运行时处于 β版。API 和生命周期行为可能在版本间变更。
启用动态子智能体
当智能体同时具备子智能体和解释器中间件时,动态子智能体即可用。安装 QuickJS 解释器包,并在智能体中添加CodeInterpreterMiddleware。
:::python
pip install -U "deepagents[quickjs]"
uv add "deepagents[quickjs]"
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()],
)
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()],
)
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()],
)
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()],
)
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()],
)
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()],
)
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()],
)
动态子智能体分发默认开启,当智能体具备子智能体和解释器中间件时。传递
CodeInterpreterMiddleware(subagents=False) 以强制通过常规 task 工具路径分发。解释器需要 langchain-quickjs>=0.2.0 和 Python 3.11 或更高版本。npm install deepagents @langchain/quickjs
pnpm add deepagents @langchain/quickjs
yarn add deepagents @langchain/quickjs
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents: [{
name: "reviewer",
description: "Reviews code for security issues, citing lines and severity",
systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "openai:gpt-5.5",
subagents: [{
name: "reviewer",
description: "Reviews code for security issues, citing lines and severity",
systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "anthropic:claude-sonnet-5",
subagents: [{
name: "reviewer",
description: "Reviews code for security issues, citing lines and severity",
systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "openrouter:z-ai/glm-5.2",
subagents: [{
name: "reviewer",
description: "Reviews code for security issues, citing lines and severity",
systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
subagents: [{
name: "reviewer",
description: "Reviews code for security issues, citing lines and severity",
systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "baseten:zai-org/GLM-5.2",
subagents: [{
name: "reviewer",
description: "Reviews code for security issues, citing lines and severity",
systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "ollama:north-mini-code-1.0",
subagents: [{
name: "reviewer",
description: "Reviews code for security issues, citing lines and severity",
systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
}],
middleware: [createCodeInterpreterMiddleware()],
});
动态子智能体分发默认开启,当智能体具备子智能体和解释器中间件时。传递
createCodeInterpreterMiddleware({ subagents: false }) 以强制通过常规 task 工具路径分发。触发动态编排
动态分发是隐式的:智能体根据任务结构决定是否通过代码分散工作,而非依赖每调用标志。“工作流” 是有效触发词。 内置解释器系统提示将 “工作流” 视为组织工作的信号——通过
task() 从代码分发子智能体。将请求表述为 “工作流” 是主动启用动态编排的杠杆:在需要智能体通过代码分散工作时使用该表述。对于单次直接委托,应平铺表述请求。result = agent.invoke({
"messages": [{"role": "user", "content": "Run a workflow that reviews every file in src/routes/ and summarizes the top risks."}]
})
const result = await 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:
curl -LsSf https://langch.in/dcode | bash
dcode
task 工具管理分散,智能体会编写调用内置 task() 全局的编排脚本来执行。例如:“运行一个工作流来审查 src/ 中的所有文件是否存在 SQL 注入。”
作为子代理的创建,dcode会在动态子代理面板中实时显示它们,并按调度阶段分组。

dcode 是快速体验此功能的最佳方式,但您也可以在您选择的编程代理(例如通过 ACP(如 Zed))中启用动态子代理。
流式输出
深度代理支持从协调者和所有受托子代理处接收流式更新。 :::python 使用stream_events 获取类型化投影——分别为子代理、消息、工具调用和值提供独立迭代器,以便独立消费每个部分。
:::
:::js
使用 streamEvents 获取类型化投影——分别为子代理、消息、工具调用和值提供独立迭代器,以便独立消费每个部分。
:::
跟踪子代理进度
最简单的模式是通过迭代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}")
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}")
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}")
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}")
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}")
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}")
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 运行。
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
name: "main-agent",
systemPrompt:
"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.",
systemPrompt: "You are a great researcher. Return a brief summary.",
},
],
});
async function streamSubagentProgress() {
const stream = await agent.streamEvents(
{
messages: [
{
role: "user",
content: "Research one recent advance in quantum computing.",
},
],
},
{ version: "v3" },
);
const coordinatorMessages: string[] = [];
const subagentHandles: { name: string }[] = [];
await Promise.all([
(async () => {
for await (const message of stream.messages) {
const text = await message.text;
console.log("[coordinator]", text);
coordinatorMessages.push(text);
}
})(),
(async () => {
for await (const subagent of stream.subagents) {
console.log(`[${subagent.name}] started`);
subagentHandles.push({ name: subagent.name });
for await (const message of subagent.messages) {
console.log(`[${subagent.name}]`, await message.text);
}
}
})(),
stream.output,
]);
return { coordinatorMessages, subagentHandles };
}
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: "openai:gpt-5.5",
name: "main-agent",
systemPrompt:
"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.",
systemPrompt: "You are a great researcher. Return a brief summary.",
},
],
});
async function streamSubagentProgress() {
const stream = await agent.streamEvents(
{
messages: [
{
role: "user",
content: "Research one recent advance in quantum computing.",
},
],
},
{ version: "v3" },
);
const coordinatorMessages: string[] = [];
const subagentHandles: { name: string }[] = [];
await Promise.all([
(async () => {
for await (const message of stream.messages) {
const text = await message.text;
console.log("[coordinator]", text);
coordinatorMessages.push(text);
}
})(),
(async () => {
for await (const subagent of stream.subagents) {
console.log(`[${subagent.name}] started`);
subagentHandles.push({ name: subagent.name });
for await (const message of subagent.messages) {
console.log(`[${subagent.name}]`, await message.text);
}
}
})(),
stream.output,
]);
return { coordinatorMessages, subagentHandles };
}
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: "anthropic:claude-sonnet-5",
name: "main-agent",
systemPrompt:
"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.",
systemPrompt: "You are a great researcher. Return a brief summary.",
},
],
});
async function streamSubagentProgress() {
const stream = await agent.streamEvents(
{
messages: [
{
role: "user",
content: "Research one recent advance in quantum computing.",
},
],
},
{ version: "v3" },
);
const coordinatorMessages: string[] = [];
const subagentHandles: { name: string }[] = [];
await Promise.all([
(async () => {
for await (const message of stream.messages) {
const text = await message.text;
console.log("[coordinator]", text);
coordinatorMessages.push(text);
}
})(),
(async () => {
for await (const subagent of stream.subagents) {
console.log(`[${subagent.name}] started`);
subagentHandles.push({ name: subagent.name });
for await (const message of subagent.messages) {
console.log(`[${subagent.name}]`, await message.text);
}
}
})(),
stream.output,
]);
return { coordinatorMessages, subagentHandles };
}
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: "openrouter:z-ai/glm-5.2",
name: "main-agent",
systemPrompt:
"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.",
systemPrompt: "You are a great researcher. Return a brief summary.",
},
],
});
async function streamSubagentProgress() {
const stream = await agent.streamEvents(
{
messages: [
{
role: "user",
content: "Research one recent advance in quantum computing.",
},
],
},
{ version: "v3" },
);
const coordinatorMessages: string[] = [];
const subagentHandles: { name: string }[] = [];
await Promise.all([
(async () => {
for await (const message of stream.messages) {
const text = await message.text;
console.log("[coordinator]", text);
coordinatorMessages.push(text);
}
})(),
(async () => {
for await (const subagent of stream.subagents) {
console.log(`[${subagent.name}] started`);
subagentHandles.push({ name: subagent.name });
for await (const message of subagent.messages) {
console.log(`[${subagent.name}]`, await message.text);
}
}
})(),
stream.output,
]);
return { coordinatorMessages, subagentHandles };
}
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
name: "main-agent",
systemPrompt:
"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.",
systemPrompt: "You are a great researcher. Return a brief summary.",
},
],
});
async function streamSubagentProgress() {
const stream = await agent.streamEvents(
{
messages: [
{
role: "user",
content: "Research one recent advance in quantum computing.",
},
],
},
{ version: "v3" },
);
const coordinatorMessages: string[] = [];
const subagentHandles: { name: string }[] = [];
await Promise.all([
(async () => {
for await (const message of stream.messages) {
const text = await message.text;
console.log("[coordinator]", text);
coordinatorMessages.push(text);
}
})(),
(async () => {
for await (const subagent of stream.subagents) {
console.log(`[${subagent.name}] started`);
subagentHandles.push({ name: subagent.name });
for await (const message of subagent.messages) {
console.log(`[${subagent.name}]`, await message.text);
}
}
})(),
stream.output,
]);
return { coordinatorMessages, subagentHandles };
}
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: "baseten:zai-org/GLM-5.2",
name: "main-agent",
systemPrompt:
"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.",
systemPrompt: "You are a great researcher. Return a brief summary.",
},
],
});
async function streamSubagentProgress() {
const stream = await agent.streamEvents(
{
messages: [
{
role: "user",
content: "Research one recent advance in quantum computing.",
},
],
},
{ version: "v3" },
);
const coordinatorMessages: string[] = [];
const subagentHandles: { name: string }[] = [];
await Promise.all([
(async () => {
for await (const message of stream.messages) {
const text = await message.text;
console.log("[coordinator]", text);
coordinatorMessages.push(text);
}
})(),
(async () => {
for await (const subagent of stream.subagents) {
console.log(`[${subagent.name}] started`);
subagentHandles.push({ name: subagent.name });
for await (const message of subagent.messages) {
console.log(`[${subagent.name}]`, await message.text);
}
}
})(),
stream.output,
]);
return { coordinatorMessages, subagentHandles };
}
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: "ollama:north-mini-code-1.0",
name: "main-agent",
systemPrompt:
"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.",
systemPrompt: "You are a great researcher. Return a brief summary.",
},
],
});
async function streamSubagentProgress() {
const stream = await agent.streamEvents(
{
messages: [
{
role: "user",
content: "Research one recent advance in quantum computing.",
},
],
},
{ version: "v3" },
);
const coordinatorMessages: string[] = [];
const subagentHandles: { name: string }[] = [];
await Promise.all([
(async () => {
for await (const message of stream.messages) {
const text = await message.text;
console.log("[coordinator]", text);
coordinatorMessages.push(text);
}
})(),
(async () => {
for await (const subagent of stream.subagents) {
console.log(`[${subagent.name}] started`);
subagentHandles.push({ name: subagent.name });
for await (const message of subagent.messages) {
console.log(`[${subagent.name}]`, await message.text);
}
}
})(),
stream.output,
]);
return { coordinatorMessages, subagentHandles };
}
LangSmith 追踪
当深度代理运行时,所有由子代理或协调者执行的操作都会在元数据中添加代理名称(键为lc_agent_name)。例如 {'lc_agent_name': 'research-agent'}。这允许您在 LangSmith 中通过子代理标识和过滤运行。

在 LangSmith 中打开运行以比较协调者追踪与各子代理运行。按照 可观测性快速入门 配置环境。我们建议同时启用 LangSmith Engine 以监控追踪、检测问题并推荐修复方案。
在 LangSmith 中按子代理过滤
由于每个子代理的name 会将其元数据写入 lc_agent_name 键的每个运行结果中,您可以使用 LangSmith 的元数据过滤功能隔离特定子代理的所有运行——适用于调试、监控或对比子代理行为变化。
在 LangSmith UI 中过滤
- 在 LangSmith 中打开您的追踪项目。
- 在追踪项目页切换视图为 运行 以查看独立跨度。
- 点击 添加过滤器 并选择 元数据。
- 设置 键 为
lc_agent_name,值 为子代理名称(例如coordinator)。
这仅显示该子代理生成的运行。可将过滤器保存为命名视图以复用。如需完整过滤选项参考,请查阅 过滤追踪。
通过 SDK 程序性过滤
使用 LangSmith 过滤查询语言中的has 比较器匹配元数据键值对:
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 键的运行:
runs = client.list_runs(
project_name="<your-project>",
filter="has(metadata, 'lc_agent_name')",
)
结构化输出
子智能体支持 结构化输出,因此父智能体可以接收到可预测且可解析的JSON格式数据,而非自由格式的文本。 :::python子智能体的结构化输出需要
deepagents>=0.5.3。response_format。当子智能体执行完毕,其结构化响应会被序列化为JSON并作为 ToolMessage 内容返回给父智能体。该方案支持任何由 @[create_agent] 支持的类型:Pydantic模型、ToolStrategy(...)、ProviderStrategy(...),或原始 schema 类型。
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://..."]}'
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://..."]}'
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://..."]}'
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://..."]}'
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://..."]}'
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://..."]}'
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://..."]}'
子智能体的结构化输出需要
deepagents>=1.8.4。responseFormat。当子智能体执行完毕,其结构化响应会被序列化为JSON并作为 ToolMessage 内容返回给父智能体。该方案支持任何由 createAgent 支持的类型:Zod模式、JSON schema对象、toolStrategy(...),或 providerStrategy(...)。
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
const webSearch = tool(
async ({ query }: { query: string }) => `web results for ${query}`,
{
name: "web_search",
description: "Search the web",
schema: z.object({ query: z.string() }),
},
);
const ResearchFindings = z.object({
summary: z.string().describe("Summary of findings"),
confidence: z.number().describe("Confidence score from 0 to 1"),
sources: z.array(z.string()).describe("List of source URLs"),
});
const researchSubagent = {
name: "researcher",
description: "Researches topics and returns structured findings",
systemPrompt: "Research the given topic thoroughly. Return your findings.",
tools: [webSearch],
responseFormat: ResearchFindings,
};
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents: [researchSubagent],
});
const result = await agent.invoke({
messages: [
{ role: "user", content: "Research recent advances in quantum computing" },
],
});
// The parent's ToolMessage contains JSON-serialized structured data:
// '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
const webSearch = tool(
async ({ query }: { query: string }) => `web results for ${query}`,
{
name: "web_search",
description: "Search the web",
schema: z.object({ query: z.string() }),
},
);
const ResearchFindings = z.object({
summary: z.string().describe("Summary of findings"),
confidence: z.number().describe("Confidence score from 0 to 1"),
sources: z.array(z.string()).describe("List of source URLs"),
});
const researchSubagent = {
name: "researcher",
description: "Researches topics and returns structured findings",
systemPrompt: "Research the given topic thoroughly. Return your findings.",
tools: [webSearch],
responseFormat: ResearchFindings,
};
const agent = createDeepAgent({
model: "openai:gpt-5.5",
subagents: [researchSubagent],
});
const result = await agent.invoke({
messages: [
{ role: "user", content: "Research recent advances in quantum computing" },
],
});
// The parent's ToolMessage contains JSON-serialized structured data:
// '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
const webSearch = tool(
async ({ query }: { query: string }) => `web results for ${query}`,
{
name: "web_search",
description: "Search the web",
schema: z.object({ query: z.string() }),
},
);
const ResearchFindings = z.object({
summary: z.string().describe("Summary of findings"),
confidence: z.number().describe("Confidence score from 0 to 1"),
sources: z.array(z.string()).describe("List of source URLs"),
});
const researchSubagent = {
name: "researcher",
description: "Researches topics and returns structured findings",
systemPrompt: "Research the given topic thoroughly. Return your findings.",
tools: [webSearch],
responseFormat: ResearchFindings,
};
const agent = createDeepAgent({
model: "anthropic:claude-sonnet-5",
subagents: [researchSubagent],
});
const result = await agent.invoke({
messages: [
{ role: "user", content: "Research recent advances in quantum computing" },
],
});
// The parent's ToolMessage contains JSON-serialized structured data:
// '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
const webSearch = tool(
async ({ query }: { query: string }) => `web results for ${query}`,
{
name: "web_search",
description: "Search the web",
schema: z.object({ query: z.string() }),
},
);
const ResearchFindings = z.object({
summary: z.string().describe("Summary of findings"),
confidence: z.number().describe("Confidence score from 0 to 1"),
sources: z.array(z.string()).describe("List of source URLs"),
});
const researchSubagent = {
name: "researcher",
description: "Researches topics and returns structured findings",
systemPrompt: "Research the given topic thoroughly. Return your findings.",
tools: [webSearch],
responseFormat: ResearchFindings,
};
const agent = createDeepAgent({
model: "openrouter:z-ai/glm-5.2",
subagents: [researchSubagent],
});
const result = await agent.invoke({
messages: [
{ role: "user", content: "Research recent advances in quantum computing" },
],
});
// The parent's ToolMessage contains JSON-serialized structured data:
// '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
const webSearch = tool(
async ({ query }: { query: string }) => `web results for ${query}`,
{
name: "web_search",
description: "Search the web",
schema: z.object({ query: z.string() }),
},
);
const ResearchFindings = z.object({
summary: z.string().describe("Summary of findings"),
confidence: z.number().describe("Confidence score from 0 to 1"),
sources: z.array(z.string()).describe("List of source URLs"),
});
const researchSubagent = {
name: "researcher",
description: "Researches topics and returns structured findings",
systemPrompt: "Research the given topic thoroughly. Return your findings.",
tools: [webSearch],
responseFormat: ResearchFindings,
};
const agent = createDeepAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
subagents: [researchSubagent],
});
const result = await agent.invoke({
messages: [
{ role: "user", content: "Research recent advances in quantum computing" },
],
});
// The parent's ToolMessage contains JSON-serialized structured data:
// '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
const webSearch = tool(
async ({ query }: { query: string }) => `web results for ${query}`,
{
name: "web_search",
description: "Search the web",
schema: z.object({ query: z.string() }),
},
);
const ResearchFindings = z.object({
summary: z.string().describe("Summary of findings"),
confidence: z.number().describe("Confidence score from 0 to 1"),
sources: z.array(z.string()).describe("List of source URLs"),
});
const researchSubagent = {
name: "researcher",
description: "Researches topics and returns structured findings",
systemPrompt: "Research the given topic thoroughly. Return your findings.",
tools: [webSearch],
responseFormat: ResearchFindings,
};
const agent = createDeepAgent({
model: "baseten:zai-org/GLM-5.2",
subagents: [researchSubagent],
});
const result = await agent.invoke({
messages: [
{ role: "user", content: "Research recent advances in quantum computing" },
],
});
// The parent's ToolMessage contains JSON-serialized structured data:
// '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
const webSearch = tool(
async ({ query }: { query: string }) => `web results for ${query}`,
{
name: "web_search",
description: "Search the web",
schema: z.object({ query: z.string() }),
},
);
const ResearchFindings = z.object({
summary: z.string().describe("Summary of findings"),
confidence: z.number().describe("Confidence score from 0 to 1"),
sources: z.array(z.string()).describe("List of source URLs"),
});
const researchSubagent = {
name: "researcher",
description: "Researches topics and returns structured findings",
systemPrompt: "Research the given topic thoroughly. Return your findings.",
tools: [webSearch],
responseFormat: ResearchFindings,
};
const agent = createDeepAgent({
model: "ollama:north-mini-code-1.0",
subagents: [researchSubagent],
});
const result = await agent.invoke({
messages: [
{ role: "user", content: "Research recent advances in quantum computing" },
],
});
// The parent's ToolMessage contains JSON-serialized structured data:
// '{"summary": "...", "confidence": 0.87, "sources": ["https://..."]}'
View example trace
为此示例打开一个公开的 LangSmith 运行。
response_format 时,父智能体会直接接收子智能体的最后消息文本。启用后,父智能体将始终获得与 schema 匹配的有效JSON,这在需要程序化处理结果或传递给下游工具时非常有用。
对于 schema 类型及策略(工具调用 vs. 原生实现)的完整细节,请参考 结构化输出。
通用子智能体
除用户自定义的子智能体外,每个深度智能体始终拥有一个general-purpose 子智能体。该子智能体具备以下特性:
- 使用经过 用户资料叠加后的默认系统提示
- 访问与主智能体相同的工具集
- 除非显式覆盖,否则使用相同模型
- 继承主智能体的技能(当技能已配置时)
覆盖通用子智能体
:::python在
subagents 列表中包含一个具有 name="general-purpose" 属性的子智能体,以替换默认配置。此方式可用于为通用子智能体配置不同的模型、工具或系统提示:
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
},
],
)
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
},
],
)
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
},
],
)
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
},
],
)
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
},
],
)
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
},
],
)
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
},
],
)
在
subagents 列表中包含一个具有 name: "general-purpose" 属性的子智能体,以替换默认配置。此方式可用于为通用子智能体配置不同的模型、工具或系统提示:
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
// Main agent uses Gemini; general-purpose subagent uses GPT
const agent = await createDeepAgent({
model: "google:gemini-3.6-flash",
tools: [internetSearch],
subagents: [
{
name: "general-purpose",
description: "General-purpose agent for research and multi-step tasks",
systemPrompt: "You are a general-purpose assistant.",
tools: [internetSearch],
model: "openai:gpt-5.5", // Different model for delegated tasks
},
],
});
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
// Main agent uses Gemini; general-purpose subagent uses GPT
const agent = await createDeepAgent({
model: "openai:gpt-5.5",
tools: [internetSearch],
subagents: [
{
name: "general-purpose",
description: "General-purpose agent for research and multi-step tasks",
systemPrompt: "You are a general-purpose assistant.",
tools: [internetSearch],
model: "openai:gpt-5.5", // Different model for delegated tasks
},
],
});
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
// Main agent uses Gemini; general-purpose subagent uses GPT
const agent = await createDeepAgent({
model: "anthropic:claude-sonnet-5",
tools: [internetSearch],
subagents: [
{
name: "general-purpose",
description: "General-purpose agent for research and multi-step tasks",
systemPrompt: "You are a general-purpose assistant.",
tools: [internetSearch],
model: "openai:gpt-5.5", // Different model for delegated tasks
},
],
});
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
// Main agent uses Gemini; general-purpose subagent uses GPT
const agent = await createDeepAgent({
model: "openrouter:z-ai/glm-5.2",
tools: [internetSearch],
subagents: [
{
name: "general-purpose",
description: "General-purpose agent for research and multi-step tasks",
systemPrompt: "You are a general-purpose assistant.",
tools: [internetSearch],
model: "openai:gpt-5.5", // Different model for delegated tasks
},
],
});
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
// Main agent uses Gemini; general-purpose subagent uses GPT
const agent = await createDeepAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [internetSearch],
subagents: [
{
name: "general-purpose",
description: "General-purpose agent for research and multi-step tasks",
systemPrompt: "You are a general-purpose assistant.",
tools: [internetSearch],
model: "openai:gpt-5.5", // Different model for delegated tasks
},
],
});
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
// Main agent uses Gemini; general-purpose subagent uses GPT
const agent = await createDeepAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [internetSearch],
subagents: [
{
name: "general-purpose",
description: "General-purpose agent for research and multi-step tasks",
systemPrompt: "You are a general-purpose assistant.",
tools: [internetSearch],
model: "openai:gpt-5.5", // Different model for delegated tasks
},
],
});
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import { z } from "zod";
const internetSearch = tool(
async ({ query }: { query: string }) => `search results for ${query}`,
{
name: "internet_search",
description: "Run a web search",
schema: z.object({ query: z.string() }),
},
);
// Main agent uses Gemini; general-purpose subagent uses GPT
const agent = await createDeepAgent({
model: "ollama:north-mini-code-1.0",
tools: [internetSearch],
subagents: [
{
name: "general-purpose",
description: "General-purpose agent for research and multi-step tasks",
systemPrompt: "You are a general-purpose assistant.",
tools: [internetSearch],
model: "openai:gpt-5.5", // Different model for delegated tasks
},
],
});
enabled 标志设置为 False。
使用场景
通用子智能体适用于无需特殊行为的上下文隔离场景。主智能体可将复杂多步骤任务委托给该子智能体,并获取精炼的结果,而无需中间工具调用带来的冗余信息。Example
相较于主智能体执行10次网络搜索并填充上下文,采用通用子智能体可优化流程:
task(name="general-purpose", task="Research quantum computing trends")。子智能体内部完成所有搜索操作,仅返回摘要。技能继承
在配置 技能 时若启用create_deep_agent:
- 通用子智能体:自动继承主智能体的技能
- 自定义子智能体:默认不继承技能——需通过
skills参数为其配置独立技能
带有技能配置的子智能体才能获得
SkillsMiddleware 实例——未配置 skills 参数的自定义子智能体不会。当存在时,技能状态在双向间完全隔离:父智能体的技能对子智能体不可见,子智能体的技能也不会回传至父智能体。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
)
import { createDeepAgent } from "deepagents";
const researchSubagent = {
name: "researcher",
description: "Research assistant with specialized skills",
systemPrompt: "You are a researcher.",
tools: [webSearch],
skills: ["/skills/research/", "/skills/web-search/"], // Subagent-specific skills
};
const agent = await createDeepAgent({
model: "google:gemini-3.6-flash",
skills: ["/skills/main/"], // Main agent and GP subagent get these
subagents: [researchSubagent], // Researcher gets only its own skills
});
最佳实践
写清晰描述
主智能体通过描述决定调用哪个子智能体。需具体说明: ✅ 好的:"Analyzes financial data and generates investment insights with confidence scores"
❌ 坏的: "Does finance stuff"
保持系统提示详细
包含使用工具的具体指导及输出格式规范: :::pythonresearch_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],
}
const researchSubagent = {
name: "research-agent",
description:
"Conducts in-depth research using web search and synthesizes findings",
systemPrompt: `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: [internetSearch],
};
最小化工具集
仅向子智能体提供其所需工具。这能提升专注度和安全性: :::python# ✅ Good: Focused tool set
email_agent = {
"name": "email-sender",
"tools": [send_email, validate_email], # Only email-related
}
// ✅ Good: Focused tool set
const emailAgent = {
name: "email-sender",
tools: [sendEmail, validateEmail], // Only email-related
};
# ❌ Bad: Too many tools
email_agent = {
"name": "email-sender",
"tools": [send_email, web_search_tool, database_query, format_document], # Unfocused
}
// ❌ Bad: Too many tools
const emailAgentBad = {
name: "email-sender",
tools: [sendEmail, webSearch, databaseQuery, fileUpload], // Unfocused
};
根据任务选择模型
不同模型擅长不同任务: :::pythonsubagents = [
{
"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
},
]
const subagents = [
{
name: "contract-reviewer",
description: "Reviews legal documents and contracts",
systemPrompt: "You are an expert legal reviewer...",
tools: [readDocument, analyzeContract],
model: "google:gemini-3.6-flash", // Large context for long documents
},
{
name: "financial-analyst",
description: "Analyzes financial data and market trends",
systemPrompt: "You are an expert financial analyst...",
tools: [getStockPrice, analyzeFundamentals],
model: "openai:gpt-5.5", // Better for numerical analysis
},
];
const subagents = [
{
name: "contract-reviewer",
description: "Reviews legal documents and contracts",
systemPrompt: "You are an expert legal reviewer...",
tools: [readDocument, analyzeContract],
model: "openai:gpt-5.5", // Large context for long documents
},
{
name: "financial-analyst",
description: "Analyzes financial data and market trends",
systemPrompt: "You are an expert financial analyst...",
tools: [getStockPrice, analyzeFundamentals],
model: "openai:gpt-5.5", // Better for numerical analysis
},
];
const subagents = [
{
name: "contract-reviewer",
description: "Reviews legal documents and contracts",
systemPrompt: "You are an expert legal reviewer...",
tools: [readDocument, analyzeContract],
model: "anthropic:claude-sonnet-5", // Large context for long documents
},
{
name: "financial-analyst",
description: "Analyzes financial data and market trends",
systemPrompt: "You are an expert financial analyst...",
tools: [getStockPrice, analyzeFundamentals],
model: "openai:gpt-5.5", // Better for numerical analysis
},
];
const subagents = [
{
name: "contract-reviewer",
description: "Reviews legal documents and contracts",
systemPrompt: "You are an expert legal reviewer...",
tools: [readDocument, analyzeContract],
model: "openrouter:z-ai/glm-5.2", // Large context for long documents
},
{
name: "financial-analyst",
description: "Analyzes financial data and market trends",
systemPrompt: "You are an expert financial analyst...",
tools: [getStockPrice, analyzeFundamentals],
model: "openai:gpt-5.5", // Better for numerical analysis
},
];
const subagents = [
{
name: "contract-reviewer",
description: "Reviews legal documents and contracts",
systemPrompt: "You are an expert legal reviewer...",
tools: [readDocument, analyzeContract],
model: "fireworks:accounts/fireworks/models/glm-5p2", // Large context for long documents
},
{
name: "financial-analyst",
description: "Analyzes financial data and market trends",
systemPrompt: "You are an expert financial analyst...",
tools: [getStockPrice, analyzeFundamentals],
model: "openai:gpt-5.5", // Better for numerical analysis
},
];
const subagents = [
{
name: "contract-reviewer",
description: "Reviews legal documents and contracts",
systemPrompt: "You are an expert legal reviewer...",
tools: [readDocument, analyzeContract],
model: "baseten:zai-org/GLM-5.2", // Large context for long documents
},
{
name: "financial-analyst",
description: "Analyzes financial data and market trends",
systemPrompt: "You are an expert financial analyst...",
tools: [getStockPrice, analyzeFundamentals],
model: "openai:gpt-5.5", // Better for numerical analysis
},
];
const subagents = [
{
name: "contract-reviewer",
description: "Reviews legal documents and contracts",
systemPrompt: "You are an expert legal reviewer...",
tools: [readDocument, analyzeContract],
model: "ollama:north-mini-code-1.0", // Large context for long documents
},
{
name: "financial-analyst",
description: "Analyzes financial data and market trends",
systemPrompt: "You are an expert financial analyst...",
tools: [getStockPrice, analyzeFundamentals],
model: "openai:gpt-5.5", // Better for numerical analysis
},
];
返回简洁结果
要求子智能体返回摘要而非原始数据: :::pythondata_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."""
}
const dataAnalyst = {
systemPrompt: `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.`,
};
常见模式
多个专业化子智能体
为不同领域创建专业化子智能体: :::pythonfrom 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,
)
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,
)
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,
)
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,
)
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,
)
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,
)
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,
)
import { createDeepAgent } from "deepagents";
const subagents = [
{
name: "data-collector",
description: "Gathers raw data from various sources",
systemPrompt: "Collect comprehensive data on the topic",
tools: [webSearch, apiCall, databaseQuery],
},
{
name: "data-analyzer",
description: "Analyzes collected data for insights",
systemPrompt: "Analyze data and extract key insights",
tools: [statisticalAnalysis],
},
{
name: "report-writer",
description: "Writes polished reports from analysis",
systemPrompt: "Create professional reports from insights",
tools: [formatDocument],
},
];
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
systemPrompt:
"You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents: subagents,
});
import { createDeepAgent } from "deepagents";
const subagents = [
{
name: "data-collector",
description: "Gathers raw data from various sources",
systemPrompt: "Collect comprehensive data on the topic",
tools: [webSearch, apiCall, databaseQuery],
},
{
name: "data-analyzer",
description: "Analyzes collected data for insights",
systemPrompt: "Analyze data and extract key insights",
tools: [statisticalAnalysis],
},
{
name: "report-writer",
description: "Writes polished reports from analysis",
systemPrompt: "Create professional reports from insights",
tools: [formatDocument],
},
];
const agent = createDeepAgent({
model: "openai:gpt-5.5",
systemPrompt:
"You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents: subagents,
});
import { createDeepAgent } from "deepagents";
const subagents = [
{
name: "data-collector",
description: "Gathers raw data from various sources",
systemPrompt: "Collect comprehensive data on the topic",
tools: [webSearch, apiCall, databaseQuery],
},
{
name: "data-analyzer",
description: "Analyzes collected data for insights",
systemPrompt: "Analyze data and extract key insights",
tools: [statisticalAnalysis],
},
{
name: "report-writer",
description: "Writes polished reports from analysis",
systemPrompt: "Create professional reports from insights",
tools: [formatDocument],
},
];
const agent = createDeepAgent({
model: "anthropic:claude-sonnet-5",
systemPrompt:
"You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents: subagents,
});
import { createDeepAgent } from "deepagents";
const subagents = [
{
name: "data-collector",
description: "Gathers raw data from various sources",
systemPrompt: "Collect comprehensive data on the topic",
tools: [webSearch, apiCall, databaseQuery],
},
{
name: "data-analyzer",
description: "Analyzes collected data for insights",
systemPrompt: "Analyze data and extract key insights",
tools: [statisticalAnalysis],
},
{
name: "report-writer",
description: "Writes polished reports from analysis",
systemPrompt: "Create professional reports from insights",
tools: [formatDocument],
},
];
const agent = createDeepAgent({
model: "openrouter:z-ai/glm-5.2",
systemPrompt:
"You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents: subagents,
});
import { createDeepAgent } from "deepagents";
const subagents = [
{
name: "data-collector",
description: "Gathers raw data from various sources",
systemPrompt: "Collect comprehensive data on the topic",
tools: [webSearch, apiCall, databaseQuery],
},
{
name: "data-analyzer",
description: "Analyzes collected data for insights",
systemPrompt: "Analyze data and extract key insights",
tools: [statisticalAnalysis],
},
{
name: "report-writer",
description: "Writes polished reports from analysis",
systemPrompt: "Create professional reports from insights",
tools: [formatDocument],
},
];
const agent = createDeepAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
systemPrompt:
"You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents: subagents,
});
import { createDeepAgent } from "deepagents";
const subagents = [
{
name: "data-collector",
description: "Gathers raw data from various sources",
systemPrompt: "Collect comprehensive data on the topic",
tools: [webSearch, apiCall, databaseQuery],
},
{
name: "data-analyzer",
description: "Analyzes collected data for insights",
systemPrompt: "Analyze data and extract key insights",
tools: [statisticalAnalysis],
},
{
name: "report-writer",
description: "Writes polished reports from analysis",
systemPrompt: "Create professional reports from insights",
tools: [formatDocument],
},
];
const agent = createDeepAgent({
model: "baseten:zai-org/GLM-5.2",
systemPrompt:
"You coordinate data analysis and reporting. Use subagents for specialized tasks.",
subagents: subagents,
});
import { createDeepAgent } from "deepagents";
const subagents = [
{
name: "data-collector",
description: "Gathers raw data from various sources",
systemPrompt: "Collect comprehensive data on the topic",
tools: [webSearch, apiCall, databaseQuery],
},
{
name: "data-analyzer",
description: "Analyzes collected data for insights",
systemPrompt: "Analyze data and extract key insights",
tools: [statisticalAnalysis],
},
{
name: "report-writer",
description: "Writes polished reports from analysis",
systemPrompt: "Create professional reports from insights",
tools: [formatDocument],
},
];
const agent = createDeepAgent({
model: "ollama:north-mini-code-1.0",
systemPrompt:
"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"),
)
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"),
)
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"),
)
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"),
)
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"),
)
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"),
)
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"),
)
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
sessionId: z.string(),
});
const getUserData = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const userId = runtime.context?.userId;
return `Data for user ${userId}: ${input.query}`;
},
{
name: "get_user_data",
description: "Fetch data for the current user",
schema: z.object({ query: z.string() }),
},
);
const researchSubagent = {
name: "researcher",
description: "Conducts research for the current user",
systemPrompt: "You are a research assistant.",
tools: [getUserData],
};
const agent = createDeepAgent({
model: "google:gemini-3.6-flash",
subagents: [researchSubagent],
contextSchema,
});
// Context flows to the researcher subagent and its tools automatically
const result = await agent.invoke(
{ messages: [new HumanMessage("Look up my recent activity")] },
{ context: { userId: "user-123", sessionId: "abc" } },
);
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
sessionId: z.string(),
});
const getUserData = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const userId = runtime.context?.userId;
return `Data for user ${userId}: ${input.query}`;
},
{
name: "get_user_data",
description: "Fetch data for the current user",
schema: z.object({ query: z.string() }),
},
);
const researchSubagent = {
name: "researcher",
description: "Conducts research for the current user",
systemPrompt: "You are a research assistant.",
tools: [getUserData],
};
const agent = createDeepAgent({
model: "openai:gpt-5.5",
subagents: [researchSubagent],
contextSchema,
});
// Context flows to the researcher subagent and its tools automatically
const result = await agent.invoke(
{ messages: [new HumanMessage("Look up my recent activity")] },
{ context: { userId: "user-123", sessionId: "abc" } },
);
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
sessionId: z.string(),
});
const getUserData = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const userId = runtime.context?.userId;
return `Data for user ${userId}: ${input.query}`;
},
{
name: "get_user_data",
description: "Fetch data for the current user",
schema: z.object({ query: z.string() }),
},
);
const researchSubagent = {
name: "researcher",
description: "Conducts research for the current user",
systemPrompt: "You are a research assistant.",
tools: [getUserData],
};
const agent = createDeepAgent({
model: "anthropic:claude-sonnet-5",
subagents: [researchSubagent],
contextSchema,
});
// Context flows to the researcher subagent and its tools automatically
const result = await agent.invoke(
{ messages: [new HumanMessage("Look up my recent activity")] },
{ context: { userId: "user-123", sessionId: "abc" } },
);
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
sessionId: z.string(),
});
const getUserData = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const userId = runtime.context?.userId;
return `Data for user ${userId}: ${input.query}`;
},
{
name: "get_user_data",
description: "Fetch data for the current user",
schema: z.object({ query: z.string() }),
},
);
const researchSubagent = {
name: "researcher",
description: "Conducts research for the current user",
systemPrompt: "You are a research assistant.",
tools: [getUserData],
};
const agent = createDeepAgent({
model: "openrouter:z-ai/glm-5.2",
subagents: [researchSubagent],
contextSchema,
});
// Context flows to the researcher subagent and its tools automatically
const result = await agent.invoke(
{ messages: [new HumanMessage("Look up my recent activity")] },
{ context: { userId: "user-123", sessionId: "abc" } },
);
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
sessionId: z.string(),
});
const getUserData = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const userId = runtime.context?.userId;
return `Data for user ${userId}: ${input.query}`;
},
{
name: "get_user_data",
description: "Fetch data for the current user",
schema: z.object({ query: z.string() }),
},
);
const researchSubagent = {
name: "researcher",
description: "Conducts research for the current user",
systemPrompt: "You are a research assistant.",
tools: [getUserData],
};
const agent = createDeepAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
subagents: [researchSubagent],
contextSchema,
});
// Context flows to the researcher subagent and its tools automatically
const result = await agent.invoke(
{ messages: [new HumanMessage("Look up my recent activity")] },
{ context: { userId: "user-123", sessionId: "abc" } },
);
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
sessionId: z.string(),
});
const getUserData = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const userId = runtime.context?.userId;
return `Data for user ${userId}: ${input.query}`;
},
{
name: "get_user_data",
description: "Fetch data for the current user",
schema: z.object({ query: z.string() }),
},
);
const researchSubagent = {
name: "researcher",
description: "Conducts research for the current user",
systemPrompt: "You are a research assistant.",
tools: [getUserData],
};
const agent = createDeepAgent({
model: "baseten:zai-org/GLM-5.2",
subagents: [researchSubagent],
contextSchema,
});
// Context flows to the researcher subagent and its tools automatically
const result = await agent.invoke(
{ messages: [new HumanMessage("Look up my recent activity")] },
{ context: { userId: "user-123", sessionId: "abc" } },
);
import { createDeepAgent } from "deepagents";
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
sessionId: z.string(),
});
const getUserData = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const userId = runtime.context?.userId;
return `Data for user ${userId}: ${input.query}`;
},
{
name: "get_user_data",
description: "Fetch data for the current user",
schema: z.object({ query: z.string() }),
},
);
const researchSubagent = {
name: "researcher",
description: "Conducts research for the current user",
systemPrompt: "You are a research assistant.",
tools: [getUserData],
};
const agent = createDeepAgent({
model: "ollama:north-mini-code-1.0",
subagents: [researchSubagent],
contextSchema,
});
// Context flows to the researcher subagent and its tools automatically
const result = await agent.invoke(
{ messages: [new HumanMessage("Look up my recent activity")] },
{ context: { userId: "user-123", sessionId: "abc" } },
);
子智能体专属上下文
所有子智能体均接收相同父上下文。若需为特定子智能体传递配置,可通过以下方式之一:- 使用命名空间键(例如
researcher:max_depth)在扁平context映射前缀键 - 将设置建模为上下文类型中的独立字段
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,
),
)
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,
),
)
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,
),
)
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,
),
)
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,
),
)
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,
),
)
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,
),
)
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
researcherMaxDepth: z.number().optional(),
factCheckerStrictMode: z.boolean().optional(),
});
const verifyClaim = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const strictMode = runtime.context?.factCheckerStrictMode ?? false;
if (strictMode) {
return strictVerification(input.claim);
}
return basicVerification(input.claim);
},
{
name: "verify_claim",
description: "Verify a factual claim",
schema: z.object({ claim: z.string() }),
},
);
View example trace
为此示例打开一个公开的 LangSmith 运行。
识别调用工具的子智能体
当父智能体与多个子智能体共享相同工具时,可通过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)
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const sharedLookup = tool(
async (input, runtime: ToolRuntime) => {
const agentName = runtime.config?.metadata?.lc_agent_name;
if (agentName === "fact-checker") {
return strictLookup(input.query);
}
return generalLookup(input.query);
},
{
name: "shared_lookup",
description: "Look up information from various sources",
schema: z.object({ query: z.string() }),
},
);
View example trace
为此示例打开一个公开的 LangSmith 运行。
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)
import { tool } from "langchain";
import type { ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const contextSchema = z.object({
userId: z.string(),
researcherMaxDepth: z.number().optional(),
factCheckerStrictMode: z.boolean().optional(),
});
const flexibleSearch = tool(
async (input, runtime: ToolRuntime<unknown, typeof contextSchema>) => {
const agentName = runtime.config?.metadata?.lc_agent_name ?? "unknown";
const ctx = runtime.context;
const maxResults =
agentName === "researcher" ? (ctx?.researcherMaxDepth ?? 5) : 5;
const includeRaw = false;
return performSearch(input.query, { maxResults, includeRaw });
},
{
name: "flexible_search",
description: "Search with agent-specific settings",
schema: z.object({ query: z.string() }),
},
);
View example trace
为此示例打开一个公开的 LangSmith 运行。
故障排查
子智能体未被调用
问题:主智能体自行处理任务而非委托。 解决方案:-
使描述更具体:
:::python
::: :::js
# ✅ 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// ✅ Good const goodDescription = { name: "research-specialist", description: "Conducts in-depth research on specific topics using web search. Use when you need detailed information that requires multiple searches.", };::: :::js# ❌ Bad bad_subagent = { "name": "helper", "description": "helps with stuff", }:::// ❌ Bad const badDescription = { name: "helper", description: "helps with stuff", }; -
明确指示主智能体委托:
:::python
::: :::js
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.", }, ], )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.", }, ], )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.", }, ], )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.", }, ], )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.", }, ], )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.", }, ], )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.", }, ], ):::import { createDeepAgent } from "deepagents"; const agent = createDeepAgent({ systemPrompt: `...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", systemPrompt: "You are a researcher.", }, ], });
上下文仍持续膨胀
问题:使用子智能体后上下文仍膨胀。 解决方案:-
要求子智能体返回简洁结果:
:::python
::: :::js
system_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.""":::const systemPrompt = `... 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.`; -
使用文件系统存储大数据:
:::python
::: :::js
system_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.""":::const filesystemPrompt = `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.`;
错误子智能体被选中
问题:主智能体调用与任务不匹配的子智能体。 解决方案:在描述中清晰区分子智能体: :::pythonsubagents = [
{
"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.",
},
]
const subagents = [
{
name: "quick-researcher",
description:
"For simple, quick research questions that need 1-2 searches. Use when you need basic facts or definitions.",
systemPrompt: "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.",
systemPrompt: "You are the deep-researcher subagent.",
},
];
官方原文:src/oss/deepagents/subagents.mdx · 非官方翻译,译文由 AI 生成,以英文原文为准。