长期记忆使您的智能体能够跨不同对话和会话存储并回忆信息。 与仅限于单个线程的短期记忆不同,长期记忆可跨线程持久保存,并可在任意时刻被回忆。 长期记忆构建于 LangGraph 存储之上,该存储将数据保存为按命名空间和键组织的 JSON 文档。Documentation Index
Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
Use this file to discover all available pages before exploring further.
使用方法
要为智能体添加长期记忆,请创建一个存储并将其传递给create_agent:
- InMemoryStore
- PostgreSQL
from langchain.agents import create_agent
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
# InMemoryStore 将数据存储到内存字典中。在生产环境中请使用基于数据库的存储。
store = InMemoryStore()
agent: Runnable = create_agent(
"claude-sonnet-4-6",
tools=[],
store=store,
)
pip install langgraph-checkpoint-postgres
from langchain.agents import create_agent
from langchain_core.runnables import Runnable
from langgraph.store.postgres import PostgresStore # type: ignore[import-not-found]
DB_URI = "postgresql://postgres:postgres@localhost:5442/postgres?sslmode=disable"
with PostgresStore.from_conn_string(DB_URI) as store:
store.setup()
agent: Runnable = create_agent(
"claude-sonnet-4-6",
tools=[],
store=store,
)
runtime.store 参数从存储中读取数据或向存储写入数据。具体示例请参阅在工具中读取长期记忆和从工具写入长期记忆。
若需深入了解记忆类型(语义记忆、情景记忆、程序性记忆)及记忆写入策略,请参阅记忆概念指南。
记忆存储
LangGraph 将长期记忆作为 JSON 文档存储在存储中。 每条记忆都组织在自定义的namespace(类似于文件夹)和唯一的 key(类似于文件名)之下。命名空间通常包含用户或组织 ID 或其他便于信息组织的标签。
这种结构支持记忆的层次化组织。跨命名空间的搜索则通过内容过滤器实现。
- InMemoryStore
- PostgreSQL
from collections.abc import Sequence
from langgraph.store.base import IndexConfig
from langgraph.store.memory import InMemoryStore
def embed(texts: Sequence[str]) -> list[list[float]]:
# Replace with an actual embedding function or LangChain embeddings object
return [[1.0, 2.0] for _ in texts]
# InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production use.
store = InMemoryStore(index=IndexConfig(embed=embed, dims=2))
user_id = "my-user"
application_context = "chitchat"
namespace = (user_id, application_context)
store.put(
namespace,
"a-memory",
{
"rules": [
"User likes short, direct language",
"User only speaks English & python",
],
"my-key": "my-value",
},
)
# get the "memory" by ID
item = store.get(namespace, "a-memory")
# search for "memories" within this namespace, filtering on content equivalence, sorted by vector similarity
items = store.search(
namespace, filter={"my-key": "my-value"}, query="language preferences"
)
from collections.abc import Sequence
from langgraph.store.base import IndexConfig
from langgraph.store.postgres import PostgresStore # type: ignore[import-not-found]
def embed(texts: Sequence[str]) -> list[list[float]]:
# 替换为实际的嵌入函数或 LangChain 嵌入对象
return [[1.0, 2.0] for _ in texts]
DB_URI = "postgresql://postgres:postgres@localhost:5442/postgres?sslmode=disable"
with PostgresStore.from_conn_string(
DB_URI,
index=IndexConfig(embed=embed, dims=2), # type: ignore[arg-type]
) as store:
store.setup()
user_id = "my-user"
application_context = "chitchat"
namespace = (user_id, application_context)
store.put(
namespace,
"a-memory",
{
"rules": [
"User likes short, direct language",
"User only speaks English & python",
],
"my-key": "my-value",
},
)
item = store.get(namespace, "a-memory")
items = store.search(
namespace, filter={"my-key": "my-value"}, query="language preferences"
)
在工具中读取长期记忆
- InMemoryStore
- PostgreSQL
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
@dataclass
class Context:
user_id: str
# InMemoryStore 将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
store = InMemoryStore()
# 使用 put 方法向存储写入示例数据
store.put(
(
"users",
), # 用于分组相关数据的命名空间(用户数据的 users 命名空间)
"user_123", # 命名空间内的键(以用户 ID 为键)
{
"name": "John Smith",
"language": "English",
}, # 要存储的给定用户的数据
)
@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
"""查找用户信息。"""
# 访问存储 - 与提供给 `create_agent` 的相同
assert runtime.store is not None
user_id = runtime.context.user_id
# 从存储检索数据 - 返回包含值和元数据的 StoreValue 对象
user_info = runtime.store.get(("users",), user_id)
return str(user_info.value) if user_info else "Unknown user"
agent: Runnable = create_agent(
model="claude-sonnet-4-6",
tools=[get_user_info],
# 将存储传递给代理 - 使代理在运行工具时能够访问存储
store=store,
context_schema=Context,
)
# 运行代理
agent.invoke(
{"messages": [{"role": "user", "content": "look up user information"}]},
context=Context(user_id="user_123"),
)
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.postgres import PostgresStore # type: ignore[import-not-found]
@dataclass
class Context:
user_id: str
DB_URI = "postgresql://postgres:postgres@localhost:5442/postgres?sslmode=disable"
with PostgresStore.from_conn_string(DB_URI) as store:
store.setup()
store.put(("users",), "user_123", {"name": "John Smith", "language": "English"})
@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
"""Look up user info."""
assert runtime.store is not None
user_info = runtime.store.get(("users",), runtime.context.user_id)
return str(user_info.value) if user_info else "Unknown user"
agent: Runnable = create_agent(
"claude-sonnet-4-6",
tools=[get_user_info],
store=store,
context_schema=Context,
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "look up user information"}]},
context=Context(user_id="user_123"),
)
从工具写入长期记忆
- InMemoryStore
- PostgreSQL
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict
# InMemoryStore 将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
store = InMemoryStore()
@dataclass
class Context:
user_id: str
# TypedDict 定义了 LLM 的用户信息结构
class UserInfo(TypedDict):
name: str
# 允许代理更新用户信息的工具(适用于聊天应用程序)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
"""保存用户信息。"""
# 访问存储 - 与提供给 `create_agent` 的相同
assert runtime.store is not None
store = runtime.store
user_id = runtime.context.user_id
# 在存储中存储数据(命名空间,键,数据)
store.put(("users",), user_id, dict(user_info))
return "Successfully saved user info."
agent: Runnable = create_agent(
model="claude-sonnet-4-6",
tools=[save_user_info],
store=store,
context_schema=Context,
)
# 运行代理
agent.invoke(
{"messages": [{"role": "user", "content": "My name is John Smith"}]},
# 通过上下文传递的 user_id 用于标识正在更新谁的信息
context=Context(user_id="user_123"),
)
# 您可以直接访问存储以获取值
item = store.get(("users",), "user_123")
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.postgres import PostgresStore # type: ignore[import-not-found]
from typing_extensions import TypedDict
@dataclass
class Context:
user_id: str
class UserInfo(TypedDict):
name: str
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
"""Save user info."""
assert runtime.store is not None
runtime.store.put(("users",), runtime.context.user_id, dict(user_info))
return "Successfully saved user info."
DB_URI = "postgresql://postgres:postgres@localhost:5442/postgres?sslmode=disable"
with PostgresStore.from_conn_string(DB_URI) as store:
store.setup()
agent: Runnable = create_agent(
"claude-sonnet-4-6",
tools=[save_user_info],
store=store,
context_schema=Context,
)
agent.invoke(
{"messages": [{"role": "user", "content": "My name is John Smith"}]},
context=Context(user_id="user_123"),
)
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

