跳转至

指南 06 · 断点持久化

wf.compile() 默认用内存断点,进程退出就丢。生产环境需要「进程重启、断点与交互不丢」,就要把断点存到数据库。本章统一讲接入方式。

1. 为什么不能直接用默认序列化

断点内容含 _ctx(带 stream_callback 闭包),LangGraph 默认 msgpack 无法落库。因此持久化必须注入框架的 PersistentSerializer(保存前剥离 _ctx、恢复时由网关注入新 ctx)。

别绕过这套——它是本框架「断点含运行上下文闭包」这一设计的前提,绕开恢复会炸。

2. 三件套统一公式

不管接哪个数据库,模式都一样(三步同构):

from agentframework.runtime.checkpointer import PersistentSerializer

# ① 建连接
conn = ...  # 库相关连接
# ② 构造 saver,注入 PersistentSerializer
saver = SomeAsyncSaver(conn, serde=PersistentSerializer())
# ③ 自动建表 + 传给 compile
await saver.setup()
app = wf.compile(store=saver)

同步 vs 异步(极易踩坑):

  • 网关(SSE)是异步的 → 必须用各 saver 的异步版本AsyncSqliteSaver / AsyncPostgresSaver / AIOMySQLSaver)。
  • 仅在程序内同步 invoke 才用同步版(SqliteSaver / PostgresSaver / PyMySQLSaver)。
  • MongoDB 的 MongoDBSaver 本身支持异步驱动。

3. 接入矩阵

数据库 saver(异步优先)
SQLite langgraph-checkpoint-sqlite(核心依赖,随框架) AsyncSqliteSaver / SqliteSaver
PostgreSQL agentframework[pg] AsyncPostgresSaver / PostgresSaver
MongoDB agentframework[mongo] MongoDBSaver
MySQL ≥8.0.19 / MariaDB ≥10.7.1 agentframework[mysql] AIOMySQLSaver / PyMySQLSaver

4. 各库最小片段

SQLite

import aiosqlite
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from agentframework.runtime.checkpointer import PersistentSerializer

conn = await aiosqlite.connect("checkpoints.db")
saver = AsyncSqliteSaver(conn, serde=PersistentSerializer())
await saver.setup()
app = wf.compile(store=saver)

PostgreSQL

import psycopg
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
from agentframework.runtime.checkpointer import PersistentSerializer

conn = await psycopg.AsyncConnection.connect(
    "postgresql://user:password@localhost:5432/agentframework",
    autocommit=True,
)
saver = AsyncPostgresSaver(conn, serde=PersistentSerializer())
await saver.setup()
app = wf.compile(store=saver)

MongoDB

from motor.motor_asyncio import AsyncIOMotorClient
from langgraph.checkpoint.mongodb.aio import MongoDBSaver
from agentframework.runtime.checkpointer import PersistentSerializer

client = AsyncIOMotorClient("mongodb://localhost:27017")
saver = MongoDBSaver(client, db_name="agentframework", serde=PersistentSerializer())
await saver.setup()
app = wf.compile(store=saver)

MySQL

import asyncmy
from langgraph.checkpoint.mysql.aio import AIOMySQLSaver
from agentframework.runtime.checkpointer import PersistentSerializer

pool = await asyncmy.create_pool(
    host="localhost",
    user="root",
    password="pwd",
    db="agentframework",
    autocommit=True,
)
saver = AIOMySQLSaver(pool, serde=PersistentSerializer())
await saver.setup()
app = wf.compile(store=saver)

5. 恢复语义

  • chatId → thread_id 落库;同会话断点按版本链保存。
  • interactive 挂起的 writes 落库不丢:进程重启后,同一 chatId 续跑恢复交互。
  • chatId 续接、异 chatId 完全并行隔离。

6. 完整可运行示例

本站收录了各库接入的完整可运行源码与运行说明:

下一步

  • 断点 + 交互式对话概念 → 运行时与网关指南 04
  • 想自定义断点存储抽象 → 看仓库 src/agentframework/runtime/checkpointer.pystate/checkpoint.py