LangGraph 源码学习总结 3-单结点图的执行分析

把 LangGraph 的"三步"一次看个够

------从官方文档、示例到源码的完整拆解

一、Pregel 的"三步"模型

官方给出的执行模型如下,关键模型是 Plan、Execution、Update.核心概念有 Actors、Channels

python 复制代码
"""Pregel manages the runtime behavior for LangGraph applications.

## Overview

Pregel combines [**actors**](https://en.wikipedia.org/wiki/Actor_model)
and **channels** into a single application.
**Actors** read data from channels and write data to channels.
Pregel organizes the execution of the application into multiple steps,
following the **Pregel Algorithm**/**Bulk Synchronous Parallel** model.

Each step consists of three phases:

- **Plan**: Determine which **actors** to execute in this step. For example,
    in the first step, select the **actors** that subscribe to the special
    **input** channels; in subsequent steps,
    select the **actors** that subscribe to channels updated in the previous step.
- **Execution**: Execute all selected **actors** in parallel,
    until all complete, or one fails, or a timeout is reached. During this
    phase, channel updates are invisible to actors until the next step.
- **Update**: Update the channels with the values written by the **actors**
    in this step.

Repeat until no **actors** are selected for execution, or a maximum number of
steps is reached.

## Actors

An **actor** is a `PregelNode`.
It subscribes to channels, reads data from them, and writes data to them.
It can be thought of as an **actor** in the Pregel algorithm.
`PregelNodes` implement LangChain's
Runnable interface.

## Channels

Channels are used to communicate between actors (`PregelNodes`).
Each channel has a value type, an update type, and an update function -- which
takes a sequence of updates and
modifies the stored value. Channels can be used to send data from one chain to
another, or to send data from a chain to itself in a future step. LangGraph
provides a number of built-in channels:

### Basic channels: LastValue and Topic

- `LastValue`: The default channel, stores the last value sent to the channel,
   useful for input and output values, or for sending data from one step to the next
- `Topic`: A configurable PubSub Topic, useful for sending multiple values
   between *actors*, or for accumulating output. Can be configured to deduplicate
   values, and/or to accumulate values over the course of multiple steps.

### Advanced channels: Context and BinaryOperatorAggregate

- `Context`: exposes the value of a context manager, managing its lifecycle.
  Useful for accessing external resources that require setup and/or teardown. eg.
  `client = Context(httpx.Client)`
- `BinaryOperatorAggregate`: stores a persistent value, updated by applying
   a binary operator to the current value and each update
   sent to the channel, useful for computing aggregates over multiple steps. eg.
  `total = BinaryOperatorAggregate(int, operator.add)`

LangGraph 把一次图计算拆成无限循环的三步,直到没有任务可跑或达到步数上限:

  1. Plan(选节点)
    看哪些通道的值在上轮被改过,把订阅这些通道的节点挑出来。
  2. Execution(跑节点)
    并发执行被选中的节点;节点读通道、算结果、把"写请求"攒进自己的 writes 列表,但此时并不真正写回通道
  3. Update(落数据)
    等本轮所有节点跑完,一次性把 writes 里的 (channel, value) 写进通道,并更新 checkpoint 版本号。

下一轮再拿新的通道版本重新做 Plan,如此往复。

二、示例验证------单节点图

代码只有 11 行,却完整走了一遍三步:

python 复制代码
from langgraph.channels import EphemeralValue
from langgraph.pregel import Pregel, Channel

node1 = (
    Channel.subscribe_to("a")   # 订阅通道 a
    | (lambda x: x + x)         # 业务逻辑
    | Channel.write_to("b")     # 写通道 b
)
app = Pregel(
    nodes={"node1": node1},
    channels={"a": EphemeralValue(str), "b": EphemeralValue(str)},
    input_channels=["a"],
    output_channels=["b"],
)
print(app.invoke({"a": "foo"}))     # → {'b': 'foofoo'}

Plan :首轮只有 a 被外部输入更新 → 选中 node1
Executionnode1 算出 "foofoo",把 ("b", "foofoo") 塞进自己的 writes。
Updateapply_writes 把 writes 真正写进通道 b,checkpoint 版本号刷新。

下一轮 Plan 发现没有任何通道再被更新,循环结束,返回 {'b': 'foofoo'}

三、源码级定位

  1. Plan
    .venv/lib/python3.12/site-packages/langgraph/pregel/algo.py
    prepare_next_tasks(...)

    • 先处理上轮残留的 pending_sends(PUSH 任务)
    • 再根据 updated_channels + trigger_to_nodes 快速圈出本轮被触发的节点(PULL 任务)
  2. Execution
    .venv/lib/python3.12/site-packages/langgraph/pregel/runner.py
    PregelRunner.tick(...)

    • 并发跑任务,回调 commit(task, exc) 把每个任务产生的原始 writes 缓存起来
    • 本身碰通道,只负责"跑完并收集写请求"
  3. Update

    仍在 algo.py ------ apply_writes(checkpoint, channels, tasks, None)

    • SyncPregelLoop / AsyncPregelLoop下一轮开头 调用
    • 一次性把所有 writes 应用到通道,更新版本号,完成真正的"通道更新"

四、总结

官方文档、示例、源码三者互相印证:
Plan 决定谁跑,Execution 只算不写,Update 集中落盘 ,最终借鉴Pregel、BSP模型实现图的额执行。

相关推荐
带刺的坐椅4 天前
AI 应用工作流:LangGraph 和 Solon AI Flow,我该选谁?
java·python·ai·solon·flow·langgraph
爬点儿啥6 天前
[Ai Agent] 09 LangGraph 进阶:构建可控、可协作的多智能体系统
人工智能·ai·langchain·大模型·agent·langgraph
后台开发者Ethan10 天前
LangGraph ReAct应用
python·langgraph
后台开发者Ethan12 天前
LangGraph 的持久化
python·langgraph
g323086316 天前
langchain langGraph 中streaming 流式输出 stream_mode
langchain·langgraph
学历真的很重要21 天前
LangChain V1.0 Messages 详细指南
开发语言·后端·语言模型·面试·langchain·职场发展·langgraph
稳稳C91 个月前
02|Langgraph | 从入门到实战 | workflow与Agent
人工智能·langchain·agent·langgraph
水中加点糖1 个月前
使用LangChain+LangGraph自定义AI工作流,实现音视频字幕生成工具
人工智能·ai·langchain·工作流·langgraph
用什么都重名1 个月前
LangGraph vs CrewAI vs OpenAI Swarm:三大AI框架
人工智能·langgraph·crewai·openai swarm
lihuayong1 个月前
LangGraph React智能体 - 推理与行动的完美结合
人工智能·langgraph·react 智能体