深度智能体可以创建子智能体来委托工作。您可以在 subagents 参数中指定自定义子智能体。子智能体对于上下文隔离(保持主智能体的上下文清洁)以及提供专业化指令非常有用。

为什么使用子智能体?

子智能体解决了上下文膨胀问题。当智能体使用具有大量输出的工具(网络搜索、文件读取、数据库查询)时,上下文窗口会被中间结果迅速填满。子智能体可以隔离这些细节工作——主智能体只接收最终结果,而不是几十次工具调用产生的冗余内容。 何时使用子智能体:
  • ✅ 会让主智能体上下文变得混乱的多步骤任务
  • ✅ 需要自定义指令或工具的专业领域
  • ✅ 需要不同模型能力的任务
  • ✅ 希望主智能体专注于高层协调时
何时不该使用子智能体:
  • ❌ 简单的单步骤任务
  • ❌ 需要保留中间上下文的场景
  • ❌ 子智能体的额外开销大于收益时

配置

subagents 应该是字典或 CompiledSubAgent 对象的列表,有两种定义方式。

SubAgent(基于字典)

大多数用例中,将子智能体定义为字典即可: 必填字段:
  • name (str):子智能体的唯一标识。主智能体在调用 task() 工具时会使用此名称。
  • description (str):子智能体负责的工作。描述要具体、可执行,便于主智能体决定何时委派。
  • system_prompt (str):对子智能体的指令,包含工具使用说明和输出格式要求。
  • tools (List[Callable]):子智能体可使用的工具。尽量保持精简,只提供必要工具。
可选字段:
  • model (str | BaseChatModel):覆盖主智能体的模型。使用 "提供商:模型名" 格式(例如 "openai:gpt-4o")。
  • middleware (List[Middleware]):额外中间件,用于自定义行为、记录日志或限流。
  • interrupt_on (Dict[str, bool]):为特定工具配置人在回路,需要搭配检查点使用。

CompiledSubAgent

针对复杂工作流,可以为子智能体提供预编译的 LangGraph 图: 字段:
  • name (str):唯一标识
  • description (str):子智能体职责
  • runnable (Runnable):经 .compile() 编译的 LangGraph 图

使用 SubAgent

import os
from typing import Literal
from tavily import TavilyClient
from deepagents import create_deep_agent

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,
):
    """运行网络搜索"""
    return tavily_client.search(
        query,
        max_results=max_results,
        include_raw_content=include_raw_content,
        topic=topic,
    )

research_subagent = {
    "name": "research-agent",
    "description": "用于深入研究问题",
    "system_prompt": "You are a great researcher",
    "tools": [internet_search],
    "model": "openai:gpt-4o",  # 可选覆盖,默认为主智能体模型
}
subagents = [research_subagent]

agent = create_deep_agent(
    model="claude-sonnet-4-5-20250929",
    subagents=subagents
)

使用 CompiledSubAgent

对于更复杂的场景,可以将预构建的 LangGraph 图作为子智能体传入:
from deepagents import create_deep_agent, CompiledSubAgent
from langchain.agents import create_agent

# 创建自定义智能体图
custom_graph = create_agent(
    model=your_model,
    tools=specialized_tools,
    prompt="You are a specialized agent for data analysis..."
)

# 将其作为自定义子智能体
custom_subagent = CompiledSubAgent(
    name="data-analyzer",
    description="专门用于复杂数据分析任务的智能体",
    runnable=custom_graph
)

subagents = [custom_subagent]

agent = create_deep_agent(
    model="claude-sonnet-4-5-20250929",
    tools=[internet_search],
    system_prompt=research_instructions,
    subagents=subagents
)

通用子智能体

除了用户定义的子智能体外,深度智能体始终可以访问一个 general-purpose(通用)子智能体。该子智能体:
  • 与主智能体共享同一系统提示
  • 拥有相同的工具访问权限
  • 使用相同的模型(除非显式覆盖)

何时使用

通用子智能体适合在无需特殊行为的情况下实现上下文隔离。主智能体可以将复杂的多步骤任务委派给它,从而获得简洁的结果,避免中间工具调用导致上下文膨胀。

示例

与其让主智能体执行 10 次网络搜索并填满上下文,不如将任务委派给通用子智能体:task(name="general-purpose", task="Research quantum computing trends")。子智能体会在内部完成所有搜索,并仅返回摘要。

最佳实践

编写清晰的描述

主智能体会根据描述来决定调用哪个子智能体,请确保描述具体、可操作。 优秀示例: "Analyzes financial data and generates investment insights with confidence scores" 糟糕示例: "Does finance stuff"

保持系统提示详尽

提供关于如何使用工具以及如何格式化输出的具体指导:
research_subagent = {
    "name": "research-agent",
    "description": "Conducts in-depth research using web search and synthesizes findings",
    "system_prompt": """You are a thorough researcher. Your job is to:

    1. Break down the research question into searchable queries
    2. Use internet_search to find relevant information
    3. Synthesize findings into a comprehensive but concise summary
    4. Cite sources when making claims

    Output format:
    - Summary (2-3 paragraphs)
    - Key findings (bullet points)
    - Sources (with URLs)

    Keep your response under 500 words to maintain clean context.""",
    "tools": [internet_search],
}

精简工具集

仅为子智能体提供必要的工具,以保证专注度和安全性。
# ✅ 优秀:聚焦的工具集
email_agent = {
    "name": "email-sender",
    "tools": [send_email, validate_email],  # 仅与邮件相关
}

# ❌ 糟糕:工具过多
email_agent = {
    "name": "email-sender",
    "tools": [send_email, web_search, database_query, file_upload],  # 缺乏聚焦
}

按任务选择模型

不同模型擅长不同的任务,按需选择最合适的模型:
subagents = [
    {
        "name": "contract-reviewer",
        "description": "Reviews legal documents and contracts",
        "system_prompt": "You are an expert legal reviewer...",
        "tools": [read_document, analyze_contract],
        "model": "claude-sonnet-4-5-20250929",  # 长文档需要更大上下文
    },
    {
        "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-4o",  # 更适合数值分析
    },
]

返回精炼结果

要求子智能体仅返回摘要,而非原始数据:
data_analyst = {
    "system_prompt": """Analyze the data and return:
    1. Key insights (3-5 bullet points)
    2. Overall confidence score
    3. Recommended next actions

    Do NOT include:
    - Raw data
    - Intermediate calculations
    - Detailed tool outputs

    Keep response under 300 words."""
}

常见模式

多个专业子智能体

针对不同领域创建专业子智能体:
from deepagents import create_deep_agent

subagents = [
    {
        "name": "data-collector",
        "description": "收集与主题相关的原始数据",
        "system_prompt": "Collect comprehensive data on the topic",
        "tools": [web_search, api_call, database_query],
    },
    {
        "name": "data-analyzer",
        "description": "分析已收集的数据并提炼洞察",
        "system_prompt": "Analyze data and extract key insights",
        "tools": [statistical_analysis],
    },
    {
        "name": "report-writer",
        "description": "根据分析结果撰写专业报告",
        "system_prompt": "Create professional reports from insights",
        "tools": [format_document],
    },
]

agent = create_deep_agent(
    model="claude-sonnet-4-5-20250929",
    system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
    subagents=subagents
)
工作流程:
  1. 主智能体创建高层计划
  2. 将数据收集委派给 data-collector
  3. 将结果传递给 data-analyzer
  4. 将洞察交给 report-writer
  5. 汇总最终输出
每个子智能体都在干净且专注的上下文中运行。

故障排除

子智能体未被调用

问题:主智能体尝试自己完成工作而不是委派。 解决方案
  1. 让描述更加具体:
    # ✅ 优秀
    {"name": "research-specialist", "description": "Conducts in-depth research on specific topics using web search. Use when you need detailed information that requires multiple searches."}
    
    # ❌ 糟糕
    {"name": "helper", "description": "helps with stuff"}
    
  2. 在主智能体提示中强调委派:
    agent = create_deep_agent(
        system_prompt="""...your instructions...
    
        IMPORTANT: 对于复杂任务,请使用 task() 工具将工作委派给子智能体。
        这样可以保持上下文整洁,并提升结果质量。""",
        subagents=[...]
    )
    

上下文仍然膨胀

问题:即使使用了子智能体,上下文仍然被填满。 解决方案
  1. 要求子智能体返回精炼结果:
    system_prompt="""...
    
    IMPORTANT: 仅返回最关键的摘要。
    请勿包含原始数据、中间搜索结果或详细的工具输出。
    你的响应应控制在 500 个英文单词以内。"""
    
  2. 使用文件系统存储大数据:
    system_prompt="""当你需要收集大量数据时:
    1. 将原始数据保存到 /data/raw_results.txt
    2. 对数据进行处理和分析
    3. 只返回分析摘要
    
    这样可以保持上下文干净。"""
    

被选择的子智能体不正确

问题:主智能体为任务调用了不合适的子智能体。 解决方案:在描述中清晰地区分子智能体:
subagents = [
    {
        "name": "quick-researcher",
        "description": "适用于 1-2 次搜索即可搞定的简单快速调研,获取基础事实或定义时使用。",
    },
    {
        "name": "deep-researcher",
        "description": "适用于需要多次搜索、信息综合与分析的复杂深度调研,面向完整报告场景。",
    }
]

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.