/images/hugo/avatar.png

pregel - 2

1. Pregel 的方法

前面我们总结过 Pregel 有如下方法。

方法名 输入类型 输出类型 作用
__init__ nodes, channels, input_channels, output_channels None 初始化 Pregel 实例,设置节点、通道、输入输出等配置
get_graph config: RunnableConfig | None, xray: int | bool = False Graph 返回计算图的可绘制表示
aget_graph config: RunnableConfig | None, xray: int | bool = False Graph 异步返回计算图的可绘制表示
_repr_mimebundle_ **kwargs: Any dict[str, Any] Jupyter 显示图形用的 MIME 包
copy update: dict[str, Any] | None = None Self 创建 Pregel 对象的副本
with_config config: RunnableConfig | None = None, **kwargs: Any Self 使用更新配置创建 Pregel 副本
validate 无参数 Self 验证图形配置的有效性
config_schema include: Sequence[str] | None = None type[BaseModel] 获取配置模式(已弃用)
get_config_jsonschema include: Sequence[str] | None = None dict[str, Any] 获取配置 JSON 模式(已弃用)
get_context_jsonschema 无参数 dict[str, Any] | None 获取上下文 JSON 模式
get_input_schema config: RunnableConfig | None = None type[BaseModel] 获取输入模式
get_input_jsonschema config: RunnableConfig | None = None dict[str, Any] 获取输入 JSON 模式
get_output_schema config: RunnableConfig | None = None type[BaseModel] 获取输出模式
get_output_jsonschema config: RunnableConfig | None = None dict[str, Any] 获取输出 JSON 模式
get_subgraphs namespace: str | None = None, recurse: bool = False Iterator[tuple[str, PregelProtocol]] 获取图的子图
aget_subgraphs namespace: str | None = None, recurse: bool = False AsyncIterator[tuple[str, PregelProtocol]] 异步获取图的子图
get_state config: RunnableConfig, subgraphs: bool = False StateSnapshot 获取图的当前状态
aget_state config: RunnableConfig, subgraphs: bool = False StateSnapshot 异步获取图的当前状态
get_state_history config: RunnableConfig, filter, before, limit Iterator[StateSnapshot] 获取图状态历史
aget_state_history config: RunnableConfig, filter, before, limit AsyncIterator[StateSnapshot] 异步获取图状态历史
bulk_update_state config: RunnableConfig, supersteps: Sequence[Sequence[StateUpdate]] RunnableConfig 批量更新图状态
abulk_update_state config: RunnableConfig, supersteps: Sequence[Sequence[StateUpdate]] RunnableConfig 异步批量更新图状态
update_state config: RunnableConfig, values, as_node, task_id RunnableConfig 更新图状态
aupdate_state config: RunnableConfig, values, as_node, task_id RunnableConfig 异步更新图状态
stream input, config, context, stream_mode Iterator[dict[str, Any] | Any] 流式执行图并返回步骤输出
astream input, config, context, stream_mode AsyncIterator[dict[str, Any] | Any] 异步流式执行图并返回步骤输出
invoke input, config, context, stream_mode dict[str, Any] | Any 同步执行图并返回最终结果
ainvoke input, config, context, stream_mode dict[str, Any] | Any 异步执行图并返回最终结果
clear_cache nodes: Sequence[str] | None = None None 清除指定节点的缓存
aclear_cache nodes: Sequence[str] | None = None None 异步清除指定节点的缓存

主要功能分类:

pregel checkpoint

langgraph 中的 Checkpointer 用于在流程中持久化执行进度,使得可以恢复中断或支持长时间运行。

1. Checkpointer

Langgraph 中定义了三个类用于实现对 Checkpointer 的定义: 2. Checkpoint

  1. CheckpointTuple
  2. CheckpointMetadata
序号 名称 角色 说明
1️⃣ CheckpointTuple 📦 顶层容器 封装了 checkpoint 本体、其元数据、相关配置等
2️⃣ Checkpoint 🧠 核心数据(状态快照) 图执行中保存的值、状态、调度上下文等
3️⃣ CheckpointMetadata 🏷️ 元数据标签 checkpoint 的非功能信息(时间戳、ID、tags 等)

1.1 Checkpoint

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ChannelVersions = dict[str, Union[str, int, float]]

class Checkpoint(TypedDict):
    """State snapshot at a given point in time."""

    v: int
    """The version of the checkpoint format. Currently 1."""
    id: str
    """The ID of the checkpoint. This is both unique and monotonically
    increasing, so can be used for sorting checkpoints from first to last."""
    ts: str
    """The timestamp of the checkpoint in ISO 8601 format."""
    channel_values: dict[str, Any]
    """The values of the channels at the time of the checkpoint.
    Mapping from channel name to deserialized channel snapshot value.
    """
    channel_versions: ChannelVersions
    """The versions of the channels at the time of the checkpoint.
    The keys are channel names and the values are monotonically increasing
    version strings for each channel.
    """
    versions_seen: dict[str, ChannelVersions]
    """Map from node ID to map from channel name to version seen.
    This keeps track of the versions of the channels that each node has seen.
    Used to determine which nodes to execute next.
    """
属性名 含义
v 检查点格式的版本号,目前为 1。用于向前兼容。
id 检查点的唯一标识符,单调递增(可用于排序)。
ts 检查点的时间戳,ISO 8601 格式字符串,例如 "2025-08-04T10:32:00.000Z"
channel_values 当前检查点时所有 channel 的值,键为 channel 名,值为反序列化后的数据。
channel_versions 每个 channel 当前的版本号,键为 channel 名,值为字符串、整数或浮点数等单调递增值。
versions_seen 用于追踪每个 node 最近“看见”的 channel 版本。键为 node 名,值为该 node 最近读到的 {channel: version} 映射。可用于判断哪些节点需要重新执行。

下面是一个示例:

pregel - 1

经过前面这么多节的铺垫,我们了解了 Pregel 组合的各种对象,现在我们来看看 Pregel 类的实现。

1. Pregel

1.1 Pregel 属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Pregel(
    PregelProtocol[StateT, ContextT, InputT, OutputT],
    Generic[StateT, ContextT, InputT, OutputT],
):
    nodes: dict[str, PregelNode]

    channels: dict[str, BaseChannel | ManagedValueSpec]

    stream_mode: StreamMode = "values"
    """Mode to stream output, defaults to 'values'."""

    stream_eager: bool = False
    """Whether to force emitting stream events eagerly, automatically turned on
    for stream_mode "messages" and "custom"."""

    output_channels: str | Sequence[str]

    stream_channels: str | Sequence[str] | None = None
    """Channels to stream, defaults to all channels not in reserved channels"""

    interrupt_after_nodes: All | Sequence[str]

    interrupt_before_nodes: All | Sequence[str]

    input_channels: str | Sequence[str]

    step_timeout: float | None = None
    """Maximum time to wait for a step to complete, in seconds. Defaults to None."""

    debug: bool
    """Whether to print debug information during execution. Defaults to False."""

    checkpointer: Checkpointer = None
    """Checkpointer used to save and load graph state. Defaults to None."""

    store: BaseStore | None = None
    """Memory store to use for SharedValues. Defaults to None."""

    cache: BaseCache | None = None
    """Cache to use for storing node results. Defaults to None."""

    retry_policy: Sequence[RetryPolicy] = ()
    """Retry policies to use when running tasks. Empty set disables retries."""

    cache_policy: CachePolicy | None = None
    """Cache policy to use for all nodes. Can be overridden by individual nodes.
    Defaults to None."""

    context_schema: type[ContextT] | None = None
    """Specifies the schema for the context object that will be passed to the workflow."""

    config: RunnableConfig | None = None

    name: str = "LangGraph"

    trigger_to_nodes: Mapping[str, Sequence[str]]
属性名 类型 说明 默认值
nodes dict[str, PregelNode] 图中的节点集合,键为节点名,值为对应节点对象 无默认值(必须提供)
channels dict[str, BaseChannel | ManagedValueSpec] 所有定义的通道,包括状态传递通道、值通道等 无默认值
stream_mode StreamMode(如 "values""messages""custom" 控制流的输出流模式 "values"
stream_eager bool 是否立即输出事件流(如 trace、消息)。部分模式下自动为 True False
output_channels str | Sequence[str] 输出数据写入的目标通道 无默认值
stream_channels str | Sequence[str] | None 哪些通道的值将被流式输出(如果未指定,则为所有非保留通道) None
interrupt_after_nodes All | Sequence[str] 指定在哪些节点之后中断执行(可用于调试) 无默认值
interrupt_before_nodes All | Sequence[str] 指定在哪些节点之前中断执行(可用于调试) 无默认值
input_channels str | Sequence[str] 接收输入的通道名称 无默认值
step_timeout float | None 每一步最大等待时间(秒),防止阻塞 None
debug bool 是否打印调试信息 默认 False(源码中未指定默认但文档描述为 False)
checkpointer Checkpointer | None 用于保存和恢复图状态的检查点管理器 None
store BaseStore | None 用于持久化共享值(SharedValues)的存储后端 None
cache BaseCache | None 用于节点结果缓存的缓存后端 None
retry_policy Sequence[RetryPolicy] 节点执行失败时的重试策略,空序列表示不重试 ()(空元组)
cache_policy CachePolicy | None 所有节点通用的缓存策略,可被单节点覆盖 None
context_schema type[ContextT] | None context 对象的类型,用于强类型验证 None
config RunnableConfig | None 运行配置(用于 tracing、callback 等) None
name str 图的名称 "LangGraph"
trigger_to_nodes Mapping[str, Sequence[str]] 定义触发器到节点的映射(如外部事件触发哪些节点) 无默认值

1.2 使用示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from langgraph.channels import LastValue, EphemeralValue, Topic
from langgraph.pregel import Pregel, NodeBuilder

node1 = (
    NodeBuilder().subscribe_only("a")
    .do(lambda x: x + x)
    .write_to("b")
)

node2 = (
    NodeBuilder().subscribe_to("b")
    .do(lambda x: x["b"] + x["b"])
    .write_to("c")
)


app = Pregel(
    nodes={"node1": node1, "node2": node2},
    channels={
        "a": EphemeralValue(str),
        "b": LastValue(str),
        "c": EphemeralValue(str),
    },
    input_channels=["a"],
    output_channels=["b", "c"],
)

print(app.invoke({"a": "foo"}))
# {'b': 'foofoo', 'c': 'foofoofoofoo'}

我们以这个示例为切入口,先来学习 Pregel 基础部分。

pregel channel 读写

前面我们介绍了 langgraph 中的 channel 类型,这一节我们来介绍 channel 的读写。

1. ChannelRead

1
提问: 解释一下  ChannelRead 的语义,并以表格列举 ChannelRead 的属性,以另一个表格列出每个方法名、作用、输出值类型

ChannelRead 定义在 langgraph\pregel\_read.py 与 PregelNode 位于同一个 py 文件。ChannelRead 是 LangGraph 中的一个工具类,主要用于:

pregel node

1. PregelNode

1.1 PregelNode 属性

前面我们已经了解到,PregelNode 没有抽象方法,且有如下属性:

属性名 类型 语义作用 使用场景 / 示例
channels str | list[str] 输入通道名称(单个或多个)。决定从哪些通道读取输入并传给 bound channels="user_input"channels=["query", "history"]
triggers list[str] 当这些通道被写入时,当前节点在下一轮中被激活执行。 通常用来响应其他节点的输出或外部信号
mapper Callable[[Any], Any] | None 在传给 bound 之前对输入值进行转换或预处理。 如将多个输入组合成特定格式
writers list[Runnable] 在节点计算完成后,接管输出结果并写入对应通道。可自定义写入行为。 比如将 bound 的输出写入到多个通道
bound Runnable[Any, Any] 节点的核心执行逻辑,会接收来自 channels 的输入并返回输出。 可以是函数、链、LLM 调用等
retry_policy Sequence[RetryPolicy] | None 节点执行失败时的重试策略。支持如指数退避、最大次数等。 提高健壮性,处理临时失败
cache_policy CachePolicy | None 节点的缓存策略。用于跳过相同输入的重复执行。 性能优化,节省 LLM token 或 API 请求
tags Sequence[str] | None 附加在节点上的标记,用于 tracing、debug、日志等用途。 ["llm", "retriever"]
metadata Mapping[str, Any] | None 附加在节点上的任意键值对信息,用于 tracing 或运行时识别。 比如记录节点版本、模型 ID
subgraphs Sequence[PregelProtocol] 嵌套图,表示该节点内部可递归执行子图。 实现复杂控制流或组件级封装

1.2 PregelNode 方法

PregelNode 实现了 Runnable 协议,具体的实现方法是向下面这样,委托给 bound 属性: