检查点(Checkpointers)
检查点机制是 LangGraph 中用于持久化图状态的核心功能,允许代理在多次交互中或跨交互保持状态。本文涵盖类、函数、方法及其示例。
1. 类
1.1 类 CheckpointMetadata
继承自: TypedDict
描述:
CheckpointMetadata
定义与检查点关联的元数据,记录检查点的来源、步骤号、写入数据和父检查点信息。
1.1.1 属性
名称 | 类型 | 描述 |
---|---|---|
source | Literal['input', 'loop', 'update', 'fork'] | 检查点的来源,可能的值为: |
- "input" : 检查点来自 invoke 、stream 或 batch 的输入。 | ||
- "loop" : 检查点来自 Pregel 循环内部。 | ||
- "update" : 检查点来自手动状态更新。 | ||
- "fork" : 检查点是另一个检查点的副本。 | ||
step | int | 检查点的步骤号。-1 表示首个 "input" 检查点,0 表示首个 "loop" 检查点,之后为第 n 个检查点。 |
writes | dict[str, Any] | 前一个检查点到此检查点之间的写入数据,映射从节点名称到该节点的写入值。 |
parents | dict[str, str] | 父检查点的 ID,映射从检查点命名空间到检查点 ID。 |
1.2 类 Checkpoint
继承自: TypedDict
描述:
Checkpoint
表示某一时刻的状态快照,记录通道值、版本、时间戳等信息。
1.2.1 属性
名称 | 类型 | 描述 |
---|---|---|
v | int | 检查点格式的版本,当前为 1 。 |
id | str | 检查点的唯一 ID,单调递增,可用于按时间排序检查点。 |
ts | str | 检查点的时间戳,采用 ISO 8601 格式。 |
channel_values | dict[str, Any] | 检查点时通道的值,映射从通道名称到反序列化的通道快照值。 |
channel_versions | ChannelVersions | 检查点时通道的版本,映射从通道名称到单调递增的版本字符串。 |
versions_seen | dict[str, ChannelVersions] | 记录每个节点看到的通道版本,映射从节点 ID 到通道名称和版本的映射,用于确定下一个要执行的节点。 |
pending_sends | List[SendProtocol] | 已推送至节点但尚未处理的输入列表,在下一个检查点时清除。 |
1.3 类 BaseCheckpointSaver
继承自: Generic[V]
描述:
BaseCheckpointSaver
是创建图检查点保存器的基类,允许 LangGraph 代理在多次交互中或跨交互持久化状态。子类需要实现具体存储逻辑。
1.3.1 属性
名称 | 类型 | 描述 |
---|---|---|
serde | SerializerProtocol | 用于编码/解码检查点的序列化器。 |
config_specs | list[ConfigurableFieldSpec] | 定义检查点保存器的配置选项。 |
注意:
创建自定义检查点保存器时,建议实现异步方法以避免阻塞主线程。
1.3.2 方法
名称 | 描述 |
---|---|
get | 使用给定配置获取检查点。 |
get_tuple | 使用给定配置获取检查点元组。 |
list | 列出符合给定条件的检查点。 |
put | 存储检查点及其配置和元数据。 |
put_writes | 存储与检查点关联的中间写入数据。 |
delete_thread | 删除特定线程 ID 关联的所有检查点和写入数据。 |
aget | 异步使用给定配置获取检查点。 |
aget_tuple | 异步使用给定配置获取检查点元组。 |
alist | 异步列出符合给定条件的检查点。 |
aput | 异步存储检查点及其配置和元数据。 |
aput_writes | 异步存储与检查点关联的中间写入数据。 |
adelete_thread | 异步删除特定线程 ID 关联的所有检查点和写入数据。 |
get_next_version | 为通道生成下一个版本 ID。 |
方法 get
get(config: RunnableConfig) -> Optional[Checkpoint]
描述:
使用给定配置获取检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 指定要检索的检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[Checkpoint] | 请求的检查点,若未找到则返回 None 。 |
方法 get_tuple
get_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
使用给定配置获取检查点元组。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 指定要检索的检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 请求的检查点元组,若未找到则返回 None 。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 list
list(
config: Optional[RunnableConfig],
*,
filter: Optional[Dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> Iterator[CheckpointTuple]
描述:
列出符合给定条件的检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[Dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定配置之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
Iterator[CheckpointTuple] | 符合条件的检查点元组迭代器。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 put
put(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions,
) -> RunnableConfig
描述:
存储检查点及其配置和元数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 检查点的配置。 | 必填 |
checkpoint | Checkpoint | 要存储的检查点。 | 必填 |
metadata | CheckpointMetadata | 检查点的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 put_writes
put_writes(
config: RunnableConfig,
writes: Sequence[Tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
存储与检查点关联的中间写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[Tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 delete_thread
delete_thread(thread_id: str) -> None
描述:
删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 aget
async aget(config: RunnableConfig) -> Optional[Checkpoint]
描述:
异步使用给定配置获取检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 指定要检索的检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[Checkpoint] | 请求的检查点,若未找到则返回 None 。 |
方法 aget_tuple
async aget_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
异步使用给定配置获取检查点元组。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 指定要检索的检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 请求的检查点元组,若未找到则返回 None 。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 alist
async alist(
config: Optional[RunnableConfig],
*,
filter: Optional[Dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> AsyncIterator[CheckpointTuple]
描述:
异步列出符合给定条件的检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[Dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定配置之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
AsyncIterator[CheckpointTuple] | 符合条件的检查点元组异步迭代器。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 aput
async aput(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
异步存储检查点及其配置和元数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 检查点的配置。 | 必填 |
checkpoint | Checkpoint | 要存储的检查点。 | 必填 |
metadata | CheckpointMetadata | 检查点的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 aput_writes
async aput_writes(
config: RunnableConfig,
writes: Sequence[Tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
异步存储与检查点关联的中间写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[Tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 adelete_thread
async adelete_thread(thread_id: str) -> None
描述:
异步删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 get_next_version
get_next_version(
current: Optional[V],
channel: ChannelProtocol
) -> V
描述:
为通道生成下一个版本 ID。默认使用整数版本,每次递增 1。子类可重写,支持字符串、整数或浮点数版本,但需保证单调递增。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
current | Optional[V] | 当前版本标识符(整数、浮点数或字符串)。 | 必填 |
channel | ChannelProtocol | 被版本化的通道。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
V | V | 下一个版本标识符,须单调递增。 |
1.4 类 SerializerProtocol
继承自: UntypedSerializerProtocol
, Protocol
描述:
SerializerProtocol
定义了对象序列化和反序列化的协议,适用于检查点数据。
1.4.1 方法
dumps
: 将对象序列化为字节。dumps_typed
: 将对象序列化为 (类型, 字节) 元组。loads
: 从字节反序列化对象。loads_typed
: 从 (类型, 字节) 元组反序列化对象。
有效实现:
包括 pickle
、json
和 orjson
模块。
1.5 类 JsonPlusSerializer
继承自: SerializerProtocol
描述:
JsonPlusSerializer
是一种序列化器,使用 ormsgpack
进行序列化,fallback 到扩展 JSON 序列化器。
1.6 类 InMemorySaver
继承自: BaseCheckpointSaver[str]
, AbstractContextManager
, AbstractAsyncContextManager
描述:
InMemorySaver
是一个内存中的检查点保存器,使用 defaultdict
存储检查点。
注意:
仅用于调试或测试目的。生产环境中推荐安装 langgraph-checkpoint-postgres
并使用 PostgresSaver
或 AsyncPostgresSaver
。若使用 LangGraph 平台,无需指定检查点保存器,将自动使用托管的检查点保存器。
1.6.1 参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
serde | Optional[SerializerProtocol] | 用于序列化和反序列化检查点的序列化器。 | None |
1.6.2 示例
import asyncio
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph
# 定义状态图
builder = StateGraph(int)
builder.add_node("add_one", lambda x: x + 1)
builder.set_entry_point("add_one")
builder.set_finish_point("add_one")
# 创建内存检查点保存器
memory = InMemorySaver()
# 编译图并使用检查点保存器
graph = builder.compile(checkpointer=memory)
# 异步调用图
coro = graph.ainvoke(1, {"configurable": {"thread_id": "thread-1"}})
asyncio.run(coro) # 输出: 2
1.6.3 方法
名称 | 描述 |
---|---|
get | 使用给定配置获取检查点。 |
get_tuple | 从内存存储中获取检查点元组。 |
list | 从内存存储中列出检查点。 |
put | 将检查点保存到内存存储。 |
put_writes | 将写入列表保存到内存存储。 |
delete_thread | 删除特定线程 ID 关联的所有检查点和写入数据。 |
aget | 异步使用给定配置获取检查点。 |
aget_tuple | 异步从内存存储中获取检查点元组。 |
alist | 异步从内存存储中列出检查点。 |
aput | 异步将检查点保存到内存存储。 |
aput_writes | 异步将写入列表保存到内存存储。 |
adelete_thread | 异步删除特定线程 ID 关联的所有检查点和写入数据。 |
方法 get_tuple
get_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
从内存存储中获取检查点元组。如果配置包含 checkpoint_id
键,则检索匹配线程 ID 和时间戳的检查点;否则,检索给定线程 ID 的最新检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
方法 list
list(
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> Iterator[CheckpointTuple]
描述:
从内存存储中列出检查点元组,基于提供的条件。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定配置之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
Iterator[CheckpointTuple] | 符合条件的检查点元组迭代器。 |
方法 put
put(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
将检查点保存到内存存储,与提供的配置关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 包含保存检查点时间戳的更新配置。 |
方法 put_writes
put_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
将写入列表保存到内存存储,与提供的配置关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
方法 delete_thread
delete_thread(thread_id: str) -> None
描述:
删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 aget_tuple
async aget_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
异步从内存存储中获取检查点元组,基于同步 get_tuple
方法,使用 asyncio
在单独线程中运行。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
方法 alist
async alist(
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> AsyncIterator[CheckpointTuple]
描述:
异步从内存存储中列出检查点元组,基于同步 list
方法,使用 asyncio
在单独线程中运行。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定配置之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
AsyncIterator[CheckpointTuple] | 符合条件的检查点元组异步迭代器。 |
方法 aput
async aput(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
异步将检查点保存到内存存储。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 包含保存检查点时间戳的更新配置。 |
方法 aput_writes
async aput_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
异步将写入列表保存到内存存储,基于同步 put_writes
方法,使用 asyncio
在单独线程中运行。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
方法 adelete_thread
async adelete_thread(thread_id: str) -> None
描述:
异步删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
1.7 类 PersistentDict
继承自: defaultdict
描述:
PersistentDict
是一个持久化字典,API 兼容 shelve
和 anydbm
。字典保存在内存中,操作速度与常规字典相同,写入磁盘延迟到关闭或同步时(类似于 gdbm
的快速模式)。支持 pickle
、json
和 csv
序列化格式,均由快速 C 实现支持。
1.7.1 方法
方法 sync
sync() -> None
描述:
将字典写入磁盘。
1.8 类 SqliteSaver
继承自: BaseCheckpointSaver[str]
描述:
SqliteSaver
是一个同步检查点保存器,将检查点存储在 SQLite 数据库中。适用于轻量级、同步用例(演示和小项目),但不支持多线程扩展。
注意:
对于需要异步支持的场景,推荐使用 AsyncSqliteSaver
。生产环境建议使用更健壮的数据库,如 PostgreSQL。
1.8.1 参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
conn | Connection | SQLite 数据库连接。 | 必填 |
serde | Optional[SerializerProtocol] | 用于序列化和反序列化检查点的序列化器,默认为 JsonPlusSerializerCompat 。 | None |
1.8.2 示例
基本用法
import sqlite3
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import StateGraph
# 定义状态图
builder = StateGraph(int)
builder.add_node("add_one", lambda x: x + 1)
builder.set_entry_point("add_one")
builder.set_finish_point("add_one")
# 创建 SQLite 检查点保存器
# 注意:check_same_thread=False 是安全的,因为实现使用锁确保线程安全
conn = sqlite3.connect("checkpoints.sqlite", check_same_thread=False)
memory = SqliteSaver(conn)
# 编译图并使用检查点保存器
graph = builder.compile(checkpointer=memory)
config = {"configurable": {"thread_id": "1"}}
# 获取状态
graph.get_state(config)
# 调用图
result = graph.invoke(3, config)
# 再次获取状态
print(graph.get_state(config))
# 输出: StateSnapshot(values=4, next=(), config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '0c62ca34-ac19-445d-bbb0-5b4984975b2a'}}, parent_config=None)
从连接字符串创建
from langgraph.checkpoint.sqlite import SqliteSaver
# 内存数据库
with SqliteSaver.from_conn_string(":memory:") as memory:
# 代码...
# 磁盘数据库
with SqliteSaver.from_conn_string("checkpoints.sqlite") as memory:
# 代码...
1.8.3 方法
名称 | 描述 |
---|---|
from_conn_string | 从连接字符串创建新的 SqliteSaver 实例。 |
setup | 设置检查点数据库。 |
cursor | 获取 SQLite 数据库的游标。 |
get | 使用给定配置获取检查点。 |
get_tuple | 从数据库获取检查点元组。 |
list | 从数据库列出检查点。 |
put | 将检查点保存到数据库。 |
put_writes | 存储与检查点关联的中间写入数据。 |
delete_thread | 删除特定线程 ID 关联的所有检查点和写入数据。 |
aget | 异步使用给定配置获取检查点。 |
aget_tuple | 异步从数据库获取检查点元组(不支持,建议使用 AsyncSqliteSaver )。 |
alist | 异步从数据库列出检查点(不支持,建议使用 AsyncSqliteSaver )。 |
aput | 异步将检查点保存到数据库(不支持,建议使用 AsyncSqliteSaver )。 |
aput_writes | 异步存储与检查点关联的中间写入数据。 |
adelete_thread | 异步删除特定线程 ID 关联的所有检查点和写入数据。 |
get_next_version | 为通道生成下一个版本 ID。 |
方法 from_conn_string
from_conn_string(conn_string: str) -> Iterator[SqliteSaver]
描述:
从连接字符串创建新的 SqliteSaver
实例。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
conn_string | str | SQLite 连接字符串。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
SqliteSaver | Iterator[SqliteSaver] | 新的 SqliteSaver 实例。 |
方法 setup
setup() -> None
描述:
设置检查点数据库,创建必要的表(若不存在)。此方法由系统自动调用,用户无需直接调用。
方法 cursor
cursor(transaction: bool = True) -> Iterator[Cursor]
描述:
获取 SQLite 数据库的游标,供内部使用,用户无需直接调用。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
transaction | bool | 关闭游标时是否提交事务。 | True |
返回值:
类型 | 描述 |
---|---|
Cursor | sqlite3.Cursor :SQLite 数据库的游标。 |
方法 get_tuple
get_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
从 SQLite 数据库获取检查点元组。如果配置包含 checkpoint_id
键,则检索匹配线程 ID 和检查点 ID 的检查点;否则,检索给定线程 ID 的最新检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
示例:
# 基本用法
config = {"configurable": {"thread_id": "1"}}
checkpoint_tuple = memory.get_tuple(config)
print(checkpoint_tuple) # 输出: CheckpointTuple(...)
# 使用检查点 ID
config = {
"configurable": {
"thread_id": "1",
"checkpoint_ns": "",
"checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875"
}
}
checkpoint_tuple = memory.get_tuple(config)
print(checkpoint_tuple) # 输出: CheckpointTuple(...)
方法 list
list(
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> Iterator[CheckpointTuple]
描述:
从 SQLite 数据库列出检查点元组,按检查点 ID 降序排列(最新优先)。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定检查点 ID 之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
Iterator[CheckpointTuple] | 符合条件的检查点元组迭代器。 |
示例:
from langgraph.checkpoint.sqlite import SqliteSaver
with SqliteSaver.from_conn_string(":memory:") as memory:
config = {"configurable": {"thread_id": "1"}}
checkpoints = list(memory.list(config, limit=2))
print(checkpoints) # 输出: [CheckpointTuple(...), CheckpointTuple(...)]
config = {"configurable": {"thread_id": "1"}}
before = {"configurable": {"checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875"}}
with SqliteSaver.from_conn_string(":memory:") as memory:
checkpoints = list(memory.list(config, before=before))
print(checkpoints) # 输出: [CheckpointTuple(...), ...]
方法 put
put(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
将检查点保存到 SQLite 数据库,与提供的配置及其父配置(若有)关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
示例:
from langgraph.checkpoint.sqlite import SqliteSaver
with SqliteSaver.from_conn_string(":memory:") as memory:
config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
checkpoint = {
"ts": "2024-05-04T06:32:42.235444+00:00",
"id": "1ef4f797-8335-6428-8001-8a1503f9b875",
"channel_values": {"key": "value"}
}
saved_config = memory.put(config, checkpoint, {"source": "input", "step": 1, "writes": {"key": "value"}}, {})
print(saved_config)
# 输出: {'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1ef4f797-8335-6428-8001-8a1503f9b875'}}
方法 put_writes
put_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
存储与检查点关联的中间写入数据到 SQLite 数据库。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
方法 delete_thread
delete_thread(thread_id: str) -> None
描述:
删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 aget_tuple
async aget_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
异步从 SQLite 数据库获取检查点元组。
注意:
SqliteSaver
不支持此异步方法,建议使用 get_tuple()
或 AsyncSqliteSaver
。
方法 alist
async alist(
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> AsyncIterator[CheckpointTuple]
描述:
异步从 SQLite 数据库列出检查点元组。
注意:
SqliteSaver
不支持此异步方法,建议使用 list()
或 AsyncSqliteSaver
。
方法 aput
async aput(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
异步将检查点保存到 SQLite 数据库。
注意:
SqliteSaver
不支持此异步方法,建议使用 put()
或 AsyncSqliteSaver
。
方法 aput_writes
async aput_writes(
config: RunnableConfig,
writes: Sequence[Tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
异步存储与检查点关联的中间写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[Tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 adelete_thread
async adelete_thread(thread_id: str) -> None
描述:
异步删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 get_next_version
get_next_version(
current: Optional[str],
channel: ChannelProtocol
) -> str
描述:
为通道生成下一个版本 ID,默认递增整数版本。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
current | Optional[str] | 当前版本标识符。 | 必填 |
channel | ChannelProtocol | 被版本化的通道。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
str | str | 下一个版本标识符,单调递增。 |
1.9 类 AsyncSqliteSaver
继承自: BaseCheckpointSaver[str]
描述:
AsyncSqliteSaver
是一个异步检查点保存器,将检查点存储在 SQLite 数据库中,设计用于异步环境,适合 I/O 密集型操作。
提示:
- 需要安装
aiosqlite
包:pip install aiosqlite
。 - 不推荐用于生产环境,因 SQLite 写入性能有限,建议使用 PostgreSQL。
- 使用后需关闭数据库连接,否则程序可能在执行后“挂起”。推荐使用
async with
语句。
1.9.1 属性
名称 | 类型 | 描述 |
---|---|---|
conn | Connection | 异步 SQLite 数据库连接。 |
serde | SerializerProtocol | 用于编码/解码检查点的序列化器。 |
1.9.2 示例
在 StateGraph
中使用
import asyncio
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from langgraph.graph import StateGraph
async def main():
# 定义状态图
builder = StateGraph(int)
builder.add_node("add_one", lambda x: x + 1)
builder.set_entry_point("add_one")
builder.set_finish_point("add_one")
# 使用异步 SQLite 检查点保存器
async with AsyncSqliteSaver.from_conn_string("checkpoints.db") as memory:
graph = builder.compile(checkpointer=memory)
coro = graph.ainvoke(1, {"configurable": {"thread_id": "thread-1"}})
print(await asyncio.gather(coro)) # 输出: [2]
asyncio.run(main())
流式事件
import asyncio
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from langgraph.graph import StateGraph
# 定义状态图
builder = StateGraph(dict)
builder.add_node("add_one", lambda x: {"value": x["value"] + 1})
builder.set_entry_point("add_one")
builder.set_finish_point("add_one")
# 使用异步 SQLite 检查点保存器
async with AsyncSqliteSaver.from_conn_string("checkpoints.sqlite") as saver:
graph = builder.compile(checkpointer=saver)
config = {"configurable": {"thread_id": "thread-1"}}
async for event in graph.astream_events({"value": 1}, config, version="v1"):
print(event)
直接使用
import asyncio
import aiosqlite
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
async def main():
async with aiosqlite.connect("checkpoints.db") as conn:
saver = AsyncSqliteSaver(conn)
config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
checkpoint = {
"ts": "2023-05-03T10:00:00Z",
"data": {"key": "value"},
"id": "0c62ca34-ac19-445d-bbb0-5b4984975b2a"
}
saved_config = await saver.aput(config, checkpoint, {}, {})
print(saved_config)
# 输出: {'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '0c62ca34-ac19-445d-bbb0-5b4984975b2a'}}
asyncio.run(main())
1.9.3 方法
名称 | 描述 |
---|---|
from_conn_string | 从连接字符串创建新的 AsyncSqliteSaver 实例。 |
get | 使用给定配置获取检查点。 |
get_tuple | 从数据库获取检查点元组。 |
list | 从数据库列出检查点。 |
put | 将检查点保存到数据库。 |
put_writes | 存储与检查点关联的中间写入数据。 |
delete_thread | 删除特定线程 ID 关联的所有检查点和写入数据。 |
setup | 异步设置检查点数据库。 |
aget | 异步使用给定配置获取检查点。 |
aget_tuple | 异步从数据库获取检查点元组。 |
alist | 异步从数据库列出检查点。 |
aput | 异步将检查点保存到数据库。 |
aput_writes | 异步存储与检查点关联的中间写入数据。 |
adelete_thread | 异步删除特定线程 ID 关联的所有检查点和写入数据。 |
get_next_version | 为通道生成下一个版本 ID。 |
方法 from_conn_string
async from_conn_string(conn_string: str) -> AsyncIterator[AsyncSqliteSaver]
描述:
从连接字符串创建新的 AsyncSqliteSaver
实例。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
conn_string | str | SQLite 连接字符串。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
AsyncSqliteSaver | AsyncIterator[AsyncSqliteSaver] | 新的 AsyncSqliteSaver 实例。 |
方法 get_tuple
get_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
从 SQLite 数据库获取检查点元组。如果配置包含 checkpoint_id
键,则检索匹配线程 ID 和检查点 ID 的检查点;否则,检索给定线程 ID 的最新检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
方法 list
list(
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> Iterator[CheckpointTuple]
描述:
从 SQLite 数据库列出检查点元组,按检查点 ID 降序排列(最新优先)。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定检查点 ID 之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
Iterator[CheckpointTuple] | 符合条件的检查点元组迭代器。 |
方法 put
put(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
将检查点保存到 SQLite 数据库,与提供的配置及其父配置(若有)关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
方法 delete_thread
delete_thread(thread_id: str) -> None
描述:
删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 setup
async setup() -> None
描述:
异步设置检查点数据库,创建必要的表(若不存在)。此方法由系统自动调用,用户无需直接调用。
方法 aget_tuple
async aget_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
异步从 SQLite 数据库获取检查点元组。如果配置包含 checkpoint_id
键,则检索匹配线程 ID 和检查点 ID 的检查点;否则,检索给定线程 ID 的最新检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
方法 alist
async alist(
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> AsyncIterator[CheckpointTuple]
描述:
异步从 SQLite 数据库列出检查点元组,按检查点 ID 降序排列(最新优先)。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定检查点 ID 之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
AsyncIterator[CheckpointTuple] | 符合条件的检查点元组异步迭代器。 |
方法 aput
async aput(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
异步将检查点保存到 SQLite 数据库,与提供的配置及其父配置(若有)关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
方法 aput_writes
async aput_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
异步存储与检查点关联的中间写入数据到 SQLite 数据库。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
方法 adelete_thread
async adelete_thread(thread_id: str) -> None
描述:
异步删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 get_next_version
get_next_version(
current: Optional[str],
channel: ChannelProtocol
) -> str
描述:
为通道生成下一个版本 ID,默认递增整数版本。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
current | Optional[str] | 当前版本标识符。 | 必填 |
channel | ChannelProtocol | 被版本化的通道。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
str | str | 下一个版本标识符,单调递增。 |
1.10 类 PostgresSaver
继承自: BasePostgresSaver
描述:
PostgresSaver
是一个同步检查点保存器,将检查点存储在 Postgres 数据库中。
1.10.1 示例
基本用法
from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable"
with PostgresSaver.from_conn_string(DB_URI) as memory:
config = {"configurable": {"thread_id": "1"}}
checkpoint_tuple = memory.get_tuple(config)
print(checkpoint_tuple) # 输出: CheckpointTuple(...)
使用检查点 ID
from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable"
with PostgresSaver.from_conn_string(DB_URI) as memory:
config = {
"configurable": {
"thread_id": "1",
"checkpoint_ns": "",
"checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875"
}
}
checkpoint_tuple = memory.get_tuple(config)
print(checkpoint_tuple) # 输出: CheckpointTuple(...)
保存检查点
from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable"
with PostgresSaver.from_conn_string(DB_URI) as memory:
config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
checkpoint = {
"ts": "2024-05-04T06:32:42.235444+00:00",
"id": "1ef4f797-8335-6428-8001-8a1503f9b875",
"channel_values": {"key": "value"}
}
saved_config = memory.put(config, checkpoint, {"source": "input", "step": 1, "writes": {"key": "value"}}, {})
print(saved_config)
# 输出: {'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1ef4f797-8335-6428-8001-8a1503f9b875'}}
列出检查点
from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable"
with PostgresSaver.from_conn_string(DB_URI) as memory:
config = {"configurable": {"thread_id": "1"}}
checkpoints = list(memory.list(config, limit=2))
print(checkpoints) # 输出: [CheckpointTuple(...), CheckpointTuple(...)]
with PostgresSaver.from_conn_string(DB_URI) as memory:
config = {"configurable": {"thread_id": "1"}}
before = {"configurable": {"checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875"}}
checkpoints = list(memory.list(config, before=before))
print(checkpoints) # 输出: [CheckpointTuple(...), ...]
1.10.2 方法
名称 | 描述 |
---|---|
from_conn_string | 从连接字符串创建新的 PostgresSaver 实例。 |
get | 使用给定配置获取检查点。 |
get_tuple | 从数据库获取检查点元组。 |
list | 从数据库列出检查点。 |
put | 将检查点保存到数据库。 |
put_writes | 存储与检查点关联的中间写入数据。 |
delete_thread | 删除特定线程 ID 关联的所有检查点和写入数据。 |
setup | 异步设置检查点数据库。 |
aget | 异步使用给定配置获取检查点。 |
aget_tuple | 异步从数据库获取检查点元组。 |
alist | 异步从数据库列出检查点。 |
aput | 异步将检查点保存到数据库。 |
aput_writes | 异步存储与检查点关联的中间写入数据。 |
adelete_thread | 异步删除特定线程 ID 关联的所有检查点和写入数据。 |
方法 from_conn_string
from_conn_string(
conn_string: str,
*,
pipeline: bool = False
) -> Iterator[PostgresSaver]
描述:
从连接字符串创建新的 PostgresSaver
实例。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
conn_string | str | Postgres 连接信息字符串。 | 必填 |
pipeline | bool | 是否使用管道模式。 | False |
返回值:
名称 | 类型 | 描述 |
---|---|---|
PostgresSaver | Iterator[PostgresSaver] | 新的 PostgresSaver 实例。 |
方法 setup
setup() -> None
描述:
异步设置检查点数据库,创建必要的表(若不存在)并运行数据库迁移。首次使用检查点保存器时,用户必须直接调用此方法。
方法 list
list(
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> Iterator[CheckpointTuple]
描述:
从 Postgres 数据库列出检查点元组,按检查点 ID 降序排列(最新优先)。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定检查点 ID 之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
Iterator[CheckpointTuple] | 符合条件的检查点元组迭代器。 |
方法 get_tuple
get_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
从 Postgres 数据库获取检查点元组。如果配置包含 checkpoint_id
键,则检索匹配线程 ID 和检查点 ID 的检查点;否则,检索给定线程 ID 的最新检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
方法 put
put(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
将检查点保存到 Postgres 数据库,与提供的配置及其父配置(若有)关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
方法 put_writes
put_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
存储与检查点关联的中间写入数据到 Postgres 数据库。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
方法 delete_thread
delete_thread(thread_id: str) -> None
描述:
删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 aget
async aget(config: RunnableConfig) -> Optional[Checkpoint]
描述:
异步使用给定配置获取检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 指定要检索的检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[Checkpoint] | 请求的检查点,若未找到则返回 None 。 |
方法 aget_tuple
async aget_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
异步从 Postgres 数据库获取检查点元组。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 alist
async alist(
config: Optional[RunnableConfig],
*,
filter: Optional[Dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> AsyncIterator[CheckpointTuple]
描述:
异步从 Postgres 数据库列出检查点元组,按检查点 ID 降序排列(最新优先)。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[Dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定检查点 ID 之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
AsyncIterator[CheckpointTuple] | 符合条件的检查点元组异步迭代器。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 aput
async aput(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
异步将检查点保存到 Postgres 数据库,与提供的配置及其父配置(若有)关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 aput_writes
async aput_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
异步存储与检查点关联的中间写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 adelete_thread
async adelete_thread(thread_id: str) -> None
描述:
异步删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
1.11 类 AsyncPostgresSaver
继承自: BasePostgresSaver
描述:
AsyncPostgresSaver
是一个异步检查点保存器,将检查点存储在 Postgres 数据库中,专为异步环境设计,提供更高的 I/O 性能,适合需要高并发的工作负载。
1.11.1 属性
名称 | 类型 | 描述 |
---|---|---|
config_specs | list[ConfigurableFieldSpec] | 定义检查点保存器的配置选项。 |
1.11.2 方法
名称 | 描述 |
---|---|
from_conn_string | 从连接字符串创建新的 AsyncPostgresSaver 实例。 |
get | 使用给定配置获取检查点。 |
get_tuple | 从数据库获取检查点元组。 |
list | 从数据库列出检查点。 |
put | 将检查点保存到数据库。 |
put_writes | 存储与检查点关联的中间写入数据。 |
delete_thread | 删除特定线程 ID 关联的所有检查点和写入数据。 |
setup | 异步设置检查点数据库。 |
aget | 异步使用给定配置获取检查点。 |
aget_tuple | 异步从数据库获取检查点元组。 |
alist | 异步从数据库列出检查点。 |
aput | 异步将检查点保存到数据库。 |
aput_writes | 异步存储与检查点关联的中间写入数据。 |
adelete_thread | 异步删除特定线程 ID 关联的所有检查点和写入数据。 |
方法 from_conn_string
async from_conn_string(
conn_string: str,
*,
pipeline: bool = False,
serde: Optional[SerializerProtocol] = None
) -> AsyncIterator[AsyncPostgresSaver]
描述:
从连接字符串创建新的 AsyncPostgresSaver
实例。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
conn_string | str | Postgres 连接信息字符串。 | 必填 |
pipeline | bool | 是否使用异步管道模式。 | False |
serde | Optional[SerializerProtocol] | 用于序列化的协议。 | None |
返回值:
名称 | 类型 | 描述 |
---|---|---|
AsyncPostgresSaver | AsyncIterator[AsyncPostgresSaver] | 新的 AsyncPostgresSaver 实例。 |
方法 setup
async setup() -> None
描述:
异步设置检查点数据库,创建必要的表(若不存在)并运行数据库迁移。首次使用检查点保存器时,用户必须直接调用此方法。
方法 alist
async alist(
config: Optional[RunnableConfig],
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> AsyncIterator[CheckpointTuple]
描述:
异步从 Postgres 数据库列出检查点元组,按检查点 ID 降序排列(最新优先)。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定检查点 ID 之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
AsyncIterator[CheckpointTuple] | 符合条件的检查点元组异步迭代器。 |
方法 aget_tuple
async aget_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
异步从 Postgres 数据库获取检查点元组。如果配置包含 checkpoint_id
键,则检索匹配线程 ID 和检查点 ID 的检查点;否则,检索给定线程 ID 的最新检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
方法 aput
async aput(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
异步将检查点保存到 Postgres 数据库,与提供的配置及其父配置(若有)关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 aput_writes
async aput_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
异步存储与检查点关联的中间写入数据到 Postgres 数据库。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
引发异常:
类型 | 描述 |
---|---|
NotImplementedError | 自定义检查点保存器需实现此方法。 |
方法 adelete_thread
async adelete_thread(thread_id: str) -> None
描述:
异步删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 list
list(
config: Optional[RunnableConfig],
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None
) -> Iterator[CheckpointTuple]
描述:
从 Postgres 数据库列出检查点元组,按检查点 ID 降序排列(最新优先)。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | Optional[RunnableConfig] | 用于过滤检查点的基础配置。 | 必填 |
filter | Optional[dict[str, Any]] | 元数据的额外过滤条件。 | None |
before | Optional[RunnableConfig] | 仅列出指定检查点 ID 之前的检查点。 | None |
limit | Optional[int] | 返回的最大检查点数量。 | None |
返回值:
类型 | 描述 |
---|---|
Iterator[CheckpointTuple] | 符合条件的检查点元组迭代器。 |
方法 get_tuple
get_tuple(config: RunnableConfig) -> Optional[CheckpointTuple]
描述:
从 Postgres 数据库获取检查点元组。如果配置包含 checkpoint_id
键,则检索匹配线程 ID 和检查点 ID 的检查点;否则,检索给定线程 ID 的最新检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 用于检索检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[CheckpointTuple] | 检索到的检查点元组,若未找到则返回 None 。 |
方法 put
put(
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
new_versions: ChannelVersions
) -> RunnableConfig
描述:
将检查点保存到 Postgres 数据库,与提供的配置及其父配置(若有)关联。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 与检查点关联的配置。 | 必填 |
checkpoint | Checkpoint | 要保存的检查点。 | 必填 |
metadata | CheckpointMetadata | 与检查点一起保存的附加元数据。 | 必填 |
new_versions | ChannelVersions | 此次写入的新通道版本。 | 必填 |
返回值:
名称 | 类型 | 描述 |
---|---|---|
RunnableConfig | RunnableConfig | 存储检查点后的更新配置。 |
方法 put_writes
put_writes(
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = ""
) -> None
描述:
存储与检查点关联的中间写入数据到 Postgres 数据库。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 相关检查点的配置。 | 必填 |
writes | Sequence[tuple[str, Any]] | 要存储的写入列表,格式为 (通道, 值)。 | 必填 |
task_id | str | 创建写入的任务标识符。 | 必填 |
task_path | str | 创建写入的任务路径。 | "" |
方法 delete_thread
delete_thread(thread_id: str) -> None
描述:
删除特定线程 ID 关联的所有检查点和写入数据。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
thread_id | str | 要删除的线程 ID。 | 必填 |
方法 get
get(config: RunnableConfig) -> Optional[Checkpoint]
描述:
使用给定配置获取检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 指定要检索的检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[Checkpoint] | 请求的检查点,若未找到则返回 None 。 |
方法 aget
async aget(config: RunnableConfig) -> Optional[Checkpoint]
描述:
异步使用给定配置获取检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
config | RunnableConfig | 指定要检索的检查点的配置。 | 必填 |
返回值:
类型 | 描述 |
---|---|
Optional[Checkpoint] | 请求的检查点,若未找到则返回 None 。 |
2. 函数
2.1 函数 create_checkpoint
create_checkpoint(
checkpoint: Checkpoint,
channels: Optional[Mapping[str, ChannelProtocol]],
step: int,
*,
id: Optional[str] = None
) -> Checkpoint
描述:
为给定的通道创建检查点。
参数:
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
checkpoint | Checkpoint | 要创建的检查点数据。 | 必填 |
channels | Optional[Mapping[str, ChannelProtocol]] | 通道的映射。 | None |
step | int | 检查点的步骤号。 | 必填 |
id | Optional[str] | 检查点的唯一 ID。 | None |
返回值:
类型 | 描述 |
---|---|
Checkpoint | 创建的检查点对象。 |
3. 模块
3.1 模块 aio
描述:
提供异步 I/O 相关的功能,通常用于支持异步检查点保存器(如 AsyncSqliteSaver
和 AsyncPostgresSaver
)。
3.2 模块 utils
描述:
包含 LangGraph 检查点机制的实用工具函数,可能用于序列化、配置管理或其他辅助功能。
4. 总结
- 检查点机制:LangGraph 的核心功能,用于持久化图状态,支持在多次交互或跨交互中保持一致性。
- 关键类:
CheckpointMetadata
和Checkpoint
:定义检查点的元数据和状态快照。BaseCheckpointSaver
:检查点保存器的基类,提供同步和异步方法。InMemorySaver
:内存存储,适合调试和测试。SqliteSaver
和AsyncSqliteSaver
:基于 SQLite 的同步和异步保存器,适合轻量级应用。PostgresSaver
和AsyncPostgresSaver
:基于 Postgres 的同步和异步保存器,适合生产环境。PersistentDict
:内存中的持久化字典,延迟写入磁盘。SerializerProtocol
和JsonPlusSerializer
:支持检查点数据的序列化和反序列化。
- 使用建议:
- 对于调试或小规模测试,使用
InMemorySaver
。 - 对于轻量级应用,使用
SqliteSaver
或AsyncSqliteSaver
。 - 对于生产环境,推荐使用
PostgresSaver
或AsyncPostgresSaver
以获得更好的性能和可扩展性。 - 在 LangGraph 平台上,无需手动指定检查点保存器,系统会自动使用托管的检查点保存器。
- 对于调试或小规模测试,使用
检查点机制为 LangGraph 提供了强大的状态管理能力,适合构建需要持久化复杂工作流的应用程序。建议从简单的 InMemorySaver
开始,逐步过渡到数据库支持的保存器以满足生产需求。
参考资料: