/images/hugo/avatar.png

pregel loop

1. PregelLoop

1
2
# 提问
上面是 Langgraph PregelLoop 的定义,请给我解释一下 PregelLoop 的语义,并以表格的形式列举 PregelLoop 的属性,并以另一个表格列举 PregelLoop 的方法

1.1 PregelLoop 语义

PregelLoop 是 LangGraph 中实现 Pregel 模式的核心类之一,承担了图执行调度器的角色。它负责以超步(superstep)方式逐步调度图中的节点(PregelNode),并在每个 tick 中处理任务的生成、执行、中断判断、检查点记录、流写入以及缓存等一系列关键操作。PregelLoop 应该是 LangGraph 中最复杂的类,也是最核心的类。

pregel runner

1. PregelRunner

这个 PregelRunner 类是 LangGraph 中 Pregel 模式的一部分,用于并发执行节点任务、提交写入数据、处理中断与输出流。

它不是图的核心结构(如 PregelLoop、PregelNode),但作为执行调度器,用于运行单个“超级步(superstep)”中的节点任务并控制其生命周期。

pregel stream mode

6. 消息流模式

6.1 stream_mode="messages"

当图中某个节点调用了 LLM(如 OpenAI Chat API),你可能希望 逐 token 地将 LLM 回复 stream 给前端。LangGraph 提供 messages 模式实现这一点:

stream 中相关代码详解

1
2
3
4
if "messages" in stream_modes:
    run_manager.inheritable_handlers.append(
        StreamMessagesHandler(stream.put, subgraphs)
    )
  • 给 callback handler 列表添加一个 StreamMessagesHandler
  • 它会自动挂载到所有 LLM 调用上(只要用的是 langchain LLM);
  • 它将每个 token 连同其 metadata(包括哪一个节点)写入 stream.put()
  • 如果是子图节点,还会加上完整 namespace 路径。

消息流的输出格式

1
("messages", ("Hello", {"name": "llm_node", "type": "llm"}))

或者如果启用了子图:

pregel runtime

1. Runtime

1
2
# 提问
上面是 Langgraph Runtime 的定义,请给我解释一下 Runtime 的语义,并以表格的形式列举 Runtime 的属性,并以另一个表格列举 Runtime 的方法

1.1 Runtime 语义

LangGraph 中的 Runtime 类是一个用于封装运行时上下文与工具的便利类,通常会在每个图执行期间作为第二个参数注入节点函数中(第一个是 state,第二个是 runtime),以提供更强大的能力,比如:

pregel cache

前面我们了解到 langgraph cache 类似于 @functools.lru_cache,可以缓存函数的返回值,避免重复计算。这一节我们来看 Cache 的具体实现细节。

1. BaseCache

cache 如实现由 BaseCache 抽象基类约定。

pregel store

前面我们了解到 Store 是一种 通用的 key-value 存储系统,可以将 store 看作 LangGraph 中的共享缓存 / 状态仓库。这一节我们来看 Store 的具体实现细节。

1. BaseStore

Store 如实现由 BaseStore 抽象基类约定。

1.1 BaseStore 属性

 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
class BaseStore(ABC):
    supports_ttl: bool = False
    ttl_config: TTLConfig | None = None

    __slots__ = ("__weakref__",)

class TTLConfig(TypedDict, total=False):
    """Configuration for TTL (time-to-live) behavior in the store."""

    refresh_on_read: bool
    """Default behavior for refreshing TTLs on read operations (GET and SEARCH).
    
    If True, TTLs will be refreshed on read operations (get/search) by default.
    This can be overridden per-operation by explicitly setting refresh_ttl.
    Defaults to True if not configured.
    """
    default_ttl: float | None
    """Default TTL (time-to-live) in minutes for new items.
    
    If provided, new items will expire after this many minutes after their last access.
    The expiration timer refreshes on both read and write operations.
    Defaults to None (no expiration).
    """
    sweep_interval_minutes: int | None
    """Interval in minutes between TTL sweep operations.
    
    If provided, the store will periodically delete expired items based on TTL.
    Defaults to None (no sweeping).
    """

下面是 TTLConfig 几个配置项的含义: