跳到内容

子图

子图(subgraph)是一个在另一个图中作为节点使用的——这是封装概念在 LangGraph 中的应用。子图允许您构建包含多个组件的复杂系统,而这些组件本身就是图。

Subgraph

使用子图的一些原因包括:

  • 构建多智能体系统
  • 当您想在多个图中重用一组节点时
  • 当您希望不同的团队独立开发图的不同部分时,您可以将每个部分定义为一个子图。只要遵守子图的接口(输入和输出模式),父图就可以在不了解子图任何细节的情况下进行构建。

添加子图时,主要的问题是父图和子图如何通信,即它们在图执行期间如何相互传递状态。有两种情况:

from langgraph.graph import StateGraph, MessagesState, START

# Subgraph

def call_model(state: MessagesState):
    response = model.invoke(state["messages"])
    return {"messages": response}

subgraph_builder = StateGraph(State)
subgraph_builder.add_node(call_model)
...
subgraph = subgraph_builder.compile()

# Parent graph

builder = StateGraph(State)
builder.add_node("subgraph_node", subgraph)
builder.add_edge(START, "subgraph_node")
graph = builder.compile()
...
graph.invoke({"messages": [{"role": "user", "content": "hi!"}]})
  • 父图和子图有不同的模式(它们的状态模式中没有共享的状态键)。在这种情况下,您必须从父图的一个节点内部调用子图:当父图和子图具有不同的状态模式,并且您需要在调用子图之前或之后转换状态时,这种方法很有用。
from typing_extensions import TypedDict, Annotated
from langchain_core.messages import AnyMessage
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.graph.message import add_messages

class SubgraphMessagesState(TypedDict):
    subgraph_messages: Annotated[list[AnyMessage], add_messages]

# Subgraph

def call_model(state: SubgraphMessagesState):
    response = model.invoke(state["subgraph_messages"])
    return {"subgraph_messages": response}

subgraph_builder = StateGraph(SubgraphMessagesState)
subgraph_builder.add_node("call_model_from_subgraph", call_model)
subgraph_builder.add_edge(START, "call_model_from_subgraph")
...
subgraph = subgraph_builder.compile()

# Parent graph

def call_subgraph(state: MessagesState):
    response = subgraph.invoke({"subgraph_messages": state["messages"]})
    return {"messages": response["subgraph_messages"]}

builder = StateGraph(State)
builder.add_node("subgraph_node", call_subgraph)
builder.add_edge(START, "subgraph_node")
graph = builder.compile()
...
graph.invoke({"messages": [{"role": "user", "content": "hi!"}]})