LangGraph实现多智能体的方法

生活中我们常常需要同时处理多个任务,比如预订旅行时,既要订机票,又要订酒店。如果有一个智能助手能同时帮你搞定这些事情,那该有多方便啊!LangGraph的多智能体系统就能做到这一点。它就像一个超级助手团队,每个成员都有自己的专长,一起合作完成复杂的任务。接下来,我们就来看看这个神奇的多智能体系统是如何工作的。

在LangGraph中,有两种流行的多智能体架构:监督者(Supervisor)和群体(Swarm)。
监督者就像一个团队的领导,它控制所有的通信流程和任务委派,根据当前上下文和任务需求决定调用哪个智能体。
而群体则更像一个自由合作的团队,智能体根据自己的专业领域动态地将控制权交给彼此。

监督者架构

监督者架构中,有一个中央智能体负责协调所有的任务。像一个指挥官,根据任务的需求,将任务分配给不同的智能体。

比如,当你需要预订机票和酒店时,监督者会根据你的需求,将预订机票的任务分配给航班预订智能体,将预订酒店的任务分配给酒店预订智能体。

 pip install langgraph-supervisor
# -*- coding: utf-8 -*-
from langgraph.prebuilt import create_react_agent
from langchain_community.chat_models.tongyi import ChatTongyi

# from langchain_community.llms.tongyi import Tongyi
from langgraph_supervisor import create_supervisor
# pip install langgraph-supervisor

#模型初始化
llm = ChatTongyi(
    model="qwen-max-latest",#qwen-max-latest qwen-plus qwen-turbo
    temperature=0,
    verbose=True,
    )

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}."

# Supervisor监督者 多智能体
#酒店智能体
hotel_assistant = create_react_agent(
    model=llm,
    tools=[book_hotel],
    prompt="你是一位酒店预订助手。",
    name="酒店预订助手"
)

#航班智能体
flight_assistant = create_react_agent(
    model=llm,
    tools=[book_flight],
    prompt="你是一位航班预订助手。",
    name="航班预订助手"
)

supervisor = create_supervisor(
    agents=[flight_assistant,hotel_assistant,],
    model=llm,
    prompt=(
        "你管理着一个酒店预订助手和一个航班预订助手,"
        "给他们分配工作任务。完成任务就行"
    )
).compile()

for chunk in supervisor.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "预订从上海到广州机场的航班" #。预订附近的桔子酒店。
            }
        ]
    }
):
    print(chunk)
    print("\n")

#会调用失败,应该是Tongyi阿里千问对消息tool_calls现在不支持的原因
# 带有角色 "tool" 的消息必须是对带有 "tool_calls" 的前一条消息的响应。

运行结果截图

LangGraph实现多智能体的方法_第1张图片

在这个例子中,监督者会根据用户的输入,将任务分配给相应的智能体。
比如,当用户输入“预订从上海到广州的航班”时,监督者会将这个任务分配给航班预订智能体。

群体架构

与监督者架构不同,群体架构中的智能体可以根据自己的专业领域动态地将控制权交给彼此。这种架构更灵活,智能体之间可以根据任务的需要自由地切换控制权。

pip install langgraph-swarm
# -*- coding: utf-8 -*-
from langgraph.prebuilt import create_react_agent
from langchain_community.chat_models.tongyi import ChatTongyi

# from langchain_community.llms.tongyi import Tongyi
from langgraph_supervisor import create_supervisor
from langgraph.prebuilt import create_react_agent
from langgraph_swarm import create_swarm, create_handoff_tool

#模型初始化
llm = ChatTongyi(
    model="qwen-max-latest",#qwen-max-latest qwen-plus qwen-turbo
    temperature=0,
    verbose=True,
    )

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}."
    
# Swarm群体 多智能体
# pip install langgraph-swarm


transfer_to_hotel_assistant = create_handoff_tool(
    agent_name="酒店预订助手",
    description="将用户转接至酒店预订助手。",
)
transfer_to_flight_assistant = create_handoff_tool(
    agent_name="航班预订助手",
    description="将用户转接至航班预订助手。",
)

flight_assistant = create_react_agent(
    model=llm,
    tools=[book_flight, transfer_to_hotel_assistant],
    prompt="你是一位航班预订助手。",
    name="航班预订助手"
)
hotel_assistant = create_react_agent(
    model=llm,
    tools=[book_hotel, transfer_to_flight_assistant],
    prompt="你是一位酒店预订助手。",
    name="酒店预订助手"
)

swarm = create_swarm(
    agents=[flight_assistant, hotel_assistant],
    default_active_agent="航班预订助手"
).compile()

for chunk in swarm.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "预订从上海到广州机场的航班。预订附近的桔子酒店。" 
            }
        ]
    }
):
    print(chunk)
    print("\n")

运行结果截图(返回结果)

LangGraph实现多智能体的方法_第2张图片

在这个例子中,航班预订智能体和酒店预订智能体可以根据任务的需要自由地切换控制权。

比如,当用户输入“预订从上海到广州的航班。预订附近的桔子酒店。”时,航班预订智能体会先处理预订航班的任务,然后通过转接工具将控制权交给酒店预订智能体,让它处理预订酒店的任务。

交接机制(Handoffs)

在多智能体系统中,智能体之间需要进行有效的协作。
LangGraph通过交接机制(handoffs)来实现这一点。交接机制允许一个智能体将控制权“交接”给另一个智能体,并传递必要的信息。

在多代理交互中,一个常见的模式是交接(handoffs),其中一个代理将控制权“交接”给另一个代理。交接允许你指定:

  • 目标代理(destination):要导航到的目标代理
  • 有效载荷(payload):要传递给该代理的信息

langgraph-supervisor(监督者将控制权交给各个代理)和langgraph-swarm(一个代理可以将控制权交给其他代理)都使用了交接。

要使用 create_react_agent 实现交接,需要创建一个特殊的工具,可以将控制权转移到不同的代理,将这些组合在一起。

以下是如何实现一个包含两个代理的简单多代理系统——一个航班预订助手和一个酒店预订助手:

# -*- coding: utf-8 -*-
from langgraph.prebuilt import create_react_agent
from langchain_community.chat_models.tongyi import ChatTongyi

# from langchain_community.llms.tongyi import Tongyi
from langgraph_supervisor import create_supervisor

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

# pip install langgraph-supervisor

#模型初始化
llm = ChatTongyi(
    model="qwen-max-latest",#qwen-max-latest qwen-plus qwen-turbo
    temperature=0,
    verbose=True,
    )

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

    @tool(name, description=description)
    def handoff_tool(
        state: Annotated[MessagesState, InjectedState],
        tool_call_id: Annotated[str, InjectedToolCallId],
    ) -> Command:
        tool_message = {
            "role": "tool",
            "content": f"已成功转接到 {agent_name}",
            "name": name,
            "tool_call_id": tool_call_id,
        }
        return Command(
            goto=agent_name,
            update={"messages": state["messages"] + [tool_message]},
            graph=Command.PARENT,
        )
    return handoff_tool

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

# 简单代理工具
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=llm,
    tools=[book_flight, transfer_to_hotel_assistant],
    prompt="你是一位航班预订助手。",
    name="航班预订助手"
)
hotel_assistant = create_react_agent(
    model=llm,
    tools=[book_hotel, transfer_to_flight_assistant],
    prompt="你是一位酒店预订助手。",
    name="酒店预订助手"
)

# 定义多代理图
multi_agent_graph = (
    StateGraph(MessagesState)
    .add_node(flight_assistant)
    .add_node(hotel_assistant)
    .add_edge(START, "航班预订助手")
    .compile()
)

# 运行多代理图
for chunk in multi_agent_graph.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "预订从上海到广州机场的航班。并预订附近的桔子酒店。"
            }
        ]
    }
):
    print(chunk)
    print("\n")


运行结果截图(返回结果)

LangGraph实现多智能体的方法_第3张图片

在这个例子中,create_handoff_tool函数创建了一个转接工具,它允许一个智能体将控制权转交给另一个智能体,并传递必要的信息。

总结

LangGraph的多智能体系统通过分工合作的方式,让智能对话变得更高效。无论是监督者架构还是群体架构,都能根据任务的需要灵活地分配任务和切换控制权。

交接机制则让智能体之间的协作更加顺畅。在实际应用中,多智能体系统可以大大简化复杂的任务,让我们的生活更加便捷。

你可能感兴趣的:(LangGraph,python,开发语言,langchain,prompt,AI编程)