LangChain、LangGraph和DeepAgents如何使用Store实现长期记忆

张开发
2026/4/19 18:56:21 15 分钟阅读

分享文章

LangChain、LangGraph和DeepAgents如何使用Store实现长期记忆
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(storestore)在LangChain中create_agent方法支持传入Store。agent create_agent( modelclaude-sonnet-4-5-20250929, tools[get_user_info], # Pass store to agent - enables agent to access store when running tools storestore, context_schemaContext)在DeepAgents中同样的直接可传入Store概念上DeepAgents多了个Backend这个以后我们再讨论。def make_backend(runtime): return CompositeBackend( defaultStateBackend(runtime), # Ephemeral storage routes{ /memories/: StoreBackend(runtime) # Persistent storage } )agent create_deep_agent( storeInMemoryStore(), backendmake_backend, checkpointercheckpointer)2. Store的基础读写Store 提供了简洁但功能强大的操作接口主要围绕put、get和search展开。存储涉及到IO大家可能会担心性能问题Store其实提供了一套异步APIaput,aget,asearch这在高并发的 Agent生产服务时至关重要。API 方法描述关键参数put存储或更新 JSON 文档namespace,key,valueget根据命名空间和键精确获取单条记录namespace,keysearch搜索记录支持语义检索和元数据过滤namespace,query,filter,limitstore InMemoryStore(index{embed: embed, dims: 2}) user_id my-userapplication_context chitchatnamespace (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}, querylanguage 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 elseUnknown 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) returnSuccessfully saved user info.3. 如何用好NamespaceNamespace 是 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和PostgresStoreSqliteStore内置向量支持仅支持 cosine 距离。PostgresStore需要pgvector 扩展默认 cosine。Store 通过在创建时提供index配置启用向量语义检索写入时指定要索引的字段。可选fields指定要嵌入的 JSON 路径默认为[$]整个文档。核心使用search(namespace_prefix, query…, filter…, limit…)进行自然语言检索。conn_string postgresql://user:passlocalhost:5432/dbnamewith 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}, indexFalse) # dont index# Search by similarity results store.search((docs,), queryprogramming guides, limit2)向量与原始 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%免费】

更多文章