Skip to main content
深度智能体可以创建子智能体以委派工作。您可以在 subagents 参数中指定自定义子智能体。子智能体对于 隔离上下文(保持主智能体的上下文清洁)和提供专业指令很有用。

为什么使用子智能体?

子智能体解决了上下文膨胀问题。当智能体使用输出量大的工具(如网络搜索、文件读取、数据库查询)时,上下文窗口会迅速被中间结果填满。子智能体将这项详细工作隔离开——主智能体只接收最终结果,而不是产生这个结果的数十次工具调用。 何时使用子智能体:
  • ✅ 多步骤任务,这可能会使主智能体的上下文变得杂乱
  • ✅ 需要定制指令或工具的特定领域
  • ✅ 需要不同模型能力的任务
  • ✅ 当您希望主智能体专注于高级协调时
何时不使用子智能体:
  • ❌ 简单的单步任务
  • ❌ 需要维护中间上下文时
  • ❌ 当开销超过收益时

配置

subagents 应该是一个字典列表或 CompiledSubAgent 对象。有两种类型:

子智能体(基于字典)

对于大多数用例,将子智能体定义为字典: 必填字段:
  • 名称 (str):子智能体的唯一标识符。主智能体在调用 task() 工具时使用此名称。
  • 描述 (str):此子智能体执行的操作。请具体且以行动为导向。主智能体使用此信息来决定何时委派任务。
  • 系统提示 (str):对子智能体的指令。包括工具使用指南和输出格式要求。
  • 工具 (List[Callable]):子智能体可使用的工具。请保持最小化,仅包括所需工具。
可选字段:
  • 模型 (str | BaseChatModel): 覆盖主智能体的模型。使用格式 "provider:model-name"(例如,"openai:gpt-4o")。
  • 中间件 (List[Middleware]): 用于自定义行为、日志记录或速率限制的附加中间件。
  • 中断于 (Dict[str, bool]): 为特定工具配置人机交互。需要检查点器。

编译子智能体

对于复杂的流程,请使用预构建的 LangGraph 图。 字段:
  • name (str): 唯一标识符
  • description (str): 该子智能体执行的操作
  • runnable (Runnable): 编译后的 LangGraph 图(必须先调用 .compile()

使用子智能体

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,
):
    """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-4o",  # Optional override, defaults to main agent model
}
subagents = [research_subagent]

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-20250514",
    subagents=subagents
)

使用编译子智能体

对于更复杂的用例,您可以将自己的预构建LangGraph图作为子智能体提供:
from deepagents import create_deep_agent, CompiledSubAgent
from langchain.agents import create_agent

# Create a custom agent graph
custom_graph = create_agent(
    model=your_model,
    tools=specialized_tools,
    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-4-20250514",
    tools=[internet_search],
    system_prompt=research_instructions,
    subagents=subagents
)

通用子智能体

除了任何用户定义的子智能体之外,深度智能体始终可以访问一个 general-purpose 子智能体。此子智能体:
  • 与主智能体具有相同的系统提示
  • 可以访问所有相同的工具
  • 使用相同的模型(除非被覆盖)

何时使用它

通用子智能体非常适合在没有特定行为的情况下进行上下文隔离。主智能体可以将复杂的多个步骤任务委托给这个子智能体,并得到一个简洁的结果,而无需中间工具调用的冗余。

Example

与主智能体进行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],
}

最小化工具集

仅向子智能体提供它们所需的工具。这有助于提高专注度和安全性:
# ✅ Good: Focused tool set
email_agent = {
    "name": "email-sender",
    "tools": [send_email, validate_email],  # Only email-related
}

# ❌ Bad: Too many tools
email_agent = {
    "name": "email-sender",
    "tools": [send_email, web_search, database_query, file_upload],  # Unfocused
}

根据任务选择模型

不同的模型擅长不同的任务:
subagents = [
    {
        "name": "contract-reviewer",
        "description": "Reviews legal documents and contracts",
        "system_prompt": "You are an expert legal reviewer...",
        "tools": [read_document, analyze_contract],
        "model": "anthropic:claude-sonnet-4-20250514",  # 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-4o",  # Better for numerical analysis
    },
]

返回简洁的结果

指示子智能体返回摘要,而不是原始数据:
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": "Gathers raw data from various sources",
        "system_prompt": "Collect comprehensive data on the topic",
        "tools": [web_search, 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-4-20250514",
    system_prompt="You coordinate data analysis and reporting. Use subagents for specialized tasks.",
    subagents=subagents
)
工作流程:
  1. 主智能体创建高级计划
  2. 将数据收集任务委托给数据收集器
  3. 将结果传递给数据分析器
  4. 将洞察发送给报告编写者
  5. 编译最终输出
每个子智能体都只与专注于其任务的干净上下文一起工作。

故障排除

子智能体未被调用

问题:主智能体试图自己完成工作而不是委托。 解决方案
  1. 使描述更加具体:
    # ✅ Good
    {"name": "research-specialist", "description": "Conducts in-depth research on specific topics using web search. Use when you need detailed information that requires multiple searches."}
    
    # ❌ Bad
    {"name": "helper", "description": "helps with stuff"}
    
  2. 指示主智能体进行委派:
    agent = create_deep_agent(
        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=[...]
    )
    

上下文仍然在膨胀

问题:尽管使用了子智能体,上下文仍然会填满。 解决方案
  1. 指示子智能体返回简洁的结果:
    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."""
    
  2. 使用文件系统处理大数据:
    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."""
    

错误地选择了子智能体

问题:主智能体调用不合适的子智能体执行任务。 解决方案:在描述中明确区分子智能体:
subagents = [
    {
        "name": "quick-researcher",
        "description": "For simple, quick research questions that need 1-2 searches. Use when you need basic facts or definitions.",
    },
    {
        "name": "deep-researcher",
        "description": "For complex, in-depth research requiring multiple searches, synthesis, and analysis. Use for comprehensive reports.",
    }
]