持久性¶
LangGraph 具有内置的持久化层,通过检查点实现。当你使用检查点编译图时,检查点会在每个超步保存图状态的检查点
。这些检查点保存到线程
中,可以在图执行后访问。由于线程
允许在执行后访问图的状态,因此人机协作、记忆、时间旅行和容错等多种强大功能都成为可能。请参阅此操作指南,获取关于如何为图添加和使用检查点的端到端示例。下面,我们将更详细地讨论这些概念。
线程¶
线程是分配给检查点保存的每个检查点的唯一 ID 或线程标识符。当使用检查点调用图时,你必须在配置的configurable
部分指定一个thread_id
检查点¶
检查点是每个超步保存的图状态快照,由具有以下关键属性的StateSnapshot
对象表示
config
:与此检查点关联的配置。metadata
:与此检查点关联的元数据。values
:此时状态通道的值。next
:在图中接下来要执行的节点名称元组。tasks
:包含要执行的后续任务信息的PregelTask
对象元组。如果该步骤之前已尝试过,它将包含错误信息。如果图在节点内部动态中断,任务将包含与中断相关的额外数据。
让我们看看当一个简单的图如下调用时会保存哪些检查点
import { StateGraph, START, END, MemorySaver, Annotation } from "@langchain/langgraph";
const GraphAnnotation = Annotation.Root({
foo: Annotation<string>
bar: Annotation<string[]>({
reducer: (a, b) => [...a, ...b],
default: () => [],
})
});
function nodeA(state: typeof GraphAnnotation.State) {
return { foo: "a", bar: ["a"] };
}
function nodeB(state: typeof GraphAnnotation.State) {
return { foo: "b", bar: ["b"] };
}
const workflow = new StateGraph(GraphAnnotation);
.addNode("nodeA", nodeA)
.addNode("nodeB", nodeB)
.addEdge(START, "nodeA")
.addEdge("nodeA", "nodeB")
.addEdge("nodeB", END);
const checkpointer = new MemorySaver();
const graph = workflow.compile({ checkpointer });
const config = { configurable: { thread_id: "1" } };
await graph.invoke({ foo: "" }, config);
运行图后,我们期望看到正好4个检查点
- 空检查点,
START
作为下一个要执行的节点 - 包含用户输入
{foo: '', bar: []}
和nodeA
作为下一个要执行的节点的检查点 - 包含
nodeA
输出{foo: 'a', bar: ['a']}
和nodeB
作为下一个要执行的节点的检查点 - 包含
nodeB
输出{foo: 'b', bar: ['a', 'b']}
且没有后续要执行节点的检查点
请注意,bar
通道的值包含两个节点的输出,因为我们为bar
通道定义了一个Reducer。
获取状态¶
与保存的图状态交互时,你必须指定一个线程标识符。你可以通过调用await graph.getState(config)
来查看图的最新状态。这将返回一个StateSnapshot
对象,该对象对应于配置中提供的线程 ID 关联的最新检查点,或者如果提供,则对应于该线程的检查点 ID 关联的检查点。
// Get the latest state snapshot
const config = { configurable: { thread_id: "1" } };
const state = await graph.getState(config);
// Get a state snapshot for a specific checkpoint_id
const configWithCheckpoint = { configurable: { thread_id: "1", checkpoint_id: "1ef663ba-28fe-6528-8002-5a559208592c" } };
const stateWithCheckpoint = await graph.getState(configWithCheckpoint);
在我们的例子中,getState
的输出将如下所示
{
values: { foo: 'b', bar: ['a', 'b'] },
next: [],
config: { configurable: { thread_id: '1', checkpoint_ns: '', checkpoint_id: '1ef663ba-28fe-6528-8002-5a559208592c' } },
metadata: { source: 'loop', writes: { nodeB: { foo: 'b', bar: ['b'] } }, step: 2 },
created_at: '2024-08-29T19:19:38.821749+00:00',
parent_config: { configurable: { thread_id: '1', checkpoint_ns: '', checkpoint_id: '1ef663ba-28f9-6ec4-8001-31981c2c39f8' } },
tasks: []
}
获取状态历史¶
你可以通过调用await graph.getStateHistory(config)
获取给定线程的完整图执行历史。这将返回一个与配置中提供的线程 ID 关联的StateSnapshot
对象列表。重要的是,检查点将按时间顺序排列,最近的检查点/StateSnapshot
位于列表的首位。
const config = { configurable: { thread_id: "1" } };
const history = await graph.getStateHistory(config);
在我们的例子中,getStateHistory
的输出将如下所示
[
{
values: { foo: 'b', bar: ['a', 'b'] },
next: [],
config: { configurable: { thread_id: '1', checkpoint_ns: '', checkpoint_id: '1ef663ba-28fe-6528-8002-5a559208592c' } },
metadata: { source: 'loop', writes: { nodeB: { foo: 'b', bar: ['b'] } }, step: 2 },
created_at: '2024-08-29T19:19:38.821749+00:00',
parent_config: { configurable: { thread_id: '1', checkpoint_ns: '', checkpoint_id: '1ef663ba-28f9-6ec4-8001-31981c2c39f8' } },
tasks: [],
},
{
values: { foo: 'a', bar: ['a'] },
next: ['nodeB'],
config: { configurable: { thread_id: '1', checkpoint_ns: '', checkpoint_id: '1ef663ba-28f9-6ec4-8001-31981c2c39f8' } },
metadata: { source: 'loop', writes: { nodeA: { foo: 'a', bar: ['a'] } }, step: 1 },
created_at: '2024-08-29T19:19:38.819946+00:00',
parent_config: { configurable: { thread_id: '1', checkpoint_ns: '', checkpoint_id: '1ef663ba-28f4-6b4a-8000-ca575a13d36a' } },
tasks: [{ id: '6fb7314f-f114-5413-a1f3-d37dfe98ff44', name: 'nodeB', error: null, interrupts: [] }],
},
// ... (other checkpoints)
]
重放¶
也可以重播之前的图执行。如果我们将图调用
时带有thread_id
和checkpoint_id
,那么我们将从与checkpoint_id
对应的检查点重播图。
thread_id
只是一个线程的 ID。这是始终必需的。checkpoint_id
此标识符指向线程中的特定检查点。
在调用图时,你必须将这些作为配置的configurable
部分传入
// { configurable: { thread_id: "1" } } // valid config
// { configurable: { thread_id: "1", checkpoint_id: "0c62ca34-ac19-445d-bbb0-5b4984975b2a" } } // also valid config
const config = { configurable: { thread_id: "1" } };
await graph.invoke(inputs, config);
重要的是,LangGraph 知道某个特定的检查点是否以前执行过。如果执行过,LangGraph 只会重播图中该特定的步骤,而不会重新执行该步骤。有关重播的更多信息,请参阅此关于时间旅行的操作指南。
更新状态¶
除了从特定的检查点
重放图之外,我们还可以编辑图状态。我们通过使用graph.updateState()
来完成此操作。此方法有三个不同的参数
config
¶
配置应包含thread_id
,指定要更新哪个线程。当只传递thread_id
时,我们更新(或分叉)当前状态。可选地,如果我们包含checkpoint_id
字段,则分叉选定的检查点。
values
¶
这些将用于更新状态的值。请注意,此更新的处理方式与来自节点的任何更新完全相同。这意味着这些值将传递给reducer函数,如果它们为图状态中的某些通道定义了。这意味着updateState
不会自动覆盖每个通道的通道值,而只覆盖没有reducer的通道。让我们通过一个示例来了解。
假设你已定义图的状态,其架构如下(参见上面的完整示例)
import { Annotation } from "@langchain/langgraph";
const GraphAnnotation = Annotation.Root({
foo: Annotation<string>
bar: Annotation<string[]>({
reducer: (a, b) => [...a, ...b],
default: () => [],
})
});
现在假设图的当前状态是
如果你按如下方式更新状态
那么图的新状态将是
foo
键(通道)被完全改变(因为没有为该通道指定 reducer,所以updateState
会覆盖它)。然而,为bar
键指定了一个 reducer,因此它将"b"
附加到bar
的状态中。
作为节点¶
调用updateState
时可以可选指定的最后一个参数是第三个位置参数asNode
。如果你提供了它,更新将被应用,就好像它来自节点asNode
一样。如果没有提供asNode
,如果不存在歧义,它将被设置为最后更新状态的节点。这之所以重要是因为下一步要执行的步骤取决于最后更新状态的节点,因此这可以用来控制下一个执行的节点。有关状态分叉的更多信息,请参阅此关于时间旅行的操作指南。
内存存储¶
状态模式指定了一组在图执行时填充的键。如上所述,状态可以由检查点器在每个图步骤写入线程,从而实现状态持久化。
但是,如果我们想在跨线程保留一些信息怎么办?考虑一个聊天机器人,我们希望在与该用户的所有聊天对话(即线程)中保留关于该用户的特定信息!
仅靠检查点,我们无法在线程之间共享信息。这促使了对Store
接口的需求。作为说明,我们可以定义一个InMemoryStore
来存储用户在跨线程中的信息。首先,让我们在不使用LangGraph的情况下单独展示这一点。
内存由一个元组
命名空间,在这个特定示例中将是[<user_id>, "memories"]
。命名空间可以是任何长度,表示任何内容,不一定与用户特定。
我们使用store.put
方法将内存保存到存储中的命名空间。这样做时,我们指定如上定义的命名空间,以及内存的键值对:键只是内存的唯一标识符(memoryId
),值(一个对象)就是内存本身。
import { v4 as uuid4 } from 'uuid';
const memoryId = uuid4();
const memory = { food_preference: "I like pizza" };
await inMemoryStore.put(namespaceForMemory, memoryId, memory);
我们可以使用store.search
读取命名空间中的内存,它将返回给定用户的所有内存作为列表。最新的内存在列表的最后。
const memories = await inMemoryStore.search(namespaceForMemory);
console.log(memories.at(-1));
/*
{
'value': {'food_preference': 'I like pizza'},
'key': '07e0caf4-1631-47b7-b15f-65515d4c1843',
'namespace': ['1', 'memories'],
'created_at': '2024-10-02T17:22:31.590602+00:00',
'updated_at': '2024-10-02T17:22:31.590605+00:00'
}
*/
检索到的内存具有的属性是
value
:此内存的值(本身是一个字典)key
:此内存在此命名空间中的 UUIDnamespace
:字符串列表,此内存类型的命名空间created_at
:此内存创建的时间戳updated_at
:此内存更新的时间戳
有了这一切,我们在 LangGraph 中使用inMemoryStore
。inMemoryStore
与检查点器协同工作:检查点器如上所述将状态保存到线程,而inMemoryStore
允许我们存储任意信息以便跨线程访问。我们按如下方式将图与检查点器和inMemoryStore
一起编译。
import { MemorySaver } from "@langchain/langgraph";
// We need this because we want to enable threads (conversations)
const checkpointer = new MemorySaver();
// ... Define the graph ...
// Compile the graph with the checkpointer and store
const graph = builder.compile({
checkpointer,
store: inMemoryStore
});
我们像以前一样用thread_id
调用图,也用user_id
调用图,我们将用它来为我们的内存命名空间到这个特定用户,正如我们上面所展示的。
// Invoke the graph
const user_id = "1";
const config = { configurable: { thread_id: "1", user_id } };
// First let's just say hi to the AI
const stream = await graph.stream(
{ messages: [{ role: "user", content: "hi" }] },
{ ...config, streamMode: "updates" },
);
for await (const update of stream) {
console.log(update);
}
我们可以通过将config: LangGraphRunnableConfig
作为节点参数传递,在任何节点中访问inMemoryStore
和user_id
。然后,就像我们上面看到的那样,只需使用put
方法将内存保存到存储中。
import {
type LangGraphRunnableConfig,
MessagesAnnotation,
} from "@langchain/langgraph";
const updateMemory = async (
state: typeof MessagesAnnotation.State,
config: LangGraphRunnableConfig
) => {
// Get the store instance from the config
const store = config.store;
// Get the user id from the config
const userId = config.configurable.user_id;
// Namespace the memory
const namespace = [userId, "memories"];
// ... Analyze conversation and create a new memory
// Create a new memory ID
const memoryId = uuid4();
// We create a new memory
await store.put(namespace, memoryId, { memory });
};
正如我们上面所示,我们还可以在任何节点中访问存储,并使用search
来获取内存。请记住,内存以可以转换为字典的对象列表形式返回。
const memories = inMemoryStore.search(namespaceForMemory);
console.log(memories.at(-1));
/*
{
'value': {'food_preference': 'I like pizza'},
'key': '07e0caf4-1631-47b7-b15f-65515d4c1843',
'namespace': ['1', 'memories'],
'created_at': '2024-10-02T17:22:31.590602+00:00',
'updated_at': '2024-10-02T17:22:31.590605+00:00'
}
*/
我们可以访问内存并在模型调用中使用它们。
const callModel = async (
state: typeof StateAnnotation.State,
config: LangGraphRunnableConfig
) => {
const store = config.store;
// Get the user id from the config
const userId = config.configurable.user_id;
// Get the memories for the user from the store
const memories = await store.search([userId, "memories"]);
const info = memories.map((memory) => {
return JSON.stringify(memory.value);
}).join("\n");
// ... Use memories in the model call
}
如果我们创建一个新线程,只要user_id
相同,我们仍然可以访问相同的内存。
// Invoke the graph
const config = { configurable: { thread_id: "2", user_id: "1" } };
// Let's say hi again
const stream = await graph.stream(
{ messages: [{ role: "user", content: "hi, tell me about my memories" }] },
{ ...config, streamMode: "updates" },
);
for await (const update of stream) {
console.log(update);
}
当我们使用 LangGraph API 时,无论是在本地(例如,在 LangGraph Studio 中)还是使用 LangGraph Cloud,内存存储默认可用,无需在图编译期间指定。
检查点库¶
在底层,检查点功能由符合BaseCheckpointSaver接口的检查点对象提供支持。LangGraph 提供了多种检查点实现,所有这些都通过独立的、可安装的库实现
@langchain/langgraph-checkpoint
:检查点保存器的基本接口(BaseCheckpointSaver)和序列化/反序列化接口(SerializerProtocol)。包括用于实验的内存检查点实现(MemorySaver)。LangGraph 包含@langchain/langgraph-checkpoint
。@langchain/langgraph-checkpoint-sqlite
:使用 SQLite 数据库的 LangGraph 检查点实现(SqliteSaver)。非常适合实验和本地工作流。需要单独安装。@langchain/langgraph-checkpoint-postgres
:一个高级检查点,使用 Postgres 数据库(PostgresSaver),在 LangGraph Cloud 中使用。非常适合在生产环境中使用。需要单独安装。
检查点接口¶
每个检查点都符合BaseCheckpointSaver接口并实现了以下方法
.put
- 存储包含其配置和元数据的检查点。.putWrites
- 存储链接到检查点的中间写入(即待定写入)。.getTuple
- 使用给定配置(thread_id
和checkpoint_id
)获取检查点元组。这用于在graph.getState()
中填充StateSnapshot
。.list
- 列出符合给定配置和过滤条件的检查点。这用于在graph.getStateHistory()
中填充状态历史记录。
序列化器¶
当检查点保存图状态时,它们需要序列化状态中的通道值。这是通过序列化器对象完成的。@langchain/langgraph-checkpoint
定义了实现序列化器的协议以及一个处理各种类型(包括 LangChain 和 LangGraph 原语、日期时间、枚举等)的默认实现。
功能¶
人机协作 (Human-in-the-loop)¶
首先,检查点有助于人机协作工作流,允许人类检查、中断和批准图步骤。这些工作流需要检查点,因为人类必须能够随时查看图的状态,并且图必须能够在人类对状态进行任何更新后恢复执行。有关具体示例,请参阅这些操作指南。
内存¶
其次,检查点允许在交互之间保留“记忆”。在重复的人机交互(如对话)情况下,任何后续消息都可以发送到该线程,该线程将保留其对先前消息的记忆。有关如何使用检查点添加和管理对话记忆的端到端示例,请参阅此操作指南。
时光穿梭¶
第三,检查点允许“时间旅行”,允许用户重放先前的图执行以审查和/或调试特定的图步骤。此外,检查点使得在任意检查点分叉图状态以探索替代轨迹成为可能。
容错¶
最后,检查点还提供容错和错误恢复:如果一个或多个节点在给定超步中失败,你可以从上一个成功步骤重新启动图。此外,当图节点在给定超步中执行中途失败时,LangGraph 会存储在该超步中成功完成的任何其他节点的待定检查点写入,这样无论何时我们从该超步恢复图执行时,我们都不会重新运行成功的节点。
待定写入¶
此外,当图节点在给定超步中执行中途失败时,LangGraph 会存储在该超步中成功完成的任何其他节点的待定检查点写入,这样无论何时我们从该超步恢复图执行时,我们都不会重新运行成功的节点。