LangGraph 多代理架构 —— 父子图之间的消息传递方式

本文重点讲解多代理架构中父图与子图之间的消息(状态)传递方式。


1. 什么是父图?什么是子图?

1.1 概念

  • 父图(Parent Graph):一个已经编译好的 StateGraph,它是"外层"的图,负责整体工作流的编排。它可以像调用普通函数一样,把别的图当作自己的一个节点来调用。
  • 子图(Subgraph):能够作为另一个图中的节点来使用的图。它也是独立定义、独立编译的 StateGraph,有自己的状态模式和节点逻辑。

一句话理解:把一个已经编译好的图,嵌入到另一个已经编译好的图中,并且两个独立图之间的状态可以共享信息 —— 嵌入进去的那个叫子图,容纳它的那个叫父图。

1.2 结构示意(原文图示的文字化表达)

┌────────────────────────── ParentGraph(父图) ──────────────────────────┐
│                                                                        │
│   ┌─── SubGraph 1 ───┐         ┌─── SubGraph 2 ───┐                    │
│   │  ●───●           │         │  ●───●           │                    │
│   │   \ /  Sub State1│         │   \ /  Sub State2│                    │
│   │    ●             │         │    ●             │                    │
│   └──────────────────┘         └──────────────────┘                    │
│              ╲                       ╱                                  │
│               ╲                     ╱                                   │
│                ── Parent State ──                                       │
│                        ╱                                               │
│                       ╱                                                │
│   ┌─── SubGraph 3 ───┐                                                 │
│   │  ●───●           │                                                 │
│   │   \ /  Sub State3│                                                 │
│   │    ●             │                                                 │
│   └──────────────────┘                                                 │
└────────────────────────────────────────────────────────────────────────┘
  • 父图有一个全局的 Parent State(父图状态);
  • 每个子图内部拥有自己独立的 Sub State(子图状态);
  • 子图之间、子图与父图之间是否"互通",取决于双方状态中是否有共同的键(key/通道)——这正是本文的核心。

1.3 为什么需要子图?

添加子图主要解决的问题是:多个 Single-Agent 之间如何通信,即它们如何在图执行期间彼此传递状态。这是构建多代理系统(Multi-Agent System)的底层基础设施:只要遵守子图的接口(输入/输出模式)规范,子图中定义的状态就可以在父图中使用,各代理之间就能顺畅"对话"。

1.4 使用场景

  • 多代理系统:每个 Agent 是一个独立子图,父图负责调度和汇总;
  • 复杂任务拆分:把一个大的工作流按职责切成多个可独立测试、独立复用的小图;
  • 团队协作开发:不同子图由不同人维护,只要约定好状态接口即可拼装。

2. 父图和子图之间消息(状态)的传递方式

父、子图之间传递消息,本质上就是状态(State)中键值对的读写。根据父、子图状态模式中是否存在共同的键(通道),分为两种情况:

情况传递方式特点
情况一:父、子图的状态模式中有共同的键LangGraph 自动按同名键进行状态共享零胶水代码,直接 add_node(编译后的子图) 即可
情况二:父、子图的状态模式中没有共同的键需要自己写一个"中间节点函数"做状态转换灵活性最高,两边完全解耦

2.1 情况一:父、子图的状态模式中有共同的键

原理(通俗版):LangGraph 在执行到子图节点时,会把父图当前状态中与子图状态同名的键自动"拷贝"进子图作为初始状态;子图执行完毕后,再把子图状态中同名的键的更新值回写到父图状态里。相当于同名键就是父子图之间的"公共频道"。

结构示意:

┌────────────── ParentGraph ──────────────────────────────────┐
│                                                             │
│   父图状态: { user_input: str,                              │
│               final_answer: str }  ←── 共享键(绿色)        │
│                │                                            │
│                └──────▶ ┌──── SubGraph ────┐                │
│                         │   ●───●          │                │
│                         │    \ /           │                │
│                         │     ●            │                │
│                         │                  │                │
│                         │ 子图状态:        │                │
│                         │ { final_answer: str } ← 共享键    │
│                         │ { summary_answer: str } ← 子图独享│
│                         └──────────────────┘                │
└─────────────────────────────────────────────────────────────┘

要点:

  1. 子图状态中的 final_answer 与父图状态中的 final_answer 名字相同,即为共享通道;
  2. 子图中的 summary_answer 是子图独享的内部状态,父图看不到它;
  3. 数据隔离与信息共享的平衡:共享键用于通信,独享键用于子图内部逻辑。

实现步骤(条理化):

  • Step 1:定义并实例化大模型;
  • Step 2:定义父图的状态模式;
  • Step 3:定义父图的节点逻辑;
  • Step 4:定义子图的状态模式(包含与父图同名的键 + 子图独享的键);
  • Step 5:定义子图的节点逻辑;
  • Step 6:构建子图流程图并 compile() 编译;
  • Step 7:构建父图流程图,用 .add_node("节点名", 编译后的子图) 把子图作为一个普通节点加入父图;
  • Step 8:编译父图、可视化、运行验证。

完整代码见第 3.1 节案例一。

2.2 情况二:父、子图的状态模式中没有共同的键

原理(通俗版):如果父图和子图的状态设计完全不同(没有任何同名键),LangGraph 无法自动"对接"。此时需要手动写一个"桥梁节点"函数,它做的事情只有两步:

  1. 进入子图前:把父图状态转换成子图状态(构造符合子图模式入参的 dict,调用 subgraph.invoke(...));
  2. 从子图返回后:把子图的输出转换回父图状态(以父图键名 return,交给父图合并)。

结构示意:

┌────────────── ParentGraph ──────────────────────────────────┐
│                                                             │
│   父图状态: { user_input: str,                              │
│               final_answer: str }   (无任何同名键)         │
│                │                                            │
│                │ ①转换: final_answer ──▶ response_answer    │
│                ▼                                            │
│           ┌──── SubGraph ────┐                              │
│           │   ●───●          │                              │
│           │    \ /           │                              │
│           │     ●            │                              │
│           │ 子图状态:        │                              │
│           │ { response_answer: str } ← 独享                  │
│           │ { summary_answer:  str } ← 独享                  │
│           │ { score:           str } ← 独享                  │
│           └──────────────────┘                              │
│                │                                            │
│                │ ②转换: score ──▶ final_answer              │
│                ▼                                            │
│           父图继续运行                                       │
└─────────────────────────────────────────────────────────────┘

要点:

  1. 子图状态完全独立于父图状态,两边没有任何重叠的键——这是最常见的、灵活性最高的方式;
  2. 关键在于那个"桥梁节点":调用子图之前把父图输入转换为子图状态,返回之前把子图结果转换回父图状态;
  3. 在父图中注册的不再是编译后的子图本身,而是这个桥梁节点函数。

实现步骤(条理化):

  • Step 1:定义并实例化大模型;
  • Step 2:定义父图的状态模式和父图节点;
  • Step 3:定义子图的状态模式(全部是子图独享的键)和子图节点;
  • Step 4:构建子图流程图并编译;
  • Step 5:定义桥梁节点函数:内部完成"父状态 → 子状态 → 调用子图 → 子结果 → 父状态"的转换;
  • Step 6:构建父图,把桥梁函数(而非编译后的子图)作为节点加入父图;
  • Step 7:编译父图、运行验证。

完整代码见第 3.2 节案例二。


3. 父子图之间的消息传递案例解析

两个案例共用同一个业务背景:一个"回答 + 精简总结 + 打分"的评分系统。

3.1 案例一:父、子图状态有共同的键

需求
  • 父图:接收用户输入,调用大模型生成一份详细的回答(存入 final_answer);
  • 子图:拿到父图的回答后做两件事——① 把回答精简为不超过 50 词的总结;② 根据"完整回答 + 总结"给出 1~10 的综合评分;
  • 评分结果最终写回父图的共享键 final_answer。
分析如何实现
  • 共享键设计:父图与子图的状态中都定义 final_answer,父图生成的回答通过这个键自动流入子图;子图打完分后把分数写回 final_answer,父图状态随之更新;
  • 独享键设计:summary_answer 只在子图内部流转(总结 → 评分),父图不需要关心;
  • 关键动作:把编译后的子图直接 add_node 进父图,无需任何转换代码。
Step 1. 实例化大模型(deepseek-chat)
import os
from langchain_openai import ChatOpenAI

# deepseek-chat 兼容 OpenAI 接口协议,配置 DeepSeek 的 API Key 与 base_url 即可
llm = ChatOpenAI(
    model="deepseek-chat",                    # 使用 DeepSeek 对话模型
    api_key=os.getenv("DEEPSEEK_API_KEY"),    # 从环境变量读取 API Key
    base_url="https://api.deepseek.com/v1",   # DeepSeek 的 OpenAI 兼容接口地址
    temperature=0,                            # temperature=0 保证输出稳定可复现
)
Step 2. 定义父图的状态模式
from typing import TypedDict

# 定义父图中的状态
class ParentState(TypedDict):
    user_input: str      # 用来接收用户的输入
    final_answer: str    # 用来存储大模型针对用户输入的响应(与子图共享的键)
Step 3. 定义父图的节点逻辑
def parent_node(state: ParentState):
    # 用大模型处理用户输入,生成详细响应
    response = llm.invoke(state["user_input"])
    # 更新父图共享键 final_answer,稍后会被子图读取
    return {"final_answer": response}
Step 4. 定义子图的状态模式
# 定义子图中的状态
class SubgraphState(TypedDict):
    # 这个 key 与父图(ParentState)同名共享,是父子图之间的"通信频道"
    final_answer: str
    # 这个 key 是子图独享的,父图不可见
    summary_answer: str
Step 5. 定义子图的节点逻辑
from langchain_core.messages import SystemMessage, HumanMessage

# 子图节点1:把父图传来的完整回答精简为 50 词以内的总结
def subgraph_node_1(state: SubgraphState):
    system_prompt = """
    Please summary the content you receive to 50 words or less
    """
    messages = state["final_answer"]  # 读取共享键,拿到父图传递过来的响应
    messages = [SystemMessage(content=system_prompt)] \
               + [HumanMessage(content=messages.content)]
    response = llm.invoke(messages)
    # 写入子图独享键 summary_answer,供节点2使用
    return {"summary_answer": response}

# 子图节点2:根据完整回答及其总结进行综合评分(1~10 分)
def subgraph_node_2(state: SubgraphState):
    messages = f"""
    This is the full content of what you received:{state["final_answer"]} \n
    This information is summarized for the full content:{state["summary_answer"]} 
    Please rate the text and summary information, returning a scale of 1 to 10. 
    Note: Only the score value needs to be returned.
    """
    response = llm.invoke([HumanMessage(content=messages)])
    # 把评分写回共享键 final_answer,父图状态会随之更新
    return {"final_answer": response.content}
Step 6. 定义子图的图结构并编译
from langgraph.graph import START, StateGraph

# 创建子图构建器,状态模式为 SubgraphState
subgraph_builder = StateGraph(SubgraphState)
subgraph_builder.add_node(subgraph_node_1)              # 添加总结节点
subgraph_builder.add_node(subgraph_node_2)              # 添加评分节点
subgraph_builder.add_edge(START, "subgraph_node_1")     # 入口 → 节点1
subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")  # 节点1 → 节点2
subgraph = subgraph_builder.compile()                   # 编译成可运行的子图
Step 7. 定义父图的图结构,并将编译后的子图作为节点加入
# 创建父图构建器,状态模式为 ParentState
builder = StateGraph(ParentState)
builder.add_node("node_1", parent_node)  # 普通函数节点:生成回答

# 核心一步:将编译后的子图作为一个普通节点加入父图
# LangGraph 会自动按同名键 final_answer 完成父子图之间的状态传递
builder.add_node("node_2", subgraph)
builder.add_edge(START, "node_1")        # 入口 → 节点1
builder.add_edge("node_1", "node_2")     # 节点1(父)→ 节点2(子图)
graph = builder.compile()                # 编译父图
Step 8. 运行验证(流式输出)
# stream_mode='values':每执行完一个节点就输出一次当前完整状态
async for chunk in graph.astream(
    {"user_input": "我现在想学习大模型,应该关注哪些技术?"},
    stream_mode="values",
):
    print(chunk)

# 输出演变过程(节选):
# 1. {'user_input': '我现在想学习大模型,应该关注哪些技术?'}
# 2. {'user_input': ..., 'final_answer': AIMessage(content='在学习大模型……(详细回答)')}
# 3. {'user_input': ..., 'final_answer': '9'}   ← 子图把评分写回了共享键

如果想进一步查看子图内部的状态变化,可在流式传输时指定 subgraphs=True:

# subgraphs=True:输出中会带上子图的状态快照,
# 每个元素是 (命名空间路径, 状态字典),命名空间能区分输出来自父图还是子图
async for chunk in graph.astream(
    {"user_input": "如何理解RAG?"},
    stream_mode="values",
    subgraphs=True,
):
    print(chunk)

# 输出(节选):
# ((), {'user_input': '如何理解RAG?'})                    ← 父图命名空间为空元组
# ((), {..., 'final_answer': AIMessage(...)})             ← 父图节点1生成回答
# (('node_2:xxx',), {'final_answer': AIMessage(...)})     ← 进入子图,共享键带入
# (('node_2:xxx',), {..., 'summary_answer': AIMessage(...)})  ← 子图独享键出现
# (('node_2:xxx',), {'final_answer': '9', ...})           ← 子图写回评分
# ((), {'user_input': ..., 'final_answer': '9'})          ← 回到父图,评分生效
案例一小结

父图与子图借助共享状态键 final_answer 完成了通信:父图"写"、子图"读"完成总结与评分,子图再把结果"写"回同一键。这是多代理架构中最常见的底层通信模式,设计工作流时的核心问题就是:如何通过父图的全局状态键,让各子图(子代理)有效交互和信息传递。

3.2 案例二:父、子图状态没有共同的键

需求
  • 业务功能与案例一相同(生成回答 → 总结 → 评分),但要求父图与子图完全解耦:
    • 子图使用自己的一套状态键(response_answer / summary_answer / score),与父图的 final_answer 没有任何同名键;
    • 父图不关心子图内部实现,将来可以随时换成别的子图。
分析如何实现
  • 既然没有同名键,LangGraph 无法自动对接,需要写一个桥梁节点函数 parent_node_2:
    • 第一步(入):从父图状态取出 final_answer,包装成子图认识的入参 {"response_answer": ...} 调用子图;
    • 第二步(出):从子图返回值中取出 score,以父图键名 final_answer 返回;
  • 父图中注册的是这个桥梁函数,而不是编译后的子图。
Step 1. 实例化大模型(deepseek-chat)
from langchain_openai import ChatOpenAI

# 与案例一相同,使用 deepseek-chat
llm = ChatOpenAI(
    model="deepseek-chat",
    api_key=os.getenv("DEEPSEEK_API_KEY"),
    base_url="https://api.deepseek.com/v1",
    temperature=0,
)
Step 2. 定义父图的状态和节点(与案例一相同)
from typing import TypedDict

# 定义父图中的状态
class ParentState(TypedDict):
    user_input: str      # 接收用户的输入
    final_answer: str    # 存储大模型针对用户输入的响应

def parent_node_1(state: ParentState):
    # 调用大模型生成回答
    response = llm.invoke(state["user_input"])
    return {"final_answer": response}
Step 3. 定义子图的状态与节点(键名与父图完全不同)
from langchain_core.messages import SystemMessage, HumanMessage

# 定义子图中的状态 —— 三个 key 全部是子图独享的,与父图没有任何同名键
class SubgraphState(TypedDict):
    response_answer: str   # 子图自己命名的"待处理回答"键
    summary_answer: str    # 总结键
    score: str             # 评分键

# 节点1:对"待处理回答"做摘要
def subgraph_node_1(state: SubgraphState):
    system_prompt = """
    Please summary the content you receive to 50 words or less
    """
    # 注意:这里读取的是子图自己的键 response_answer
    messages = state["response_answer"]
    messages = [SystemMessage(content=system_prompt)] \
               + [HumanMessage(content=messages.content)]
    response = llm.invoke(messages)
    return {"summary_answer": response}

# 节点2:根据完整内容与总结打分
def subgraph_node_2(state: SubgraphState):
    messages = f"""
    This is the full content of what you received:{state["response_answer"]} \n
    This information is summarized for the full content:{state["summary_answer"]} 
    Please rate the text and summary information, returning a scale of 1 to 10. 
    Note: Only the score value needs to be returned.
    """
    response = llm.invoke([HumanMessage(content=messages)])
    return {"score": response.content}   # 结果写入子图自己的 score 键
Step 4. 构建并编译子图(正常流程)
subgraph_builder = StateGraph(SubgraphState)
subgraph_builder.add_node(subgraph_node_1)
subgraph_builder.add_node(subgraph_node_2)
subgraph_builder.add_edge(START, "subgraph_node_1")
subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")
subgraph = subgraph_builder.compile()
Step 5. 定义"桥梁节点"——父子图通信的关键
def parent_node_2(state: ParentState):
    # 第一步(进入子图前):把父图状态转换为子图状态
    # 父图的 final_answer ──映射──▶ 子图的 response_answer
    response = subgraph.invoke({"response_answer": state["final_answer"]})
    # 第二步(从子图返回后):把子图状态转换回父图状态
    # 子图的 score ──映射──▶ 父图的 final_answer
    return {"final_answer": response["score"]}
Step 6. 构建父图:注册的是桥梁函数而非子图本身
builder = StateGraph(ParentState)
builder.add_node("node_1", parent_node_1)   # 父图节点1:生成回答

# 注意:这里加入的不是编译后的子图,而是调用子图的桥梁函数 parent_node_2
builder.add_node("node_2", parent_node_2)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", "node_2")
graph = builder.compile()
Step 7. 运行验证
async for chunk in graph.astream(
    {"user_input": "我现在想学习大模型,应该关注哪些技术?"},
    stream_mode="values",
):
    print(chunk)

# 输出演变过程(节选):
# 1. {'user_input': '我现在想学习大模型,应该关注哪些技术?'}
# 2. {'user_input': ..., 'final_answer': AIMessage(content='……(详细回答)')}
# 3. {'user_input': ..., 'final_answer': '8'}   ← 桥梁节点把子图的 score 映射回 final_answer
# 也可以用 subgraphs=True 捕获子图内部状态并读取最终评分
all_chunk = []
async for chunk in graph.astream(
    {"user_input": "什么是机器学习?"},
    stream_mode="values",
    subgraphs=True,
):
    all_chunk.append(chunk)

all_chunk[-1][1]["final_answer"]   # 输出:'8'(最终评分)
案例二小结

subgraph state 与 parent graph state 完全独立、没有任何重叠键。通信全部依靠桥梁节点 parent_node_2:调用子图之前把父图输入转换为子图状态,返回之前把子图输出转换回父图状态。这种方式灵活性最高,父图与子图可以彻底解耦、各自独立演进。


4. 两种方式对比总结

维度有共同的键没有共同的键
注册方式builder.add_node("node_2", 编译后的子图)builder.add_node("node_2", 桥梁函数)
状态传递LangGraph 按同名键自动共享/回写桥梁函数手动完成双向转换
耦合程度父子图状态有交集,需约定键名完全解耦,互不感知
灵活性较高(改键名即影响通信)最高(两边状态可任意设计)
适用场景状态键设计统一、追求简洁父子图架构差异大、需要严格隔离

5. 总结

  1. 父图是承载整体工作流的外层图;子图是被当作节点嵌入父图的内层图。子图是构建 LangGraph 多代理系统的基础——每个 Agent 都可以是独立编译的子图。
  2. 父子图之间的消息传递本质是状态的读写,按是否存在共同的键分为两种方式:
    • 有共同键:同名键就是"公共频道",LangGraph 自动完成父子图之间的状态带入与回写,只需把编译后的子图 add_node 进父图即可;
    • 没有共同键:需要自定义一个桥梁节点函数,在调用子图前把父状态转成子状态、在返回前把子结果转回父状态,实现完全解耦的通信。
  3. 无论哪种方式,理解了状态的传递规则就具备了构建多代理系统的必要条件:设计好父图全局状态键与各子图(子代理)之间的交互接口,是搭好多代理架构工作流的核心。
Logo

一站式 AI 云服务平台

更多推荐