Skip to content

多智能体

如果一个智能体需要在多个领域进行专业化或管理许多工具,它可能会遇到困难。为了解决这个问题,你可以将你的智能体分解为更小的、独立的智能体,并将它们组合成一个多智能体系统

在多智能体系统中,智能体之间需要相互通信。它们通过交接来实现这一点——这是一种描述将控制权交给哪个智能体以及发送给该智能体的有效载荷的原始机制。

目前最流行的两种多智能体架构是:

  • 监督器 — 由一个中央监督器智能体协调各个独立智能体。监督器控制所有的通信流和任务分配,根据当前上下文和任务需求决定调用哪个智能体。
  • 蜂群 — 智能体根据各自的专业化动态地将控制权交接给其他智能体。系统会记住上一次活跃的智能体,确保后续交互中对话能从该智能体继续进行。

Supervisor

Supervisor

使用 langgraph-supervisor 库创建一个监督多代理系统:

pip install langgraph-supervisor

API Reference: ChatOpenAI | create_react_agent | create_supervisor

from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langgraph_supervisor import create_supervisor

def book_hotel(hotel_name: str):
    """预订酒店"""
    return f"成功预订了 {hotel_name} 的住宿。"

def book_flight(from_airport: str, to_airport: str):
    """预订航班"""
    return f"成功预订了从 {from_airport}{to_airport} 的航班。"

flight_assistant = create_react_agent(
    model="openai:gpt-4o",
    tools=[book_flight],
    prompt="你是一个航班预订助手",
    name="flight_assistant"
)

hotel_assistant = create_react_agent(
    model="openai:gpt-4o",
    tools=[book_hotel],
    prompt="你是一个酒店预订助手",
    name="hotel_assistant"
)

supervisor = create_supervisor(
    agents=[flight_assistant, hotel_assistant],
    model=ChatOpenAI(model="gpt-4o"),
    prompt=(
        "你管理着一个酒店预订助手和一个"
        "航班预订助手。将任务分配给他们。"
    )
).compile()

for chunk in supervisor.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "预订从 BOS 到 JFK 的航班以及在 McKittrick Hotel 的住宿"
            }
        ]
    }
):
    print(chunk)
    print("\n")

Swarm

Swarm

使用 langgraph-swarm 库创建一个群组多代理系统:

pip install langgraph-swarm

API Reference: create_react_agent | create_swarm | create_handoff_tool

from langgraph.prebuilt import create_react_agent
from langgraph_swarm import create_swarm, create_handoff_tool

transfer_to_hotel_assistant = create_handoff_tool(
    agent_name="hotel_assistant",
    description="将用户转交给酒店预订助手。",
)
transfer_to_flight_assistant = create_handoff_tool(
    agent_name="flight_assistant",
    description="将用户转交给航班预订助手。",
)

flight_assistant = create_react_agent(
    model="anthropic:claude-3-5-sonnet-latest",
    tools=[book_flight, transfer_to_hotel_assistant],
    prompt="你是一个航班预订助手",
    name="flight_assistant"
)
hotel_assistant = create_react_agent(
    model="anthropic:claude-3-5-sonnet-latest",
    tools=[book_hotel, transfer_to_flight_assistant],
    prompt="你是一个酒店预订助手",
    name="hotel_assistant"
)

swarm = create_swarm(
    agents=[flight_assistant, hotel_assistant],
    default_active_agent="flight_assistant"
).compile()

for chunk in swarm.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "从 BOS 预订到 JFK 的航班和在 McKittrick Hotel 的住宿"
            }
        ]
    }
):
    print(chunk)
    print("\n")

交接

在多代理交互中,一种常见的模式是 交接,其中一个代理将控制权 交给 另一个代理。交接允许您指定以下内容:

  • 目标: 要导航到的目标代理
  • 负载: 要传递给该代理的信息

这由 langgraph-supervisor(监督者将控制权交给单个代理)和 langgraph-swarm(单个代理可以将控制权交给其他代理)使用。

要使用 create_react_agent 实现交接,您需要:

  1. 创建一个特殊工具,可以将控制权转移到不同的代理上

    def transfer_to_bob():
        """Transfer to bob."""
        return Command(
            # 要去的代理(节点)的名称
            goto="bob",
            # 要发送给该代理的数据
            update={"messages": [...]},
            # 告诉 LangGraph 我们需要导航到
            # 父图中的代理节点
            graph=Command.PARENT,
        )
    
  2. 创建具有访问交接工具权限的单个代理:

    flight_assistant = create_react_agent(
        ..., tools=[book_flight, transfer_to_hotel_assistant]
    )
    hotel_assistant = create_react_agent(
        ..., tools=[book_hotel, transfer_to_flight_assistant]
    )
    
  3. 定义一个包含单个代理作为节点的父图:

    from langgraph.graph import StateGraph, MessagesState
    multi_agent_graph = (
        StateGraph(MessagesState)
        .add_node(flight_assistant)
        .add_node(hotel_assistant)
        ...
    )
    

将这些组合在一起,下面是实现一个简单的双代理系统的方法:一个航班预订助手和一个酒店预订助手:

API Reference: tool | InjectedToolCallId | create_react_agent | InjectedState | StateGraph | START | Command

from typing import Annotated
from langchain_core.tools import tool, InjectedToolCallId
from langgraph.prebuilt import create_react_agent, InjectedState
from langgraph.graph import StateGraph, START, MessagesState
from langgraph.types import Command

def create_handoff_tool(*, agent_name: str, description: str | None = None):
    name = f"transfer_to_{agent_name}"
    description = description or f"Transfer to {agent_name}"

    @tool(name, description=description)
    def handoff_tool(
        state: Annotated[MessagesState, InjectedState], # (1)!
        tool_call_id: Annotated[str, InjectedToolCallId],
    ) -> Command:
        tool_message = {
            "role": "tool",
            "content": f"Successfully transferred to {agent_name}",
            "name": name,
            "tool_call_id": tool_call_id,
        }
        return Command(  # (2)!
            goto=agent_name,  # (3)!
            update={"messages": state["messages"] + [tool_message]},  # (4)!
            graph=Command.PARENT,  # (5)!
        )
    return handoff_tool

# 交接
transfer_to_hotel_assistant = create_handoff_tool(
    agent_name="hotel_assistant",
    description="Transfer user to the hotel-booking assistant.",
)
transfer_to_flight_assistant = create_handoff_tool(
    agent_name="flight_assistant",
    description="Transfer user to the flight-booking assistant.",
)

# 简单代理工具
def book_hotel(hotel_name: str):
    """Book a hotel"""
    return f"Successfully booked a stay at {hotel_name}."

def book_flight(from_airport: str, to_airport: str):
    """Book a flight"""
    return f"Successfully booked a flight from {from_airport} to {to_airport}."

# 定义代理
flight_assistant = create_react_agent(
    model="anthropic:claude-3-5-sonnet-latest",
    tools=[book_flight, transfer_to_hotel_assistant],
    prompt="You are a flight booking assistant",
    name="flight_assistant"
)
hotel_assistant = create_react_agent(
    model="anthropic:claude-3-5-sonnet-latest",
    tools=[book_hotel, transfer_to_flight_assistant],
    prompt="You are a hotel booking assistant",
    name="hotel_assistant"
)

# 定义多代理图
multi_agent_graph = (
    StateGraph(MessagesState)
    .add_node(flight_assistant)
    .add_node(hotel_assistant)
    .add_edge(START, "flight_assistant")
    .compile()
)

# 运行多代理图
for chunk in multi_agent_graph.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "book a flight from BOS to JFK and a stay at McKittrick Hotel"
            }
        ]
    }
):
    print(chunk)
    print("\n")
  1. 访问代理的状态
  2. Command 原语允许在一个操作中指定状态更新和节点转换,使其在实现交接时非常有用。
  3. 要交接给的代理或节点的名称。
  4. 将代理的消息添加到父级的**状态**中作为交接的一部分。下一个代理将看到父级状态。
  5. 告诉 LangGraph 我们需要导航到**父级**多代理图中的代理节点。

注意

此交接实现假设:

  • 每个代理在其输入中接收整个消息历史(跨所有代理)的多代理系统
  • 每个代理将其内部消息历史输出到多代理系统的整体消息历史中

查看 LangGraph 的 supervisorswarm 文档,了解如何自定义交接。