多智能体系统¶
智能体是一个使用 LLM 来决定应用程序控制流的系统。随着您开发这些系统,它们可能会随着时间的推移变得更加复杂,使其更难管理和扩展。例如,您可能会遇到以下问题
- 智能体拥有太多工具可供使用,并且在决定接下来调用哪个工具时做出错误的决策
- 上下文变得过于复杂,单个智能体无法跟踪
- 系统中需要多个专业领域(例如,规划器、研究员、数学专家等)
为了解决这些问题,您可以考虑将您的应用程序分解为多个更小、独立的智能体,并将它们组合成一个 多智能体系统。这些独立的智能体可以像提示和 LLM 调用一样简单,或者像 ReAct 智能体(以及更多!)一样复杂。
使用多智能体系统的主要好处是
- 模块化:独立的智能体使开发、测试和维护智能体系统更容易。
- 专业化:您可以创建专注于特定领域的专家智能体,这有助于提高整体系统性能。
- 控制:您可以显式控制智能体如何通信(而不是依赖于函数调用)。
多智能体架构¶
有几种方法可以在多智能体系统中连接智能体
- 网络:每个智能体都可以与其他每个智能体通信。任何智能体都可以决定接下来调用哪个其他智能体。
- 主管:每个智能体都与一个主管智能体通信。主管智能体决定接下来应该调用哪个智能体。
- 主管(工具调用):这是主管架构的一个特殊情况。单个智能体可以表示为工具。在这种情况下,主管智能体使用工具调用 LLM 来决定调用哪个智能体工具,以及传递给这些智能体的参数。
- 分层:您可以定义具有主管的主管的多智能体系统。这是主管架构的推广,并允许更复杂的控制流。
- 自定义多智能体工作流:每个智能体仅与一部分智能体通信。部分流程是确定性的,只有一些智能体可以决定接下来调用哪个其他智能体。
移交¶
在多智能体架构中,智能体可以表示为图节点。每个智能体节点执行其步骤并决定是完成执行还是路由到另一个智能体,包括可能路由到自身(例如,在循环中运行)。多智能体交互中的一个常见模式是移交,其中一个智能体将控制权移交给另一个智能体。移交允许您指定
- 目标:要导航到的目标智能体(例如,要前往的节点的名称)
- 有效负载:传递给该智能体的信息(例如,状态更新)
为了在 LangGraph 中实现移交,智能体节点可以返回 Command
对象,该对象允许您组合控制流和状态更新
def agent(state) -> Command[Literal["agent", "another_agent"]]:
# the condition for routing/halting can be anything, e.g. LLM tool call / structured output, etc.
goto = get_next_agent(...) # 'agent' / 'another_agent'
return Command(
# Specify which agent to call next
goto=goto,
# Update the graph state
update={"my_state_key": "my_state_value"}
)
在更复杂的场景中,每个智能体节点本身就是一个图(即,子图),一个智能体子图中的节点可能想要导航到不同的智能体。例如,如果您有两个智能体,alice
和 bob
(父图中的子图节点),并且 alice
需要导航到 bob
,您可以在 Command
对象中设置 graph=Command.PARENT
def some_node_inside_alice(state)
return Command(
goto="bob",
update={"my_state_key": "my_state_value"},
# specify which graph to navigate to (defaults to the current graph)
graph=Command.PARENT,
)
注意
如果您需要支持使用 Command(graph=Command.PARENT)
进行通信的子图的可视化,您需要使用带有 Command
注释的节点函数来包装它们,例如,而不是这样
您需要这样做
作为工具的移交¶
最常见的智能体类型之一是 ReAct 风格的工具调用智能体。对于这些类型的智能体,常见的模式是将移交包装在工具调用中,例如
def transfer_to_bob(state):
"""Transfer to bob."""
return Command(
goto="bob",
update={"my_state_key": "my_state_value"},
graph=Command.PARENT,
)
这是从工具更新图状态的一个特殊情况,其中除了状态更新之外,还包括控制流。
重要提示
如果您想使用返回 Command
的工具,您可以选择使用预构建的 create_react_agent
/ ToolNode
组件,或者实现您自己的工具执行节点,该节点收集工具返回的 Command
对象并返回它们的列表,例如
现在让我们仔细看看不同的多智能体架构。
网络¶
在这种架构中,智能体被定义为图节点。每个智能体都可以与其他每个智能体通信(多对多连接),并且可以决定接下来调用哪个智能体。这种架构适用于没有明确的智能体层次结构或智能体应该被调用的特定顺序的问题。
from typing import Literal
from langchain_openai import ChatOpenAI
from langgraph.types import Command
from langgraph.graph import StateGraph, MessagesState, START, END
model = ChatOpenAI()
def agent_1(state: MessagesState) -> Command[Literal["agent_2", "agent_3", END]]:
# you can pass relevant parts of the state to the LLM (e.g., state["messages"])
# to determine which agent to call next. a common pattern is to call the model
# with a structured output (e.g. force it to return an output with a "next_agent" field)
response = model.invoke(...)
# route to one of the agents or exit based on the LLM's decision
# if the LLM returns "__end__", the graph will finish execution
return Command(
goto=response["next_agent"],
update={"messages": [response["content"]]},
)
def agent_2(state: MessagesState) -> Command[Literal["agent_1", "agent_3", END]]:
response = model.invoke(...)
return Command(
goto=response["next_agent"],
update={"messages": [response["content"]]},
)
def agent_3(state: MessagesState) -> Command[Literal["agent_1", "agent_2", END]]:
...
return Command(
goto=response["next_agent"],
update={"messages": [response["content"]]},
)
builder = StateGraph(MessagesState)
builder.add_node(agent_1)
builder.add_node(agent_2)
builder.add_node(agent_3)
builder.add_edge(START, "agent_1")
network = builder.compile()
API 参考: ChatOpenAI | Command | StateGraph | START | END
主管¶
在这种架构中,我们将智能体定义为节点,并添加一个主管节点 (LLM),该节点决定接下来应该调用哪个智能体节点。我们使用 Command
根据主管的决策将执行路由到适当的智能体节点。这种架构也很适合并行运行多个智能体或使用 map-reduce 模式。
from typing import Literal
from langchain_openai import ChatOpenAI
from langgraph.types import Command
from langgraph.graph import StateGraph, MessagesState, START, END
model = ChatOpenAI()
def supervisor(state: MessagesState) -> Command[Literal["agent_1", "agent_2", END]]:
# you can pass relevant parts of the state to the LLM (e.g., state["messages"])
# to determine which agent to call next. a common pattern is to call the model
# with a structured output (e.g. force it to return an output with a "next_agent" field)
response = model.invoke(...)
# route to one of the agents or exit based on the supervisor's decision
# if the supervisor returns "__end__", the graph will finish execution
return Command(goto=response["next_agent"])
def agent_1(state: MessagesState) -> Command[Literal["supervisor"]]:
# you can pass relevant parts of the state to the LLM (e.g., state["messages"])
# and add any additional logic (different models, custom prompts, structured output, etc.)
response = model.invoke(...)
return Command(
goto="supervisor",
update={"messages": [response]},
)
def agent_2(state: MessagesState) -> Command[Literal["supervisor"]]:
response = model.invoke(...)
return Command(
goto="supervisor",
update={"messages": [response]},
)
builder = StateGraph(MessagesState)
builder.add_node(supervisor)
builder.add_node(agent_1)
builder.add_node(agent_2)
builder.add_edge(START, "supervisor")
supervisor = builder.compile()
API 参考: ChatOpenAI | Command | StateGraph | START | END
查看此教程,了解主管多智能体架构的示例。
主管(工具调用)¶
在这种主管架构的变体中,我们将单个智能体定义为工具,并在主管节点中使用工具调用 LLM。这可以实现为具有两个节点的 ReAct 风格的智能体——一个 LLM 节点(主管)和一个执行工具(在这种情况下为智能体)的工具调用节点。
from typing import Annotated
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import InjectedState, create_react_agent
model = ChatOpenAI()
# this is the agent function that will be called as tool
# notice that you can pass the state to the tool via InjectedState annotation
def agent_1(state: Annotated[dict, InjectedState]):
# you can pass relevant parts of the state to the LLM (e.g., state["messages"])
# and add any additional logic (different models, custom prompts, structured output, etc.)
response = model.invoke(...)
# return the LLM response as a string (expected tool response format)
# this will be automatically turned to ToolMessage
# by the prebuilt create_react_agent (supervisor)
return response.content
def agent_2(state: Annotated[dict, InjectedState]):
response = model.invoke(...)
return response.content
tools = [agent_1, agent_2]
# the simplest way to build a supervisor w/ tool-calling is to use prebuilt ReAct agent graph
# that consists of a tool-calling LLM node (i.e. supervisor) and a tool-executing node
supervisor = create_react_agent(model, tools)
API 参考: ChatOpenAI | InjectedState | create_react_agent
分层¶
当您向系统中添加更多智能体时,主管可能变得难以管理所有这些智能体。主管可能开始对接下来调用哪个智能体做出错误的决策,上下文可能变得过于复杂,单个主管无法跟踪。换句话说,您最终会遇到与最初推动多智能体架构相同的问题。
为了解决这个问题,您可以分层设计您的系统。例如,您可以创建由各个主管管理的独立的、专门的智能体团队,以及一个顶级主管来管理这些团队。
from typing import Literal
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.types import Command
model = ChatOpenAI()
# define team 1 (same as the single supervisor example above)
def team_1_supervisor(state: MessagesState) -> Command[Literal["team_1_agent_1", "team_1_agent_2", END]]:
response = model.invoke(...)
return Command(goto=response["next_agent"])
def team_1_agent_1(state: MessagesState) -> Command[Literal["team_1_supervisor"]]:
response = model.invoke(...)
return Command(goto="team_1_supervisor", update={"messages": [response]})
def team_1_agent_2(state: MessagesState) -> Command[Literal["team_1_supervisor"]]:
response = model.invoke(...)
return Command(goto="team_1_supervisor", update={"messages": [response]})
team_1_builder = StateGraph(Team1State)
team_1_builder.add_node(team_1_supervisor)
team_1_builder.add_node(team_1_agent_1)
team_1_builder.add_node(team_1_agent_2)
team_1_builder.add_edge(START, "team_1_supervisor")
team_1_graph = team_1_builder.compile()
# define team 2 (same as the single supervisor example above)
class Team2State(MessagesState):
next: Literal["team_2_agent_1", "team_2_agent_2", "__end__"]
def team_2_supervisor(state: Team2State):
...
def team_2_agent_1(state: Team2State):
...
def team_2_agent_2(state: Team2State):
...
team_2_builder = StateGraph(Team2State)
...
team_2_graph = team_2_builder.compile()
# define top-level supervisor
builder = StateGraph(MessagesState)
def top_level_supervisor(state: MessagesState) -> Command[Literal["team_1_graph", "team_2_graph", END]]:
# you can pass relevant parts of the state to the LLM (e.g., state["messages"])
# to determine which team to call next. a common pattern is to call the model
# with a structured output (e.g. force it to return an output with a "next_team" field)
response = model.invoke(...)
# route to one of the teams or exit based on the supervisor's decision
# if the supervisor returns "__end__", the graph will finish execution
return Command(goto=response["next_team"])
builder = StateGraph(MessagesState)
builder.add_node(top_level_supervisor)
builder.add_node("team_1_graph", team_1_graph)
builder.add_node("team_2_graph", team_2_graph)
builder.add_edge(START, "top_level_supervisor")
builder.add_edge("team_1_graph", "top_level_supervisor")
builder.add_edge("team_2_graph", "top_level_supervisor")
graph = builder.compile()
API 参考: ChatOpenAI | StateGraph | START | END | Command
自定义多智能体工作流¶
在这种架构中,我们将单个智能体添加为图节点,并提前在自定义工作流中定义调用智能体的顺序。在 LangGraph 中,工作流可以通过两种方式定义
-
显式控制流(普通边):LangGraph 允许您通过 普通图边 显式定义应用程序的控制流(即智能体如何通信的顺序)。这是上述架构中最具确定性的变体——我们始终提前知道接下来将调用哪个智能体。
-
动态控制流 (Command):在 LangGraph 中,您可以允许 LLM 决定应用程序控制流的部分内容。这可以通过使用
Command
来实现。其中的一个特殊情况是 主管工具调用 架构。在这种情况下,为主管智能体提供动力的工具调用 LLM 将决定调用工具(智能体)的顺序。
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, MessagesState, START
model = ChatOpenAI()
def agent_1(state: MessagesState):
response = model.invoke(...)
return {"messages": [response]}
def agent_2(state: MessagesState):
response = model.invoke(...)
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node(agent_1)
builder.add_node(agent_2)
# define the flow explicitly
builder.add_edge(START, "agent_1")
builder.add_edge("agent_1", "agent_2")
API 参考: ChatOpenAI | StateGraph | START
智能体之间的通信¶
构建多智能体系统时,最重要的事情是弄清楚智能体如何通信。有几个不同的考虑因素
- 智能体是通过图状态还是通过工具调用进行通信?
- 如果两个智能体具有不同的状态模式怎么办?
- 如何通过共享消息列表进行通信?
图状态 vs 工具调用¶
在智能体之间传递的“有效负载”是什么?在上面讨论的大多数架构中,智能体通过图状态进行通信。在带有工具调用的主管的情况下,有效负载是工具调用参数。
图状态¶
为了通过图状态进行通信,单个智能体需要定义为图节点。这些可以作为函数或作为整个子图添加。在图执行的每个步骤中,智能体节点接收图的当前状态,执行智能体代码,然后将更新后的状态传递到下一个节点。
通常,智能体节点共享一个状态模式。但是,您可能希望设计具有不同状态模式的智能体节点。
不同的状态模式¶
智能体可能需要具有与其余智能体不同的状态模式。例如,搜索智能体可能只需要跟踪查询和检索到的文档。在 LangGraph 中,有两种方法可以实现这一点
- 定义具有单独状态模式的 子图 智能体。如果子图和父图之间没有共享状态键(通道),则添加输入/输出转换非常重要,以便父图知道如何与子图通信。
- 定义具有 私有输入状态模式 的智能体节点函数,该模式与整体图状态模式不同。这允许传递仅执行该特定智能体所需的信息。
共享消息列表¶
智能体进行通信的最常见方式是通过共享状态通道,通常是消息列表。这假设状态中始终存在至少一个由智能体共享的通道(键)。当通过共享消息列表进行通信时,还有一个额外的考虑因素:智能体应该共享其思维过程的完整历史记录,还是仅共享最终结果?
共享完整历史记录¶
智能体可以与其他所有智能体共享其思维过程的完整历史记录(即“草稿纸”)。这个“草稿纸”通常看起来像一个 消息列表。共享完整思维过程的好处是,它可能有助于其他智能体做出更好的决策,并提高整个系统的推理能力。缺点是,随着智能体的数量及其复杂性的增加,“草稿纸”将迅速增长,并且可能需要额外的 内存管理 策略。
共享最终结果¶
智能体可以拥有自己的私有“草稿纸”,并且仅与其余智能体共享最终结果。这种方法可能更适用于具有许多智能体或更复杂的智能体的系统。在这种情况下,您需要定义具有不同状态模式的智能体
对于作为工具调用的智能体,主管根据工具模式确定输入。此外,LangGraph 允许在运行时将 状态传递 给单个工具,因此如果需要,下属智能体可以访问父状态。