ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

长期记忆如何让AI真正“记住你”?

长期记忆如何让AI真正“记住你”? 一、什么是长期记忆长期记忆Long-term memory能够让智能体agent在不同对话、会话之间存储和调取信息长期记忆基于 LangGraph 的存储模块实现该模块将数据保存为 JSON 文档通过命名空间namespace和键key做数据组织。二、语法使用Tips不管是长期记忆还是短期记忆都有内存和持久化两种方式2.1 InMemoryStore 语法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[], storestore, )2.2 PostgreSQL语法# pip install -U langgraph-checkpoint-postgres psycopg[binary] 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:postgreslocalhost:5432/postgres?sslmodedisable with PostgresStore.from_conn_string(DB_URI) as store: store.setup() agent: Runnable create_agent( claude-sonnet-4-6, tools[], storestore, )三、存储方式LangGraph 将长期记忆以 JSON 文档的形式存储在存储层stores中•namespace key组合定位一条记忆namespace 做分组隔离key 在分组内唯一• 典型命名空间示例[memories, user_123]代表用户 123 的记忆文件夹3.1 InMemoryStore•不传 query只依靠filter做结构化精确匹配不进行向量相似度排序返回顺序由存储实现决定。•传入 query自然语言语义检索会基于向量相似度对结果排序。可以搭配filter先过滤再排序。def embed(texts: Sequence[str]) - list[list[float]]: # 假定返回一个向量 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(indexIndexConfig(embedembed, dims2)) 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, ], area: 北美, }, ) store.put( namespace, b-memory, { rules: [ 我喜欢国语, 我只会说一顶点点英文, ], area: 炎黄子孙, }, ) # 通过ID获取存储数据 item store.get(namespace, a-memory) rprint(item) # 在该命名空间内搜索记忆条目按内容等值条件过滤并以向量相似度排序返回结果 items store.search( namespace, filter{area: 炎黄子孙}, query国语 ) rprint(items)3.2 PostgreSQLDB_URI postgresql://postgres:postgreslocalhost:5432/postgres?sslmodedisable with PostgresStore.from_conn_string(DB_URI) as store: store.setup()其中setup() 函数会创建所需要的表store,store_migrations,vector_migrations•store存业务 / 记忆 KV 数据•store_migrations跟踪 store 表结构版本•vector_migrations跟踪向量索引 / 向量表的版本需要 pgvector3.2.1store【核心业务数据主表】作用保存普通键值数据非向量对应store.put()/store.get()读写的内容Agent 记忆、用户配置、会话元数据等。关键字段•prefix命名空间类似文件夹用来分组数据比如(users,123)•key记录的键•valueJSONB 存储的值•created_at/updated_at创建更新时间•expires_atTTL 过期时间可选自动清理简单理解LangGraph 内置 KV 存储Agent 的长期记忆就存在这张表里。3.2.2store_migrations【KV 表的迁移版本记录表框架内部】作用记录store表的 schema 迁移版本属于框架内部管理表业务代码不要手动读写。逻辑• 每次调用setup()会先读这张表判断当前数据库的表结构版本• 如果版本低自动执行对应的 ALTER/CREATE 迁移 SQL版本一致就跳过幂等重复调用 setup 不会重复建表• 保证不同版本 LangGraph 升级时自动更新store表结构不会破坏已有数据3.2.3vector_migrations【向量索引迁移版本记录表框架内部】作用管理向量索引的迁移版本依赖 pgvector 扩展。• 只有开启index_config启用向量检索才会用到这套逻辑• 记录向量相关表、索引hnsw/ivfflat 向量索引的迁移版本•setup()会检查这个表自动创建 / 升级向量表、向量索引四、在工具中读写Store4.1 在工具tools中读取长期记忆通过ToolRuntime获取store信息Tips从源码中可以看到ToolRuntime不仅可以获取store还能获取state和context上下文ToolRuntime定义如下案例代码dataclass class Context: user_id: str 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 # 根据用户id获取用户信息 user_info runtime.store.get((users,), runtime.context.user_id) return str(user_info.value) if user_info else Unknown user agent create_agent( model model, tools [get_user_info], store store, context_schema Context, ) result agent.invoke( {messages: [{role: user, content: 查看用户信息}]}, context Context(user_id user_123), ) for m in result[messages]: m.pretty_print()4.2 在工具tools中写长期记忆使用put保存信息tool def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) - str: 保存用户信息. assert runtime.store is not None runtime.store.put((users,), runtime.context.user_id, dict(user_info)) return 成功保存用户信息. with PostgresStore.from_conn_string(DB_URI) as store: store.setup() agent: Runnable create_agent( modelmodel, tools[save_user_info], storestore, context_schemaContext ) result agent.invoke( {messages: [{role: user, content: My name is John Smith}]}, contextContext(user_iduser_123), ) for m in result[messages]: m.pretty_print()4.3 从数据库中store表中可以看到存储的结果五、小总结•长短期区别短期记忆管“眼前这摊事”单线程长期记忆管“下次还认得你”跨线程。•存储核心基于 LangGraph Store 实现数据以JSON 文档形式保存通过namespace key定位。•两种姿势开发用InMemoryStore内存字典生产用PostgresStore需pgvector支持向量检索。•读写入口在工具内部通过ToolRuntime拿到store实例用get读取、put写入实现 Agent 的“经验沉淀”。没有长期记忆的 Agent 只是个金鱼脑有了 Store它才算真正有了“积累”。如果觉得有用别忘了点赞、在看、转发三连支持
返回列表