智能体短期与长期记忆的管理策略

该资料讨论为智能体状态加入短期记忆以支持多轮对话,并加入长期记忆跨会话保存用户或应用级数据,同时给出裁剪、删除、摘要消息及检查点管理等短期记忆处理方式。

AI 应用程序需要 [内存](<https://docs.langchain.com/oss/python/concepts/memory>) 在 LangGraph 中,您可以添加两种类型的内存: - [添加短期内存](<https://docs.langchain.com/oss/python/langgraph/add-memory#add-short-term-memory>) 作为你经纪人的一部分 [状态](<https://docs.langchain.com/oss/python/langgraph/graph-api#state>) 以允许多回合对话。 - [添加长期内存](<https://docs.langchain.com/oss/python/langgraph/add-memory#add-long-term-memory>) 用于存储整个会话中针对用户的或应用程序级的数据。 ## 添加短期内存 **短期** 内存( 线程级) [持久性](<https://docs.langchain.com/oss/python/langgraph/persistence>))使代理能够跟踪多回合对话。要添加短期内存: ``` from langgraph.checkpoint.memory import InMemorySaver from langgraph.graph import StateGraph checkpointer = InMemorySaver() builder = StateGraph(...) graph = builder.compile(checkpointer=checkpointer) graph.invoke( {"messages": [{"role": "user", "content": "hi! i am Bob"}]}, {"configurable": {"thread_id": "1"}}, ) ``` ### 用于生产 在生产时,使用由数据库支持的检查器: ``` from langgraph.checkpoint.postgres import PostgresSaver DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" with PostgresSaver.from_conn_string(DB_URI) as checkpointer: builder = StateGraph(...) graph = builder.compile(checkpointer=checkpointer) ``` 示例:使用 Postgres 检查器 ``` pip install -U "psycopg[binary,pool]" langgraph langgraph-checkpoint-postgres ``` 你需要打电话 `checkpointer.setup()` 您第一次使用 Postgres 检查器 - 同步( S) - 自动同步 ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.postgres import PostgresSaver model = init_chat_model(model="claude-haiku-4-5-20251001") DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" with PostgresSaver.from_conn_string(DB_URI) as checkpointer: # checkpointer.setup() def call_model(state: MessagesState): response = model.invoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = graph.stream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) stream = graph.stream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) ``` ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver model = init_chat_model(model="claude-haiku-4-5-20251001") DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" async with AsyncPostgresSaver.from_conn_string(DB_URI) as checkpointer: # await checkpointer.setup() async def call_model(state: MessagesState): response = await model.ainvoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = await graph.astream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) ``` 示例:使用 MongoDB 检查器 ``` pip install -U pymongo langgraph langgraph-checkpoint-mongodb ``` **设置** 用来使用 [MongoDB 检查器](<https://pypi.org/project/langgraph-checkpoint-mongodb/>),您需要一个 MongoDB 集群。 [本指南](<https://www.mongodb.com/docs/atlas/tutorial/deploy-free-tier-cluster/>) 用于创建组,如果您还没有。对于以代理为主的走过,请参见 [使用 MongoDB Atlas 的短期内存](<https://docs.langchain.com/oss/python/integrations/memory/mongodb-short-term-memory>). - 同步( S) - 自动同步 ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.mongodb import MongoDBSaver model = init_chat_model(model="claude-haiku-4-5-20251001") MONGODB_URI = "localhost:27017" with MongoDBSaver.from_conn_string(MONGODB_URI) as checkpointer: def call_model(state: MessagesState): response = model.invoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = graph.stream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) stream = graph.stream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) ``` ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.mongodb.aio import AsyncMongoDBSaver model = init_chat_model(model="claude-haiku-4-5-20251001") MONGODB_URI = "localhost:27017" async with AsyncMongoDBSaver.from_conn_string(MONGODB_URI) as checkpointer: async def call_model(state: MessagesState): response = await model.ainvoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = await graph.astream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) ``` 示例:使用 Redis 检查器 ``` pip install -U langgraph langgraph-checkpoint-redis ``` 你需要打电话 `checkpointer.setup()` 你第一次使用 Redis 检查器。 - 同步( S) - 自动同步 ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.redis import RedisSaver model = init_chat_model(model="claude-haiku-4-5-20251001") DB_URI = "redis://localhost:6379" with RedisSaver.from_conn_string(DB_URI) as checkpointer: # checkpointer.setup() def call_model(state: MessagesState): response = model.invoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = graph.stream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) stream = graph.stream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) ``` ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.redis.aio import AsyncRedisSaver model = init_chat_model(model="claude-haiku-4-5-20251001") DB_URI = "redis://localhost:6379" async with AsyncRedisSaver.from_conn_string(DB_URI) as checkpointer: # await checkpointer.asetup() async def call_model(state: MessagesState): response = await model.ainvoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = await graph.astream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) ``` 示例:使用甲骨文检查符 ``` pip install -U langgraph langgraph-oracledb ``` **设置** 用来使用 [甲骨文检查符](<https://pypi.org/project/langgraph-oracledb/>),您需要 Oracle AI 数据库实例。本地容器(例如) `gvenzl/oracle-free:23-slim`)或OCI中的甲骨文自治数据库,两者都工作. 你需要打电话 `checkpointer.setup()` 这是你第一次使用甲骨文检查器。 - 同步( S) - 自动同步 ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph_oracledb.checkpoint.oracle import OracleSaver model = init_chat_model(model="claude-haiku-4-5-20251001") DB_URI = "user/password@localhost:1521/FREEPDB1" with OracleSaver.from_conn_string(DB_URI) as checkpointer: # checkpointer.setup() def call_model(state: MessagesState): response = model.invoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = graph.stream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) stream = graph.stream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) for snapshot in stream.values: print(snapshot) ``` ``` from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph_oracledb.checkpoint.oracle import AsyncOracleSaver model = init_chat_model(model="claude-haiku-4-5-20251001") DB_URI = "user/password@localhost:1521/FREEPDB1" async with AsyncOracleSaver.from_conn_string(DB_URI) as checkpointer: # await checkpointer.setup() async def call_model(state: MessagesState): response = await model.ainvoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = { "configurable": { "thread_id": "1" } } stream = await graph.astream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) ``` ### 在子图中使用 如果您的图表包含 [子图](<https://docs.langchain.com/oss/python/langgraph/use-subgraphs>),您只需在编译父图时提供检查器。LangGraph会自动将检查器传播到子图中。 ``` from langgraph.graph import START, StateGraph from langgraph.checkpoint.memory import InMemorySaver from typing import TypedDict class State(TypedDict): foo: str # Subgraph def subgraph_node_1(state: State): return {"foo": state["foo"] + "bar"} subgraph_builder = StateGraph(State) subgraph_builder.add_node(subgraph_node_1) subgraph_builder.add_edge(START, "subgraph_node_1") subgraph = subgraph_builder.compile() # Parent graph builder = StateGraph(State) builder.add_node("node_1", subgraph) builder.add_edge(START, "node_1") checkpointer = InMemorySaver() graph = builder.compile(checkpointer=checkpointer) ``` 您可以配置特定子图检查行为。 见 [子图持久性](<https://docs.langchain.com/oss/python/langgraph/use-subgraphs#subgraph-persistence>) 关于持久性水平的详情,包括中断支持和状态延续。 ``` subgraph_builder = StateGraph(...) subgraph = subgraph_builder.compile(checkpointer=True) ``` ## 添加长期内存 使用长期内存存储用户专用或应用程序专用的数据,贯穿对话. ``` from langgraph.store.memory import InMemoryStore from langgraph.graph import StateGraph store = InMemoryStore() builder = StateGraph(...) graph = builder.compile(store=store) ``` ### 访问节点内的商店 一旦与商店一起编译一个图表,LangGraph会自动将商店注入您的节点功能中. 建议的商店访问方式是通过 `Runtime` 对象。 ``` from dataclasses import dataclass from langgraph.runtime import Runtime from langgraph.graph import StateGraph, MessagesState, START from langchain_core.utils.uuid import uuid7 @dataclass class Context: user_id: str async def call_model(state: MessagesState, runtime: Runtime[Context]): user_id = runtime.context.user_id namespace = (user_id, "memories") # Search for relevant memories memories = await runtime.store.asearch( namespace, query=state["messages"][-1].content, limit=3 ) info = "\n".join([d.value["data"] for d in memories]) # ... Use memories in model call # Store a new memory await runtime.store.aput( namespace, str(uuid7()), {"data": "User prefers dark mode"} ) builder = StateGraph(MessagesState, context_schema=Context) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(store=store) # Pass context at invocation time graph.invoke( {"messages": [{"role": "user", "content": "hi"}]}, {"configurable": {"thread_id": "1"}}, context=Context(user_id="1"), ) ``` ### 用于生产 在生产时,使用数据库支持的商店: ``` from langgraph.store.postgres import PostgresStore DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" with PostgresStore.from_conn_string(DB_URI) as store: builder = StateGraph(...) graph = builder.compile(store=store) ``` 示例:使用 Postgres 存储 ``` pip install -U "psycopg[binary,pool]" langgraph langgraph-checkpoint-postgres ``` 你需要打电话 `store.setup()` 您第一次使用 Postgres 商店 - 自动同步 - 同步( S) ``` from dataclasses import dataclass from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver from langgraph.store.postgres.aio import AsyncPostgresStore from langgraph.runtime import Runtime model = init_chat_model(model="claude-haiku-4-5-20251001") @dataclass class Context: user_id: str async def call_model( state: MessagesState, runtime: Runtime[Context], ): user_id = runtime.context.user_id namespace = ("memories", user_id) memories = await runtime.store.asearch(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" await runtime.store.aput(namespace, str(uuid7()), {"data": memory}) response = await model.ainvoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" async with ( AsyncPostgresStore.from_conn_string(DB_URI) as store, AsyncPostgresSaver.from_conn_string(DB_URI) as checkpointer, ): # await store.setup() # await checkpointer.setup() builder = StateGraph(MessagesState, context_schema=Context) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) config = {"configurable": {"thread_id": "1"}} stream = await graph.astream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", context=Context(user_id="1"), ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) config = {"configurable": {"thread_id": "2"}} stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", context=Context(user_id="1"), ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) ``` ``` from dataclasses import dataclass from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.postgres import PostgresSaver from langgraph.store.postgres import PostgresStore from langgraph.runtime import Runtime model = init_chat_model(model="claude-haiku-4-5-20251001") @dataclass class Context: user_id: str def call_model( state: MessagesState, runtime: Runtime[Context], ): user_id = runtime.context.user_id namespace = ("memories", user_id) memories = runtime.store.search(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" runtime.store.put(namespace, str(uuid7()), {"data": memory}) response = model.invoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable" with ( PostgresStore.from_conn_string(DB_URI) as store, PostgresSaver.from_conn_string(DB_URI) as checkpointer, ): # store.setup() # checkpointer.setup() builder = StateGraph(MessagesState, context_schema=Context) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) config = {"configurable": {"thread_id": "1"}} stream = graph.stream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", context=Context(user_id="1"), ) for snapshot in stream.values: print(snapshot) config = {"configurable": {"thread_id": "2"}} stream = graph.stream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", context=Context(user_id="1"), ) for snapshot in stream.values: print(snapshot) ``` 示例:使用 MongoDB 商店 ``` pip install -U langgraph-store-mongodb langgraph-checkpoint-mongodb ``` 语义搜索 `query` 需要 MongoDB 矢量搜索 (`$vectorSearch`),运行于 [MongoDB 地图集](<https://www.mongodb.com/docs/atlas/>) 或自行管理的 MongoDB 与 [搜索和矢量搜索](<https://www.mongodb.com/docs/search/self-managed/current/>) (`mongot`。一个平原。 `mongod` 不含 `mongot` 还不够,通过 `index_config` 从 `create_vector_index_config` 当您打开商店时。 索引创建可以超过默认的 15 秒等待, 所以设置 `auto_index_timeout` 关于Atlas集群设置,请参见 [本指南](<https://www.mongodb.com/docs/atlas/tutorial/deploy-free-tier-cluster/>)。关于向量指数设置和以代理人为重点的走过,参见 [使用 MongoDB Atlas 的长期内存](<https://docs.langchain.com/oss/python/integrations/memory/mongodb-long-term-memory>). - 自动同步 - 同步( S) ``` import os from collections.abc import Sequence from dataclasses import dataclass from uuid import uuid4 from langchain.chat_models import init_chat_model from langgraph.checkpoint.mongodb import MongoDBSaver from langgraph.graph import StateGraph, MessagesState, START from langgraph.runtime import Runtime from langgraph.store.mongodb import MongoDBStore, create_vector_index_config model = init_chat_model(model="claude-haiku-4-5-20251001") def embed(texts: Sequence[str]) -> list[list[float]]: # Replace with an embeddings model or LangChain Embeddings instance return [[1.0, 2.0] for _ in texts] @dataclass class Context: user_id: str async def call_model( state: MessagesState, runtime: Runtime[Context], ): user_id = runtime.context.user_id namespace = ("memories", user_id) memories = await runtime.store.asearch(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" await runtime.store.aput(namespace, str(uuid4()), {"data": memory}) response = await model.ainvoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"] index_config = create_vector_index_config(embed=embed, dims=2, fields=["data"]) with ( MongoDBStore.from_conn_string( MONGODB_ATLAS_URI, index_config=index_config, auto_index_timeout=120, ) as store, MongoDBSaver.from_conn_string(MONGODB_ATLAS_URI) as checkpointer, ): builder = StateGraph(MessagesState, context_schema=Context) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) import asyncio async def run(): config = {"configurable": {"thread_id": "1"}} stream = await graph.astream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", context=Context(user_id="1"), ) async for snapshot in stream.values: snapshot["messages"][-1].pretty_print() config = {"configurable": {"thread_id": "2"}} stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", context=Context(user_id="1"), ) async for snapshot in stream.values: snapshot["messages"][-1].pretty_print() asyncio.run(run()) ``` ``` import os from collections.abc import Sequence from dataclasses import dataclass from uuid import uuid4 from langchain.chat_models import init_chat_model from langgraph.checkpoint.mongodb import MongoDBSaver from langgraph.graph import StateGraph, MessagesState, START from langgraph.runtime import Runtime from langgraph.store.mongodb import MongoDBStore, create_vector_index_config model = init_chat_model(model="claude-haiku-4-5-20251001") def embed(texts: Sequence[str]) -> list[list[float]]: # Replace with an embeddings model or LangChain Embeddings instance return [[1.0, 2.0] for _ in texts] @dataclass class Context: user_id: str def call_model( state: MessagesState, runtime: Runtime[Context], ): user_id = runtime.context.user_id namespace = ("memories", user_id) memories = runtime.store.search(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" runtime.store.put(namespace, str(uuid4()), {"data": memory}) response = model.invoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"] index_config = create_vector_index_config(embed=embed, dims=2, fields=["data"]) with ( MongoDBStore.from_conn_string( MONGODB_ATLAS_URI, index_config=index_config, auto_index_timeout=120, ) as store, MongoDBSaver.from_conn_string(MONGODB_ATLAS_URI) as checkpointer, ): builder = StateGraph(MessagesState, context_schema=Context) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) config = {"configurable": {"thread_id": "1"}} stream = graph.stream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", context=Context(user_id="1"), ) for snapshot in stream.values: snapshot["messages"][-1].pretty_print() config = {"configurable": {"thread_id": "2"}} stream = graph.stream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", context=Context(user_id="1"), ) for snapshot in stream.values: snapshot["messages"][-1].pretty_print() ``` 示例:使用 Redis 存储 ``` pip install -U langgraph langgraph-checkpoint-redis ``` 你需要打电话 `store.setup()` 第一次使用时 [Redis 仓库](<https://pypi.org/project/langgraph-checkpoint-redis/>). - 自动同步 - 同步( S) ``` from dataclasses import dataclass from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.redis.aio import AsyncRedisSaver from langgraph.store.redis.aio import AsyncRedisStore from langgraph.runtime import Runtime model = init_chat_model(model="claude-haiku-4-5-20251001") @dataclass class Context: user_id: str async def call_model( state: MessagesState, runtime: Runtime[Context], ): user_id = runtime.context.user_id namespace = ("memories", user_id) memories = await runtime.store.asearch(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" await runtime.store.aput(namespace, str(uuid7()), {"data": memory}) response = await model.ainvoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} DB_URI = "redis://localhost:6379" async with ( AsyncRedisStore.from_conn_string(DB_URI) as store, AsyncRedisSaver.from_conn_string(DB_URI) as checkpointer, ): # await store.setup() # await checkpointer.asetup() builder = StateGraph(MessagesState, context_schema=Context) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) config = {"configurable": {"thread_id": "1"}} stream = await graph.astream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", context=Context(user_id="1"), ) async for snapshot in stream.values: snapshot["messages"][-1].pretty_print() config = {"configurable": {"thread_id": "2"}} stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", context=Context(user_id="1"), ) async for snapshot in stream.values: snapshot["messages"][-1].pretty_print() ``` ``` from dataclasses import dataclass from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, MessagesState, START from langgraph.checkpoint.redis import RedisSaver from langgraph.store.redis import RedisStore from langgraph.runtime import Runtime model = init_chat_model(model="claude-haiku-4-5-20251001") @dataclass class Context: user_id: str def call_model( state: MessagesState, runtime: Runtime[Context], ): user_id = runtime.context.user_id namespace = ("memories", user_id) memories = runtime.store.search(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" runtime.store.put(namespace, str(uuid7()), {"data": memory}) response = model.invoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} DB_URI = "redis://localhost:6379" with ( RedisStore.from_conn_string(DB_URI) as store, RedisSaver.from_conn_string(DB_URI) as checkpointer, ): store.setup() checkpointer.setup() builder = StateGraph(MessagesState, context_schema=Context) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) config = {"configurable": {"thread_id": "1"}} stream = graph.stream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", context=Context(user_id="1"), ) for snapshot in stream.values: snapshot["messages"][-1].pretty_print() config = {"configurable": {"thread_id": "2"}} stream = graph.stream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", context=Context(user_id="1"), ) for snapshot in stream.values: snapshot["messages"][-1].pretty_print() ``` 示例:使用甲骨文存储 ``` pip install -U langgraph langgraph-oracledb langchain-openai ``` **设置** 用来使用 [甲骨文仓库](<https://pypi.org/project/langgraph-oracledb/>),您需要一个 Oracle AI 数据库实例——用于语义的矢量索引 `search` 要求 [Oracle AI 矢量搜索](<https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/>). 你需要打电话 `store.setup()` 财务报告和财务报告 `checkpointer.setup()` 这是你第一次使用甲骨文商店和检查站。 - 同步( S) - 自动同步 ``` from langchain.chat_models import init_chat_model from langchain.embeddings import init_embeddings from langchain_core.runnables import RunnableConfig from langgraph.graph import StateGraph, MessagesState, START from langgraph.store.base import BaseStore from langgraph_oracledb.checkpoint.oracle import OracleSaver from langgraph_oracledb.store.oracle import OracleStore model = init_chat_model(model="claude-haiku-4-5-20251001") embeddings = init_embeddings("openai:text-embedding-3-small") DB_URI = "user/password@localhost:1521/FREEPDB1" with ( OracleStore.from_conn_string( DB_URI, index={"embed": embeddings, "dims": 1536}, ) as store, OracleSaver.from_conn_string(DB_URI) as checkpointer, ): store.setup() checkpointer.setup() def call_model( state: MessagesState, config: RunnableConfig, *, store: BaseStore, ): user_id = config["configurable"]["user_id"] namespace = ("memories", user_id) memories = store.search(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" store.put(namespace, str(uuid7()), {"data": memory}) response = model.invoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) config = { "configurable": { "thread_id": "1", "user_id": "1", } } stream = graph.stream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", ) for snapshot in stream.values: snapshot["messages"][-1].pretty_print() config = { "configurable": { "thread_id": "2", "user_id": "1", } } stream = graph.stream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", ) for snapshot in stream.values: snapshot["messages"][-1].pretty_print() ``` ``` from langchain.chat_models import init_chat_model from langchain.embeddings import init_embeddings from langchain_core.runnables import RunnableConfig from langgraph.graph import StateGraph, MessagesState, START from langgraph.store.base import BaseStore from langgraph_oracledb.checkpoint.oracle import AsyncOracleSaver from langgraph_oracledb.store.oracle import AsyncOracleStore model = init_chat_model(model="claude-haiku-4-5-20251001") embeddings = init_embeddings("openai:text-embedding-3-small") DB_URI = "user/password@localhost:1521/FREEPDB1" async with ( AsyncOracleStore.from_conn_string( DB_URI, index={"embed": embeddings, "dims": 1536}, ) as store, AsyncOracleSaver.from_conn_string(DB_URI) as checkpointer, ): await store.setup() await checkpointer.setup() async def call_model( state: MessagesState, config: RunnableConfig, *, store: BaseStore, ): user_id = config["configurable"]["user_id"] namespace = ("memories", user_id) memories = await store.asearch(namespace, query=str(state["messages"][-1].content)) info = "\n".join([d.value["data"] for d in memories]) system_msg = f"You are a helpful assistant talking to the user. User info: {info}" # Store new memories if the user asks the model to remember last_message = state["messages"][-1] if "remember" in last_message.content.lower(): memory = "User name is Bob" await store.aput(namespace, str(uuid7()), {"data": memory}) response = await model.ainvoke( [{"role": "system", "content": system_msg}] + state["messages"] ) return {"messages": response} builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile( checkpointer=checkpointer, store=store, ) config = { "configurable": { "thread_id": "1", "user_id": "1", } } stream = await graph.astream_events( {"messages": [{"role": "user", "content": "Hi! Remember: my name is Bob"}]}, config, version="v3", ) async for snapshot in stream.values: snapshot["messages"][-1].pretty_print() config = { "configurable": { "thread_id": "2", "user_id": "1", } } stream = await graph.astream_events( {"messages": [{"role": "user", "content": "what is my name?"}]}, config, version="v3", ) async for snapshot in stream.values: snapshot["messages"][-1].pretty_print() ``` ### 使用语义搜索 启用您图形存储器中的语义搜索, 以便让图形代理以语义相似的方式搜索存储器中的项目 。 ``` from langchain.embeddings import init_embeddings from langgraph.store.memory import InMemoryStore # Create store with semantic search enabled embeddings = init_embeddings("openai:text-embedding-3-small") store = InMemoryStore( index={ "embed": embeddings, "dims": 1536, } ) store.put(("user_123", "memories"), "1", {"text": "I love pizza"}) store.put(("user_123", "memories"), "2", {"text": "I am a plumber"}) items = store.search( ("user_123", "memories"), query="I'm hungry", limit=1 ) ``` 用语义搜索的长期内存 ``` from langchain.embeddings import init_embeddings from langchain.chat_models import init_chat_model from langgraph.store.memory import InMemoryStore from langgraph.graph import START, MessagesState, StateGraph from langgraph.runtime import Runtime model = init_chat_model("gpt-5.4-mini") # Create store with semantic search enabled embeddings = init_embeddings("openai:text-embedding-3-small") store = InMemoryStore( index={ "embed": embeddings, "dims": 1536, } ) store.put(("user_123", "memories"), "1", {"text": "I love pizza"}) store.put(("user_123", "memories"), "2", {"text": "I am a plumber"}) async def chat(state: MessagesState, runtime: Runtime): # Search based on user's last message items = await runtime.store.asearch( ("user_123", "memories"), query=state["messages"][-1].content ) memories = "\n".join( item.value["text"] for item in items if item.score is not None and item.score > 0.2 ) memories = f"## Memories of user\n{memories}" if memories else "" response = await model.ainvoke( [ {"role": "system", "content": f"You are a helpful assistant.\n{memories}"}, *state["messages"], ] ) return {"messages": [response]} builder = StateGraph(MessagesState) builder.add_node(chat) builder.add_edge(START, "chat") graph = builder.compile(store=store) stream = await graph.astream_events( {"messages": [{"role": "user", "content": "I'm hungry"}]}, version="v3", ) async for message in stream.messages: async for token in message.text: print(token, end="", flush=True) ``` ## 管理短期内存 与 [短期内存](<https://docs.langchain.com/oss/python/langgraph/add-memory#add-short-term-memory>) 启用时, 检查器会在同一线条内连续显示一个图态。 调用状态数据包含在模型输入中的模型控件的节点。 坚持状态不会自动将其全部发送到模型中。 向模型传递一个长长的信息历史可以超过其上下文窗口。 常见的解决方案有 : - [调试信件](<https://docs.langchain.com/oss/python/langgraph/add-memory#trim-messages>): 删除第一个或最后一个 N 信件( 在拨打 LLM 之前) - [删除信件](<https://docs.langchain.com/oss/python/langgraph/add-memory#delete-messages>) 从 LangGraph 状态永久 - [简写信件](<https://docs.langchain.com/oss/python/langgraph/add-memory#summarize-messages>):总结历史上早期的信息,代之以摘要 - [管理检查站](<https://docs.langchain.com/oss/python/langgraph/add-memory#manage-checkpoints>) 保存和检索信件历史 - 自定义策略( 如信件过滤等) 这使得代理能够追踪对话,而不会超过LLM的上下文窗口. ### 调试信件 大部分 LLMS 都有一个最大支持的上下文窗口( 以符号表示) 。 决定何时切换信件的方法之一是在信件历史中计数符号, 并在接近限制时切换。 如果您正在使用 LangChain , 您可以使用修剪信件工具, 并指定要从列表中保存的符号数量, 以及代码数 。 `strategy` (例如,保留最后一个) `max_tokens`)用于处理边界。在下面的例子中,节点向模型传递一个修剪后的信件列表,而不将信件从状态中删除。要修剪信件历史,请使用 [`trim_messages`](<https://reference.langchain.com/python/langchain-core/messages/utils/trim_messages>) 函数 : ``` from langchain_core.messages.utils import ( trim_messages, count_tokens_approximately ) def call_model(state: MessagesState): messages = trim_messages( state["messages"], strategy="last", token_counter=count_tokens_approximately, max_tokens=128, start_on="human", end_on=("human", "tool"), ) response = model.invoke(messages) return {"messages": [response]} builder = StateGraph(MessagesState) builder.add_node(call_model) ... ``` 完整实例: 修剪信件 ``` from langchain_core.messages.utils import ( trim_messages, count_tokens_approximately ) from langchain.chat_models import init_chat_model from langgraph.graph import StateGraph, START, MessagesState model = init_chat_model("claude-sonnet-4-6") summarization_model = model.bind(max_tokens=128) def call_model(state: MessagesState): messages = trim_messages( state["messages"], strategy="last", token_counter=count_tokens_approximately, max_tokens=128, start_on="human", end_on=("human", "tool"), ) response = model.invoke(messages) return {"messages": [response]} checkpointer = InMemorySaver() builder = StateGraph(MessagesState) builder.add_node(call_model) builder.add_edge(START, "call_model") graph = builder.compile(checkpointer=checkpointer) config = {"configurable": {"thread_id": "1"}} graph.invoke({"messages": "hi, my name is bob"}, config) graph.invoke({"messages": "write a short poem about cats"}, config) graph.invoke({"messages": "now do the same but for dogs"}, config) final_response = graph.invoke({"messages": "what's my name?"}, config) final_response["messages"][-1].pretty_print() ``` ``` ================================== Ai Message ================================== Your name is Bob, as you mentioned when you first introduced yourself. ``` ### 删除信件 您可以从图表状态删除信件来管理信件历史。 如果您想要删除特定信件或清除整个信件历史, 这样做很有用。 要从图表状态中删除信件, 您可以使用 `RemoveMessage`用于 `RemoveMessage` 要工作,需要使用状态密钥 [`add_messages`](<https://reference.langchain.com/python/langgraph/graph/message/add_messages>) [减号](<https://docs.langchain.com/oss/python/langgraph/graph-api#reducers>),喜欢 [`MessagesState`](<https://docs.langchain.com/oss/python/langgraph/graph-api#messagesstate>)。删除特定信件时: ``` from langchain.messages import RemoveMessage def delete_messages(state): messages = state["messages"] if len(messages) > 2: # remove the earliest two messages return {"messages": [RemoveMessage(id=m.id) for m in messages[:2]]} ``` 要删除 **全部( E)** 信件 : ``` from langgraph.graph.message import REMOVE_ALL_MESSAGES def delete_messages(state): return {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]} ``` 删除信件时, **保证** 请检查您正在使用的 LLM 提供者的局限性。例如: - 一些提供者期望消息历史从一个开始 `user` 消息 - 多数供应商需要 `assistant` 带有工具调用的信息,然后相应 `tool` 成果信息。 完整实例: 删除信件 ``` from langchain.messages import RemoveMessage def delete_messages(state): messages = state["messages"] if len(messages) > 2: # remove the earliest two messages return {"messages": [RemoveMessage(id=m.id) for m in messages[:2]]} def call_model(state: MessagesState): response = model.invoke(state["messages"]) return {"messages": response} builder = StateGraph(MessagesState) builder.add_sequence([call_model, delete_messages]) builder.add_edge(START, "call_model") checkpointer = InMemorySaver() app = builder.compile(checkpointer=checkpointer) config = {"configurable": {"thread_id": "1"}} stream = app.stream_events( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, version="v3" ) for snapshot in stream.values: print([(message.type, message.content) for message in snapshot["messages"]]) stream = app.stream_events( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, version="v3" ) for snapshot in stream.values: print([(message.type, message.content) for message in snapshot["messages"]]) ``` ``` [('human', "hi! I'm bob")] [('human', "hi! I'm bob"), ('ai', 'Hi Bob! How are you doing today? Is there anything I can help you with?')] [('human', "hi! I'm bob"), ('ai', 'Hi Bob! How are you doing today? Is there anything I can help you with?'), ('human', "what's my name?")] [('human', "hi! I'm bob"), ('ai', 'Hi Bob! How are you doing today? Is there anything I can help you with?'), ('human', "what's my name?"), ('ai', 'Your name is Bob.')] [('human', "what's my name?"), ('ai', 'Your name is Bob.')] ``` ### 简写信件 如上所示,缩小或删除信件的问题在于您可能因为对信件队列的挤压而丢失信息。因此,一些应用程序受益于使用聊天模式对信件历史进行总结的更复杂的方法。 ![内容提要](<https://mintcdn.com/langchain-5e9cc07a/ybiAaBfoBvFquMDz/oss/images/summary.png?fit=max&auto=format&n=ybiAaBfoBvFquMDz&q=85&s=c8ed3facdccd4ef5c7e52902c72ba938>) 提示和调谐逻辑可以用来总结信件历史。例如,在 LangGraph 中,您可以扩展 [`MessagesState`](<https://docs.langchain.com/oss/python/langgraph/graph-api#working-with-messages-in-graph-state>) 列入a `summary` 键 : ``` from langgraph.graph import MessagesState class State(MessagesState): summary: str ``` 然后,您可以生成聊天历史摘要, 使用任何已有摘要作为下一份摘要的上下文 。 `summarize_conversation` 节点可以在您已累积到一些信件之后调用 。 `messages` 状态密钥。 ``` def summarize_conversation(state: State): # First, we get any existing summary summary = state.get("summary", "") # Create our summarization prompt if summary: # A summary already exists summary_message = ( f"This is a summary of the conversation to date: {summary}\n\n" "Extend the summary by taking into account the new messages above:" ) else: summary_message = "Create a summary of the conversation above:" # Add prompt to our history messages = state["messages"] + [HumanMessage(content=summary_message)] response = model.invoke(messages) # Delete all but the 2 most recent messages delete_messages = [RemoveMessage(id=m.id) for m in state["messages"][:-2]] return {"summary": response.content, "messages": delete_messages} ``` 完整实例: 摘要信件 ``` from typing import Any, TypedDict from langchain.chat_models import init_chat_model from langchain.messages import AnyMessage from langchain_core.messages.utils import count_tokens_approximately from langgraph.graph import StateGraph, START, MessagesState from langgraph.checkpoint.memory import InMemorySaver from langmem.short_term import SummarizationNode, RunningSummary model = init_chat_model("claude-sonnet-4-6") summarization_model = model.bind(max_tokens=128) class State(MessagesState): context: dict[str, RunningSummary] class LLMInputState(TypedDict): summarized_messages: list[AnyMessage] context: dict[str, RunningSummary] summarization_node = SummarizationNode( token_counter=count_tokens_approximately, model=summarization_model, max_tokens=256, max_tokens_before_summary=256, max_summary_tokens=128, ) def call_model(state: LLMInputState): response = model.invoke(state["summarized_messages"]) return {"messages": [response]} checkpointer = InMemorySaver() builder = StateGraph(State) builder.add_node(call_model) builder.add_node("summarize", summarization_node) builder.add_edge(START, "summarize") builder.add_edge("summarize", "call_model") graph = builder.compile(checkpointer=checkpointer) # Invoke the graph config = {"configurable": {"thread_id": "1"}} graph.invoke({"messages": "hi, my name is bob"}, config) graph.invoke({"messages": "write a short poem about cats"}, config) graph.invoke({"messages": "now do the same but for dogs"}, config) final_response = graph.invoke({"messages": "what's my name?"}, config) final_response["messages"][-1].pretty_print() print("\nSummary:", final_response["context"]["running_summary"].summary) ``` 1. 我们将追踪我们的运行摘要 `context` 字段 (预计 `SummarizationNode`). 1. 定义仅用于过滤的私密状态 输入到 `call_model` 节点。 1. 我们通过一个私人输入状态来隔离汇总节点返回的消息 ``` ================================== Ai Message ================================== From our conversation, I can see that you introduced yourself as Bob. That's the name you shared with me when we began talking. Summary: In this conversation, I was introduced to Bob, who then asked me to write a poem about cats. I composed a poem titled "The Mystery of Cats" that captured cats' graceful movements, independent nature, and their special relationship with humans. Bob then requested a similar poem about dogs, so I wrote "The Joy of Dogs," which highlighted dogs' loyalty, enthusiasm, and loving companionship. Both poems were written in a similar style but emphasized the distinct characteristics that make each pet special. ``` ### 管理检查站 您可以查看和删除检查器存储的信息。 #### 查看线索状态 - 图API - 检查器 API ``` config = { "configurable": { "thread_id": "1", # optionally provide an ID for a specific checkpoint, # otherwise the latest checkpoint is shown # "checkpoint_id": "1f029ca3-1f5b-6704-8004-820c16b69a5a" } } graph.get_state(config) ``` ``` StateSnapshot( values={'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today?), HumanMessage(content="what's my name?"), AIMessage(content='Your name is Bob.')]}, next=(), config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1f5b-6704-8004-820c16b69a5a'}}, metadata={ 'source': 'loop', 'writes': {'call_model': {'messages': AIMessage(content='Your name is Bob.')}}, 'step': 4, 'parents': {}, 'thread_id': '1' }, created_at='2025-05-05T16:01:24.680462+00:00', parent_config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1790-6b0a-8003-baf965b6a38f'}}, tasks=(), interrupts=() ) ``` ``` config = { "configurable": { "thread_id": "1", # optionally provide an ID for a specific checkpoint, # otherwise the latest checkpoint is shown # "checkpoint_id": "1f029ca3-1f5b-6704-8004-820c16b69a5a" } } checkpointer.get_tuple(config) ``` ``` CheckpointTuple( config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1f5b-6704-8004-820c16b69a5a'}}, checkpoint={ 'v': 3, 'ts': '2025-05-05T16:01:24.680462+00:00', 'id': '1f029ca3-1f5b-6704-8004-820c16b69a5a', 'channel_versions': {'__start__': '00000000000000000000000000000005.0.5290678567601859', 'messages': '00000000000000000000000000000006.0.3205149138784782', 'branch:to:call_model': '00000000000000000000000000000006.0.14611156755133758'}, 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000004.0.5736472536395331'}, 'call_model': {'branch:to:call_model': '00000000000000000000000000000005.0.1410174088651449'}}, 'channel_values': {'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today?), HumanMessage(content="what's my name?"), AIMessage(content='Your name is Bob.')]}, }, metadata={ 'source': 'loop', 'writes': {'call_model': {'messages': AIMessage(content='Your name is Bob.')}}, 'step': 4, 'parents': {}, 'thread_id': '1' }, parent_config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1790-6b0a-8003-baf965b6a38f'}}, pending_writes=[] ) ``` #### 查看线程历史 - 图API - 检查器 API ``` config = { "configurable": { "thread_id": "1" } } list(graph.get_state_history(config)) ``` ``` [ StateSnapshot( values={'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?'), HumanMessage(content="what's my name?"), AIMessage(content='Your name is Bob.')]}, next=(), config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1f5b-6704-8004-820c16b69a5a'}}, metadata={'source': 'loop', 'writes': {'call_model': {'messages': AIMessage(content='Your name is Bob.')}}, 'step': 4, 'parents': {}, 'thread_id': '1'}, created_at='2025-05-05T16:01:24.680462+00:00', parent_config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1790-6b0a-8003-baf965b6a38f'}}, tasks=(), interrupts=() ), StateSnapshot( values={'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?'), HumanMessage(content="what's my name?")]}, next=('call_model',), config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1790-6b0a-8003-baf965b6a38f'}}, metadata={'source': 'loop', 'writes': None, 'step': 3, 'parents': {}, 'thread_id': '1'}, created_at='2025-05-05T16:01:23.863421+00:00', parent_config={...} tasks=(PregelTask(id='8ab4155e-6b15-b885-9ce5-bed69a2c305c', name='call_model', path=('__pregel_pull', 'call_model'), error=None, interrupts=(), state=None, result={'messages': AIMessage(content='Your name is Bob.')}),), interrupts=() ), StateSnapshot( values={'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?')]}, next=('__start__',), config={...}, metadata={'source': 'input', 'writes': {'__start__': {'messages': [{'role': 'user', 'content': "what's my name?"}]}}, 'step': 2, 'parents': {}, 'thread_id': '1'}, created_at='2025-05-05T16:01:23.863173+00:00', parent_config={...} tasks=(PregelTask(id='24ba39d6-6db1-4c9b-f4c5-682aeaf38dcd', name='__start__', path=('__pregel_pull', '__start__'), error=None, interrupts=(), state=None, result={'messages': [{'role': 'user', 'content': "what's my name?"}]}),), interrupts=() ), StateSnapshot( values={'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?')]}, next=(), config={...}, metadata={'source': 'loop', 'writes': {'call_model': {'messages': AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?')}}, 'step': 1, 'parents': {}, 'thread_id': '1'}, created_at='2025-05-05T16:01:23.862295+00:00', parent_config={...} tasks=(), interrupts=() ), StateSnapshot( values={'messages': [HumanMessage(content="hi! I'm bob")]}, next=('call_model',), config={...}, metadata={'source': 'loop', 'writes': None, 'step': 0, 'parents': {}, 'thread_id': '1'}, created_at='2025-05-05T16:01:22.278960+00:00', parent_config={...} tasks=(PregelTask(id='8cbd75e0-3720-b056-04f7-71ac805140a0', name='call_model', path=('__pregel_pull', 'call_model'), error=None, interrupts=(), state=None, result={'messages': AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?')}),), interrupts=() ), StateSnapshot( values={'messages': []}, next=('__start__',), config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-0870-6ce2-bfff-1f3f14c3e565'}}, metadata={'source': 'input', 'writes': {'__start__': {'messages': [{'role': 'user', 'content': "hi! I'm bob"}]}}, 'step': -1, 'parents': {}, 'thread_id': '1'}, created_at='2025-05-05T16:01:22.277497+00:00', parent_config=None, tasks=(PregelTask(id='d458367b-8265-812c-18e2-33001d199ce6', name='__start__', path=('__pregel_pull', '__start__'), error=None, interrupts=(), state=None, result={'messages': [{'role': 'user', 'content': "hi! I'm bob"}]}),), interrupts=() ) ] ``` ``` config = { "configurable": { "thread_id": "1" } } list(checkpointer.list(config)) ``` ``` [ CheckpointTuple( config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1f5b-6704-8004-820c16b69a5a'}}, checkpoint={ 'v': 3, 'ts': '2025-05-05T16:01:24.680462+00:00', 'id': '1f029ca3-1f5b-6704-8004-820c16b69a5a', 'channel_versions': {'__start__': '00000000000000000000000000000005.0.5290678567601859', 'messages': '00000000000000000000000000000006.0.3205149138784782', 'branch:to:call_model': '00000000000000000000000000000006.0.14611156755133758'}, 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000004.0.5736472536395331'}, 'call_model': {'branch:to:call_model': '00000000000000000000000000000005.0.1410174088651449'}}, 'channel_values': {'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?'), HumanMessage(content="what's my name?"), AIMessage(content='Your name is Bob.')]}, }, metadata={'source': 'loop', 'writes': {'call_model': {'messages': AIMessage(content='Your name is Bob.')}}, 'step': 4, 'parents': {}, 'thread_id': '1'}, parent_config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1790-6b0a-8003-baf965b6a38f'}}, pending_writes=[] ), CheckpointTuple( config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-1790-6b0a-8003-baf965b6a38f'}}, checkpoint={ 'v': 3, 'ts': '2025-05-05T16:01:23.863421+00:00', 'id': '1f029ca3-1790-6b0a-8003-baf965b6a38f', 'channel_versions': {'__start__': '00000000000000000000000000000005.0.5290678567601859', 'messages': '00000000000000000000000000000006.0.3205149138784782', 'branch:to:call_model': '00000000000000000000000000000006.0.14611156755133758'}, 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000004.0.5736472536395331'}, 'call_model': {'branch:to:call_model': '00000000000000000000000000000005.0.1410174088651449'}}, 'channel_values': {'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?'), HumanMessage(content="what's my name?")], 'branch:to:call_model': None} }, metadata={'source': 'loop', 'writes': None, 'step': 3, 'parents': {}, 'thread_id': '1'}, parent_config={...}, pending_writes=[('8ab4155e-6b15-b885-9ce5-bed69a2c305c', 'messages', AIMessage(content='Your name is Bob.'))] ), CheckpointTuple( config={...}, checkpoint={ 'v': 3, 'ts': '2025-05-05T16:01:23.863173+00:00', 'id': '1f029ca3-1790-616e-8002-9e021694a0cd', 'channel_versions': {'__start__': '00000000000000000000000000000004.0.5736472536395331', 'messages': '00000000000000000000000000000003.0.7056767754077798', 'branch:to:call_model': '00000000000000000000000000000003.0.22059023329132854'}, 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0.7040775356287469'}, 'call_model': {'branch:to:call_model': '00000000000000000000000000000002.0.9300422176788571'}}, 'channel_values': {'__start__': {'messages': [{'role': 'user', 'content': "what's my name?"}]}, 'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?')]} }, metadata={'source': 'input', 'writes': {'__start__': {'messages': [{'role': 'user', 'content': "what's my name?"}]}}, 'step': 2, 'parents': {}, 'thread_id': '1'}, parent_config={...}, pending_writes=[('24ba39d6-6db1-4c9b-f4c5-682aeaf38dcd', 'messages', [{'role': 'user', 'content': "what's my name?"}]), ('24ba39d6-6db1-4c9b-f4c5-682aeaf38dcd', 'branch:to:call_model', None)] ), CheckpointTuple( config={...}, checkpoint={ 'v': 3, 'ts': '2025-05-05T16:01:23.862295+00:00', 'id': '1f029ca3-178d-6f54-8001-d7b180db0c89', 'channel_versions': {'__start__': '00000000000000000000000000000002.0.18673090920108737', 'messages': '00000000000000000000000000000003.0.7056767754077798', 'branch:to:call_model': '00000000000000000000000000000003.0.22059023329132854'}, 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0.7040775356287469'}, 'call_model': {'branch:to:call_model': '00000000000000000000000000000002.0.9300422176788571'}}, 'channel_values': {'messages': [HumanMessage(content="hi! I'm bob"), AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?')]} }, metadata={'source': 'loop', 'writes': {'call_model': {'messages': AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?')}}, 'step': 1, 'parents': {}, 'thread_id': '1'}, parent_config={...}, pending_writes=[] ), CheckpointTuple( config={...}, checkpoint={ 'v': 3, 'ts': '2025-05-05T16:01:22.278960+00:00', 'id': '1f029ca3-0874-6612-8000-339f2abc83b1', 'channel_versions': {'__start__': '00000000000000000000000000000002.0.18673090920108737', 'messages': '00000000000000000000000000000002.0.30296526818059655', 'branch:to:call_model': '00000000000000000000000000000002.0.9300422176788571'}, 'versions_seen': {'__input__': {}, '__start__': {'__start__': '00000000000000000000000000000001.0.7040775356287469'}}, 'channel_values': {'messages': [HumanMessage(content="hi! I'm bob")], 'branch:to:call_model': None} }, metadata={'source': 'loop', 'writes': None, 'step': 0, 'parents': {}, 'thread_id': '1'}, parent_config={...}, pending_writes=[('8cbd75e0-3720-b056-04f7-71ac805140a0', 'messages', AIMessage(content='Hi Bob! How are you doing today? Is there anything I can help you with?'))] ), CheckpointTuple( config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f029ca3-0870-6ce2-bfff-1f3f14c3e565'}}, checkpoint={ 'v': 3, 'ts': '2025-05-05T16:01:22.277497+00:00', 'id': '1f029ca3-0870-6ce2-bfff-1f3f14c3e565', 'channel_versions': {'__start__': '00000000000000000000000000000001.0.7040775356287469'}, 'versions_seen': {'__input__': {}}, 'channel_values': {'__start__': {'messages': [{'role': 'user', 'content': "hi! I'm bob"}]}} }, metadata={'source': 'input', 'writes': {'__start__': {'messages': [{'role': 'user', 'content': "hi! I'm bob"}]}}, 'step': -1, 'parents': {}, 'thread_id': '1'}, parent_config=None, pending_writes=[('d458367b-8265-812c-18e2-33001d199ce6', 'messages', [{'role': 'user', 'content': "hi! I'm bob"}]), ('d458367b-8265-812c-18e2-33001d199ce6', 'branch:to:call_model', None)] ) ] ``` #### 删除线索中的所有检查点 ``` thread_id = "1" checkpointer.delete_thread(thread_id) ``` ## 数据库管理 如果您正在使用任何基于数据库的持久性执行( 如 Postgres, Redis, 或 Oracle) 来存储短存储和/或长期存储, 您将需要运行迁移来建立所需的计划, 才能使用您的数据库。 根据常规, 大多数数据库特定的库定义一个 。 `setup()` 在运行所需迁移的检查器或存储实例上使用的方法。但是,您应当检查您是否具体实施了 [`BaseCheckpointSaver`](<https://reference.langchain.com/python/langgraph/checkpoints/#langgraph.checkpoint.base.BaseCheckpointSaver>) 或 时 间 [`BaseStore`](<https://reference.langchain.com/python/langchain-core/stores/BaseStore>) 以确认确切的方法名称和用途。我们建议将运行迁移作为专门的部署步骤,或者您可以确保它们作为服务器启动的一部分运行。 --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langgraph/add-memory.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?

查看原始来源