LangChain、LangGraph和DeepAgents如何使用Store实现长期记忆
Store 是 LangChain体系提供的**跨线程/会话**持久化键值存储工具,一个简单的 JSON 文档存储系统,支持分层命名空间,可选向量语义检索与 TTL 过期。它让 Agent 能在多次对话间共享数据,例如**用户偏好**、**长期记忆**或**缓存结果**。
Store 是 LangChain体系提供的跨线程/会话持久化键值存储工具,一个简单的 JSON 文档存储系统,支持分层命名空间,可选向量语义检索与 TTL 过期。它让 Agent 能在多次对话间共享数据,例如用户偏好、长期记忆或缓存结果。
单个对话线程的短期记忆(Checkpointer)会受到thread_id的隔离限制,但是Store可以突破它,生产环境Store底层依靠数据库持久化,配合Namespace就能实现Agent的长期记忆。
1. Store的集成
LangGraph通过 compile 方法将 store 对象传入。此时,LangGraph 会自动处理 Store 的生命周期。
from langgraph.store.memory import InMemoryStore from langgraph.graph import StateGraphstore = InMemoryStore() builder = StateGraph(...)graph = builder.compile(store=store)
在LangChain中, create_agent方法支持传入Store。
agent = create_agent( model="claude-sonnet-4-5-20250929", tools=[get_user_info], # Pass store to agent - enables agent to access store when running tools store=store, context_schema=Context)
在DeepAgents中,同样的直接可传入Store,概念上DeepAgents多了个Backend,这个以后我们再讨论。
def make_backend(runtime): return CompositeBackend( default=StateBackend(runtime), # Ephemeral storage routes={ "/memories/": StoreBackend(runtime) # Persistent storage } )agent = create_deep_agent( store=InMemoryStore(), backend=make_backend, checkpointer=checkpointer)
2. Store的基础读写
Store 提供了简洁但功能强大的操作接口,主要围绕 put、get 和 search 展开。存储涉及到IO,大家可能会担心性能问题,Store其实提供了一套异步API(aput, aget, asearch),这在高并发的 Agent 生产服务时至关重要。
| API 方法 | 描述 | 关键参数 |
|---|---|---|
| put | 存储或更新 JSON 文档 | namespace , key, value |
| get | 根据命名空间和键精确获取单条记录 | namespace , key |
| search | 搜索记录,支持语义检索和元数据过滤 | namespace , query, filter, limit |
store = InMemoryStore(index={"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 IDitem = store.get(namespace, "a-memory") # search for "memories" within this namespace, filtering on content equivalence, sorted by vector similarityitems = store.search( namespace, filter={"my-key": "my-value"}, query="language preferences")
我们可以通过Tool机制,让Agent使用Store,如果使用LangChain或DeepAgents,我们可以从runtime中获取create_agent和create_deep_agent传入的store对象。生产需要使用DB实现的Store,需要关注数据库连接池,避免消耗资源。
@tooldef get_user_info(runtime: ToolRuntime[Context]) -> str: """Look up user info.""" # Access the store - same as that provided to `create_agent` store = runtime.store user_id = runtime.context.user_id # Retrieve data from store - returns StoreValue object with value and metadata user_info = store.get(("users",), user_id) return str(user_info.value) if user_info else"Unknown user"# Tool that allows agent to update user information (useful for chat applications)@tooldef save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str: """Save user info.""" # Access the store - same as that provided to `create_agent` store = runtime.store user_id = runtime.context.user_id # Store data in the store (namespace, key, data) store.put(("users",), user_id, user_info) return"Successfully saved user info."
3. 如何用好Namespace
Namespace 是 Store 中组织数据的分层路径,以字符串元组表示,类似文件夹结构,用于隔离不同业务域、用户或环境的数据。
设计Store机制的时候,还是folder-like structure,但已经展现了langchain对“万物皆文件”理念的偏爱,和Manus中的“FileSystem as Memory”思路一致。等到了DeepAgents,又设计FileSystem的抽象工具——Backend,真正的为Agent提供了文件系统。这里先聚焦Namespace。
Namespace 通常以 元组(Tuple) 的形式表示,支持多级嵌套,实现层级化管理。开发者可以根据业务需求灵活组织记忆:
- 用户级隔离:最常见的模式,确保每个用户的偏好和事实仅在其对应的
user_id空间内可见。 - 组织级共享:可以将 Namespace 设置为
("memories", "{org_id}"),使同一组织内的所有 Agent 能够搜索和共享该组织的政策或规则。 - 按类别划分:可以在用户 ID 下进一步细分,如
("agent_smith", "memories", "{user_id}", "preferences"),专门用于存储特定类型的非结构化信息。
# 根级 store.put(("docs",), "report1", {"title": "年报"}) # 用户级 store.put(("docs", "user123"), "notes", {"content": "..."})) # 多级缓存 store.put(("cache", "embeddings", "v1"), "e1", {"vec": [...]})
Namespace除了灵活的组织分级,也提供了高级过滤和通配符,在应对复杂业务场景时非常方便。
# 前缀过滤 store.list_namespaces(prefix=("test",)) # 后缀过滤 store.list_namespaces(suffix=("public",)) # 组合 store.list_namespaces(prefix=("a",), suffix=("f",)) # 通配符 store.list_namespaces(prefix=("a", "*", "f"))
4.语义检索
Store语义检索依赖于底层实现,官方提供了SqliteStore和PostgresStore,SqliteStore内置向量支持,仅支持 cosine 距离。PostgresStore需要pgvector 扩展,默认 cosine。
Store 通过在创建时提供 index 配置启用向量语义检索,写入时指定要索引的字段。可选 fields 指定要嵌入的 JSON 路径,默认为 ["$"](整个文档)。
核心使用 search(namespace_prefix, query=…, filter=…, limit=…) 进行自然语言检索。
conn_string = "postgresql://user:pass@localhost:5432/dbname"with PostgresStore.from_conn_string( conn_string, index={"dims": 1536,"embed": init_embeddings("openai:text-embedding-3-small"),"fields": ["text"] # specify which fields to embed. Default is the whole serialized value }) as store: store.setup() # Do this once to run migrations# Store documents store.put(("docs",), "doc1", {"text": "Python tutorial"}) store.put(("docs",), "doc2", {"text": "TypeScript guide"}) store.put(("docs",), "doc2", {"text": "Other guide"}, index=False) # don't index# Search by similarity results = store.search(("docs",), query="programming guides", limit=2)
向量与原始 JSON 文档分开存储,不影响普通 get/put 操作。
5. Store小结
Store 是实现长期记忆(Long-term Memory)的关键,设计理念回归本质,采用简洁的文档存储模式,支持通过命名空间(Namespace)和键(Key)的层级结构来组织 JSON 格式的数据条目。不仅支持基础的存(put)、取(get)操作,更集成了强大的语义搜索(Semantic Search) 功能,使 Agent 能够根据“含义”而非仅仅是精确匹配来检索用户的历史偏好、事实知识或过往经验,能从反馈中学习并持续进化。
为了让 Agent 能够以更符合 AI 直觉的方式操作这些长期记忆,DeepAgents 进一步通过其 Backend 机制,将 Store 的底层存取逻辑抽象为了一套 AI 原生的文件系统操作接口,我们下次再详细讨论。
学AI大模型的正确顺序,千万不要搞错了
🤔2026年AI风口已来!各行各业的AI渗透肉眼可见,超多公司要么转型做AI相关产品,要么高薪挖AI技术人才,机遇直接摆在眼前!
有往AI方向发展,或者本身有后端编程基础的朋友,直接冲AI大模型应用开发转岗超合适!
就算暂时不打算转岗,了解大模型、RAG、Prompt、Agent这些热门概念,能上手做简单项目,也绝对是求职加分王🔋

📝给大家整理了超全最新的AI大模型应用开发学习清单和资料,手把手帮你快速入门!👇👇
学习路线:
✅大模型基础认知—大模型核心原理、发展历程、主流模型(GPT、文心一言等)特点解析
✅核心技术模块—RAG检索增强生成、Prompt工程实战、Agent智能体开发逻辑
✅开发基础能力—Python进阶、API接口调用、大模型开发框架(LangChain等)实操
✅应用场景开发—智能问答系统、企业知识库、AIGC内容生成工具、行业定制化大模型应用
✅项目落地流程—需求拆解、技术选型、模型调优、测试上线、运维迭代
✅面试求职冲刺—岗位JD解析、简历AI项目包装、高频面试题汇总、模拟面经
以上6大模块,看似清晰好上手,实则每个部分都有扎实的核心内容需要吃透!
我把大模型的学习全流程已经整理📚好了!抓住AI时代风口,轻松解锁职业新可能,希望大家都能把握机遇,实现薪资/职业跃迁~
这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】

更多推荐


所有评论(0)