一、为什么需要持久化? LangGraph 把图的每一步执行状态保存成 checkpoint(检查点) ,解锁了四个核心能力:
能力
说明
Human-in-the-loop
人类可以在任意步骤查看、暂停、修改状态后继续执行
Memory
同一个 thread 内的多轮对话自动保留上下文
Time travel
可以回放历史执行,也可以从任意检查点分叉探索不同路径
Fault-tolerance
节点失败时从上一个成功的 checkpoint 恢复,不重跑已成功的节点
二、核心概念 Thread(线程) 每次对话或任务运行对应一个 thread_id,所有 checkpoint 都挂在这个 ID 下。调用图时必须传:
1 2 config = {"configurable" : {"thread_id" : "1" }} graph.invoke(input , config)
Super-step 与 Checkpoint 每个 super-step 是图的一次”滴答”——所有当前调度的节点(可并行)执行完毕后,保存一次 checkpoint。
对于 START → A → B → END 这样的线性图,会产生 4 个 checkpoint:
1 2 3 4 checkpoint 0: 空状态, next = START checkpoint 1: 用户输入, next = node_a checkpoint 2: node_a 输出后,next = node_b checkpoint 3: node_b 输出后,next = () ← 完成
完整示例 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 from langgraph.graph import StateGraph, START, ENDfrom langgraph.checkpoint.memory import InMemorySaverfrom typing import Annotatedfrom typing_extensions import TypedDictfrom operator import addclass State (TypedDict ): foo: str bar: Annotated[list [str ], add] def node_a (state: State ): return {"foo" : "a" , "bar" : ["a" ]} def node_b (state: State ): return {"foo" : "b" , "bar" : ["b" ]} workflow = StateGraph(State) workflow.add_node(node_a) workflow.add_node(node_b) workflow.add_edge(START, "node_a" ) workflow.add_edge("node_a" , "node_b" ) workflow.add_edge("node_b" , END) checkpointer = InMemorySaver() graph = workflow.compile (checkpointer=checkpointer) config = {"configurable" : {"thread_id" : "1" }} graph.invoke({"foo" : "" , "bar" : []}, config)
六、总结
Checkpointer 是图的”自动存档”,Store 是图的”跨存档共享背包”。两者配合使用,才能构建真正有记忆、可恢复、支持人类干预的 agent 系统。