Skip to content

实战:多智能体 (Multi-Agent)

使用 Subagents 模式构建多 Agent 协作系统。

多智能体系统协调专门的组件来处理复杂的工作流。最常用的模式是 Subagents(子 Agent)模式:一个主 Agent 将子 Agent 作为工具进行协调,所有路由都通过主 Agent。

Subagents 模式

主 Agent 将子 Agent 作为工具调用,决定何时以及如何调用每个子 Agent:

python
from langchain.agents import create_agent, SubAgent
from langchain.tools import tool

# 创建研究子 Agent
research_agent = create_agent(
    model="openai:gpt-4o",
    tools=[],
    system_prompt="You are a research specialist.",
    name="researcher",
)

# 写作子 Agent
writing_agent = create_agent(
    model="openai:gpt-4o",
    tools=[],
    system_prompt="You are a writing specialist.",
    name="writer",
)

# 主 Agent 协调子 Agent
agent = create_agent(
    model="openai:gpt-4o",
    tools=[],
    subagents=[
        SubAgent(
            name="researcher",
            agent=research_agent,
            description="For researching and gathering information",
        ),
        SubAgent(
            name="writer",
            agent=writing_agent,
            description="For writing and composing content",
        ),
    ],
    system_prompt="You are a coordinator. Delegate tasks to your subagents.",
)

选择模式

模式适用场景
Subagents主 Agent 协调子 Agent,适用于分布式开发和并行执行
HandoffsAgent 之间动态切换控制权,子 Agent 可直接与用户交互
Skills单个 Agent 按需加载专业知识,保持控制权
Router路由步骤分类输入并分发给专门的 Agent

下一步

本站为非官方中文学习站点,不代表 LangChain 官方。部分内容参考官方文档并重新整理为中文学习笔记。