跳至内容

持久化

LangGraph 内置了持久化层,通过检查点器实现。当您使用检查点器编译图时,检查点器会在每个超级步骤保存图状态的 checkpoint。这些检查点会保存到 thread 中,图执行后可以访问这些线程。由于 threads 允许在图执行后访问图的状态,因此人机协作、内存、时间旅行和容错等多种强大功能都成为可能。有关如何在图中添加和使用检查点器的端到端示例,请参阅此操作指南。下面,我们将更详细地讨论这些概念。

Checkpoints

线程

线程是检查点器保存的每个检查点分配的唯一 ID 或线程标识符。在使用检查点器调用图时,您必须在配置的可配置部分中指定 thread_id

{"configurable": {"thread_id": "1"}}

检查点

检查点是在每个超级步骤保存的图状态的快照,由 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)
]

State

重放

也可以回放之前的图执行。如果我们使用 thread_idcheckpoint_id 调用图,那么我们将从与 checkpoint_id 对应的检查点重放图。

  • thread_id 只是线程的 ID。这是始终必需的。
  • checkpoint_id:此标识符指代线程中的特定检查点。

在调用图时,您必须将这些作为配置的可配置部分传递。

// { 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 只需重放图中的该特定步骤,而不会重新执行该步骤。有关重放的更多信息,请参阅此时间旅行操作指南

Replay

更新状态

除了从特定 checkpoints 重放图之外,我们还可以编辑图状态。我们通过 graph.updateState() 来实现这一点。此方法有三个不同的参数:

config

配置应包含 thread_id,指定要更新哪个线程。当只传递 thread_id 时,我们更新(或分叉)当前状态。可选地,如果包含 checkpoint_id 字段,则分叉该选定的检查点。

values

这些是用于更新状态的值。请注意,此更新的处理方式与来自节点的任何更新完全相同。这意味着这些值将传递给reducer函数(如果它们在图状态的某些通道中定义)。这意味着 updateState 不会自动覆盖每个通道的通道值,而只覆盖没有 reducer 的通道。让我们来看一个例子。

假设您已使用以下 schema 定义了图的状态(参见上面的完整示例):

import { Annotation } from "@langchain/langgraph";

const GraphAnnotation = Annotation.Root({
  foo: Annotation<string>
  bar: Annotation<string[]>({
    reducer: (a, b) => [...a, ...b],
    default: () => [],
  })
});

现在假设图的当前状态是:

{ foo: "1", bar: ["a"] }

如果您按如下方式更新状态:

await graph.updateState(config, { foo: "2", bar: ["b"] });

那么图的新状态将是:

{ foo: "2", bar: ["a", "b"] }

foo 键(通道)已完全改变(因为该通道没有指定 reducer,因此 updateState 会覆盖它)。然而,为 bar 键指定了一个 reducer,因此它将 "b" 附加到 bar 的状态。

作为节点

调用 updateState 时可以可选指定的最后一个参数是第三个位置参数 asNode。如果提供此参数,更新将如同来自节点 asNode 一样应用。如果未提供 asNode,则在不模糊的情况下,它将被设置为最后更新状态的节点。这之所以重要,是因为下一步要执行的步骤取决于最后提供更新的节点,因此这可用于控制哪个节点接下来执行。有关分叉状态的更多信息,请参阅此时间旅行操作指南

Update

内存存储

Update

一个状态 schema 指定了在图执行时填充的一组键。如上所述,状态可以通过检查点器在每个图步骤写入线程,从而实现状态持久化。

但是,如果我们想在线程之间保留一些信息怎么办?考虑一个聊天机器人的情况,我们希望在与用户进行的所有聊天对话(例如线程)中保留有关该用户的特定信息!

仅靠检查点器,我们无法在线程之间共享信息。这促使了 Store 接口的需求。作为示例,我们可以定义一个 InMemoryStore 来存储用户在不同线程中的信息。首先,让我们在不使用 LangGraph 的情况下单独展示这一点。

import { InMemoryStore } from "@langchain/langgraph";

const inMemoryStore = new InMemoryStore();

内存由一个 tuple 进行命名空间管理,在此特定示例中为 [, "memories"]。命名空间可以是任意长度,并表示任何内容,不一定与用户相关。

const userId = "1";
const namespaceForMemory = [userId, "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:此内存在此命名空间中的 UUID
  • namespace:一个字符串列表,此内存类型的命名空间
  • 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 作为节点参数传递,在任何节点中访问 inMemoryStoreuser_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 数据库 (SqliteSaver) 的 LangGraph 检查点器实现。非常适合实验和本地工作流。需要单独安装。
  • @langchain/langgraph-checkpoint-postgres:使用 Postgres 数据库 (PostgresSaver) 的高级检查点器,用于 LangGraph Cloud。非常适合在生产环境中使用。需要单独安装。

检查点器接口

每个检查点器都符合 BaseCheckpointSaver 接口并实现以下方法:

  • .put - 存储带其配置和元数据的检查点。
  • .putWrites - 存储与检查点关联的中间写入(即待处理写入)。
  • .getTuple - 使用给定配置(thread_idcheckpoint_id)获取检查点元组。这用于在 graph.getState() 中填充 StateSnapshot
  • .list - 列出与给定配置和过滤条件匹配的检查点。这用于在 graph.getStateHistory() 中填充状态历史。

序列化器

当检查点器保存图状态时,它们需要序列化状态中的通道值。这通过序列化器对象完成。@langchain/langgraph-checkpoint 定义了一个实现序列化器的协议,以及一个处理多种类型(包括 LangChain 和 LangGraph 原语、日期时间、枚举等)的默认实现。

功能

人机协作

首先,检查点器通过允许人类检查、中断和批准图步骤来促进人机协作工作流。这些工作流需要检查点器,因为人类必须能够随时查看图的状态,并且图必须能够在人类对状态进行任何更新后恢复执行。有关具体示例,请参阅这些操作指南

内存

其次,检查点器允许在交互之间拥有“内存”。在重复的人机交互(如对话)中,任何后续消息都可以发送到该线程,该线程将保留其对先前消息的记忆。有关如何使用检查点器添加和管理对话内存的端到端示例,请参阅此操作指南

时间旅行

第三,检查点器允许“时间旅行”,用户可以重放之前的图执行,以查看和/或调试特定的图步骤。此外,检查点器使得在任意检查点分叉图状态以探索替代轨迹成为可能。

容错

最后,检查点还提供容错和错误恢复:如果一个或多个节点在给定超级步骤中失败,您可以从上次成功的步骤重新启动图。此外,当图节点在给定超级步骤中执行中途失败时,LangGraph 会存储在该超级步骤中成功完成的任何其他节点的待处理检查点写入,以便当我们从该超级步骤恢复图执行时,我们不会重新运行成功的节点。

待处理写入

此外,当图节点在给定超级步骤中执行中途失败时,LangGraph 会存储在该超级步骤中成功完成的任何其他节点的待处理检查点写入,以便当我们从该超级步骤恢复图执行时,我们不会重新运行成功的节点。