掌握Agent记忆系统:让AI像人一样拥有短期、长期和知识图谱记忆(收藏版)

发布时间:2026/7/21 17:34:16
掌握Agent记忆系统:让AI像人一样拥有短期、长期和知识图谱记忆(收藏版) 本文详细解析了AI Agent的记忆系统设计分为短期记忆Context Window的优化使用、长期记忆向量数据库实现语义检索和知识图谱结构化知识存储。通过三层记忆的分层管理和协作使AI能够像人一样处理当前对话、历史事件和知识关联。文章还提供了实用的代码示例和避坑指南帮助开发者构建更智能的AI Agent。一句话定义Agent 记忆系统 让 AI 像人一样把「刚刚发生的」「学过的」「长期积累的」分层管理。类比人类的记忆分三层——工作记忆当前对话的上下文几分钟内、情节记忆某件具体的事比如「上周我们讨论过 XX 方案」、语义记忆知识图谱比如「TypeScript 的类型系统是这样的」。AI 的记忆系统设计和这个完全对应人类记忆Agent 对应实现方式工作记忆短期记忆Context Window消息列表情节记忆长期记忆向量数据库语义检索语义记忆知识图谱结构化知识存储图数据库第一层短期记忆——Context Window 的正确用法短期记忆就是 Context Window 里的消息列表但原样塞满不是最优解。大多数开发者的实现是直接追加// ❌ 原始实现无脑追加必然 OOM constmessages: Message[] []; asyncfunctionchat(userInput: string) { messages.push({ role: user, content: userInput }); const response await llm.invoke(messages); // 越来越长最终爆 context messages.push({ role: assistant, content: response.content }); return response.content; }问题很明显聊 20 轮之后Context Window 满了要么报错要么模型开始遗忘早期内容。正确做法滑动窗口 摘要压缩保留近期上下文的同时不丢失历史。import { ChatOpenAI } fromlangchain/openai; import { SystemMessage, HumanMessage, AIMessage } fromlangchain/core/messages; const llm newChatOpenAI({ model: gpt-4o-mini }); // 核心动态管理消息列表 asyncfunctionmanageHistory( history: Message[], maxTokens 4000 ): PromiseMessage[] { const currentTokens estimateTokens(history); if (currentTokens maxTokens) { return history; // 还没满原样返回 } // 保留最近 10 条5轮对话防止丢失即时上下文 const recent history.slice(-10); const older history.slice(0, -10); // 用模型压缩历史比规则截断效果好 30% const summary await llm.invoke([ newSystemMessage( 将以下对话历史压缩成 200 字以内的摘要保留关键决策、用户偏好和重要结论 ), newHumanMessage( older.map((m) ${m.role}: ${m.content}).join(/n) ), ]); // 摘要作为系统消息放最前面 return [ newSystemMessage(对话历史摘要${summary.content}), ...recent, ]; } // 粗估 token 数4个字符约等于1个token functionestimateTokens(messages: Message[]): number { return messages.reduce((sum, m) sum m.content.length / 4, 0); }核心短期记忆不是越长越好滑动窗口 摘要压缩是平衡成本和质量的正确姿势。第二层长期记忆——向量数据库实现语义检索长期记忆解决的问题是「我一个月前告诉过你的事你现在能不能想起来」实现原理很直接——把历史对话或重要信息向量化存储需要时按语义相似度检索。关键点在于存什么、什么时候存、存多少。import { OpenAIEmbeddings } fromlangchain/openai; import { MemoryVectorStore } fromlangchain/vectorstores/memory; import { Document } fromlangchain/core/documents; // 初始化向量存储生产环境用 Pinecone / Weaviate / Chroma const embeddings newOpenAIEmbeddings(); const vectorStore newMemoryVectorStore(embeddings); // ✅ 选择性存储只存有价值的信息 asyncfunctionsaveToLongTermMemory( content: string, metadata: { type: preference | fact | decision | task; importance: high | medium | low; userId: string; } ) { // 低重要度的内容不存节省存储和检索噪音 if (metadata.importance low) return; await vectorStore.addDocuments([ newDocument({ pageContent: content, metadata: { ...metadata, timestamp: Date.now(), // 重要存储时间戳旧的记忆权重要打折 }, }), ]); } // ✅ 检索时加时间衰减越近的记忆越相关 asyncfunctionrecallMemory(query: string, userId: string) { const results await vectorStore.similaritySearchWithScore( query, 5, // 取最相似的 5 条 { userId } // 只检索当前用户的记忆 ); // 时间衰减30天前的记忆相关性打 0.7 折 const now Date.now(); const decayedResults results.map(([doc, score]) { const ageInDays (now - doc.metadata.timestamp) / (1000 * 60 * 60 * 24); const decayFactor ageInDays 30 ? 0.7 : 1.0; return { doc, score: score * decayFactor }; }); // 只返回相关性 0.7 的结果避免噪音 return decayedResults .filter(({ score }) score 0.7) .map(({ doc }) doc.pageContent); } // 在 Agent 回答前先检索相关记忆注入 context asyncfunctionagentWithMemory(userInput: string, userId: string) { const memories awaitrecallMemory(userInput, userId); const systemPrompt memories.length 0 ? 你记得关于这个用户的以下信息/n${memories.join(/n)}/n/n基于这些记忆回答问题。 : 你是一个助手。; return llm.invoke([ newSystemMessage(systemPrompt), newHumanMessage(userInput), ]); }核心长期记忆不是把所有对话都存进去选择性存储 时间衰减才能保持信噪比。第三层知识图谱——结构化知识的极致形态知识图谱解决的是「关系」问题——不只是记住事实还要记住事实之间的关联。举个例子「用户喜欢 React」「用户在做 AI 项目」「React 有 AI SDK」——如果这三条是孤立存储的Agent 无法推导出「可以向用户推荐 Vercel AI SDK」。但如果存在图里路径推理就能做到。实际开发中大多数项目用不到完整的图数据库Neo4j更常见的方案是用结构化 JSON 语义向量的混合存储// 混合记忆结构结构化属性 语义描述 interfaceMemoryNode { id: string; type: person | project | preference | event; attributes: Recordstring, unknown; relations: Array{ type: string; // likes, works_on, knows_about targetId: string; }; embedding?: number[]; // 可选语义向量用于模糊检索 } classStructuredMemoryStore { private nodes newMapstring, MemoryNode(); // 存储或更新节点 upsert(node: MemoryNode) { const existing this.nodes.get(node.id); if (existing) { // 合并属性不覆盖防止丢失旧信息 this.nodes.set(node.id, { ...existing, attributes: { ...existing.attributes, ...node.attributes }, relations: [...newSet([...existing.relations, ...node.relations])], }); } else { this.nodes.set(node.id, node); } } // 图遍历找到所有2跳以内的相关节点 getRelated(nodeId: string, depth 2): MemoryNode[] { const visited newSetstring(); constresult: MemoryNode[] []; consttraverse (id: string, currentDepth: number) { if (currentDepth 0 || visited.has(id)) return; visited.add(id); const node this.nodes.get(id); if (!node) return; result.push(node); node.relations.forEach(({ targetId }) { traverse(targetId, currentDepth - 1); }); }; traverse(nodeId, depth); return result; } // 序列化为 LLM 可读的 context toContextString(nodeId: string): string { const related this.getRelated(nodeId); return related .map((n) [${n.type}] ${JSON.stringify(n.attributes)}) .join(/n); } } // 使用示例 const memStore newStructuredMemoryStore(); // 存入用户节点 memStore.upsert({ id: user_james, type: person, attributes: { name: James, role: frontend_developer }, relations: [ { type: works_on, targetId: project_ai_assistant }, { type: prefers, targetId: tech_react }, ], }); memStore.upsert({ id: tech_react, type: preference, attributes: { name: React, category: frontend_framework }, relations: [ { type: has_ecosystem, targetId: tech_vercel_ai_sdk }, ], }); // Agent 回答时注入用户的知识图谱上下文 const context memStore.toContextString(user_james); // 输出[person] {name:James,role:frontend_developer} // [preference] {name:React,category:frontend_framework} // ...核心知识图谱的价值在于「关系推理」混合结构化 JSON 向量是大多数项目的性价比最高方案。三层记忆的协作完整的记忆感知 Agent把三层记忆整合起来才是一个真正有记忆的 Agentimport { ChatOpenAI } fromlangchain/openai; import { SystemMessage, HumanMessage } fromlangchain/core/messages; classMemoryAwareAgent { private llm newChatOpenAI({ model: gpt-4o }); privateshortTermHistory: Message[] []; privatelongTermStore: LongTermMemoryStore; privateknowledgeGraph: StructuredMemoryStore; constructor(privateuserId: string) { this.longTermStore newLongTermMemoryStore(); this.knowledgeGraph newStructuredMemoryStore(); } asyncchat(userInput: string): Promisestring { // Step 1: 检索长期记忆并行执行不阻塞 const [longTermMemories, graphContext] awaitPromise.all([ this.longTermStore.recall(userInput, this.userId), Promise.resolve(this.knowledgeGraph.toContextString(this.userId)), ]); // Step 2: 构建系统 prompt注入记忆层 const systemPrompt this.buildSystemPrompt(longTermMemories, graphContext); // Step 3: 管理短期记忆滑动窗口 const managedHistory awaitmanageHistory(this.shortTermHistory); // Step 4: 调用模型 const messages [ newSystemMessage(systemPrompt), ...managedHistory, newHumanMessage(userInput), ]; const response await this.llm.invoke(messages); // Step 5: 更新短期记忆 this.shortTermHistory.push( { role: user, content: userInput }, { role: assistant, content: response.content as string } ); // Step 6: 异步决策是否存入长期记忆不影响响应速度 this.asyncSaveMemory(userInput, response.content as string); return response.content as string; } private buildSystemPrompt(memories: string[], graphCtx: string): string { const parts [你是一个有记忆的 AI 助手。]; if (graphCtx) { parts.push(/n关于用户你知道/n${graphCtx}); } if (memories.length 0) { parts.push(/n相关的历史记忆/n${memories.join(/n)}); } return parts.join(/n); } // 异步存储不阻塞当前响应 private async asyncSaveMemory(input: string, output: string) { // 让模型判断这轮对话是否值得记忆 const shouldSave await this.llm.invoke([ new SystemMessage( 判断以下对话是否包含值得长期记忆的信息用户偏好/重要决策/事实只回答 yes 或 no ), new HumanMessage(用户${input}/n助手${output}), ]); if ((shouldSave.content as string).toLowerCase().includes(yes)) { await this.longTermStore.save( 用户说${input}助手回答${output}, { type: conversation, importance: high, userId: this.userId } ); } } }核心三层记忆各司其职检索并行化存储异步化才能做到有记忆而不慢。常见坑坑1把所有对话都存进向量库// ❌ 每轮都存存了一堆没用的 async function onMessage(msg: Message) { await vectorStore.addDocuments([new Document({ pageContent: msg.content })]); }向量库里全是「好的」「明白了」「那接下来呢」这类废话检索出来全是噪音。// ✅ 让模型判断是否值得存 const worthSaving await llm.invoke([ new SystemMessage(这句话有没有值得记忆的关键信息yes/no), new HumanMessage(msg.content), ]); if (worthSaving.content yes) { await vectorStore.addDocuments([...]); }坑2检索不区分用户// ❌ 全局检索用户A的记忆跑到用户B那里 const results await vectorStore.similaritySearch(query, 5);生产环境里多用户共用一个向量库不加过滤条件会导致记忆错位。// ✅ 检索时带 userId 过滤 const results await vectorStore.similaritySearch(query, 5, { filter: { userId: currentUserId }, });坑3短期记忆直接截断丢失关键上下文// ❌ 超长就直接砍掉前面的 if (messages.length 20) { messages messages.slice(-20); // 可能把任务背景砍掉了 }用摘要压缩而不是硬截断// ✅ 超长时先摘要再拼接最近内容 const summary await summarizeOlderMessages(messages.slice(0, -20)); messages [new SystemMessage(历史摘要${summary}), ...messages.slice(-20)];坑4记忆注入太多反而稀释了 Prompt// ❌ 检索 Top 20 条全部塞进 prompt const memories await vectorStore.similaritySearch(query, 20); const systemPrompt 你知道${memories.join(/n)}; // 20条记忆 用户问题 对话历史 Context 直接爆炸// ✅ 控制注入数量只用相关性 0.8 的最多 5 条 const results await vectorStore.similaritySearchWithScore(query, 5); const relevant results .filter(([_, score]) score 0.8) .map(([doc]) doc.pageContent);坑5忘记给记忆加过期机制记忆不应该永久有效。用户一年前说「我不喜欢 Vue」不代表现在还这样。// ✅ 存储时加 TTL检索时跳过过期记忆 await vectorStore.addDocuments([ new Document({ pageContent: content, metadata: { timestamp: Date.now(), ttlDays: 90, // 90天后过期 }, }), ]); // 检索时过滤只取 90 天内的记忆 const cutoff Date.now() - 90 * 24 * 60 * 60 * 1000; const results await vectorStore.similaritySearch(query, 5, { filter: { timestamp: { $gt: cutoff } }, });选型参考需求推荐方案备注单用户简单 chatbotMemoryVectorStoreLangChain 内存版开发测试用不持久化多用户生产环境Chroma / Pinecone / WeaviateChroma 本地部署友好Pinecone 托管省心需要关系推理Neo4j 向量混合复杂度高一般 Agent 不需要企业内网知识库pgvectorPostgreSQL 插件已有 PG 的团队最低迁移成本发布前自查清单短期记忆有滑动窗口 摘要压缩不是无脑追加向量存储检索加了用户隔离过滤存储前有重要性判断不存废话相关性阈值 0.7注入数量 ≤ 5 条记忆有 TTL不永久有效长期记忆存储是异步的不阻塞当前响应总结这篇我们从底层拆解了 Agent 记忆系统的三层设计短期记忆Context Window 不是越满越好滑动窗口 摘要压缩是正确姿势长期记忆向量数据库实现语义检索关键是选择性存储 时间衰减知识图谱解决关系推理问题混合 JSON 向量是大多数项目的性价比最优解三层协作检索并行化、存储异步化做到有记忆而不慢常见坑存太多、不隔离用户、硬截断、注入太多、忘记过期——五个坑踩过才知道理解记忆系统的核心是记忆本质上是 context 管理的延伸每一层记忆都是在回答什么信息值得在什么时候出现在 prompt 里这个问题。如何学习大模型 AI 由于新岗位的生产效率要优于被取代岗位的生产效率所以实际上整个社会的生产效率是提升的。但是具体到个人只能说是“最先掌握AI的人将会比较晚掌握AI的人有竞争优势”。这句话放在计算机、互联网、移动互联网的开局时期都是一样的道理。我在一线科技企业深耕十二载见证过太多因技术卡位而跃迁的案例。那些率先拥抱 AI 的同事早已在效率与薪资上形成代际优势我意识到有很多经验和知识值得分享给大家也可以通过我们的能力和经验解答大家在大模型的学习中的很多困惑。我们整理出这套AI 大模型突围资料包✅ 从零到一的 AI 学习路径图✅ 大模型调优实战手册附医疗/金融等大厂真实案例✅ 百度/阿里专家闭门录播课✅ 大模型当下最新行业报告✅ 真实大厂面试真题✅ 2026 最新岗位需求图谱所有资料 ⚡️ 朋友们如果有需要《AI大模型入门进阶学习资源包》下方扫码获取~① 全套AI大模型应用开发视频教程包含提示工程、RAG、LangChain、Agent、模型微调与部署、DeepSeek等技术点② 大模型系统化学习路线作为学习AI大模型技术的新手方向至关重要。 正确的学习路线可以为你节省时间少走弯路方向不对努力白费。这里我给大家准备了一份最科学最系统的学习成长路线图和学习规划带你从零基础入门到精通③ 大模型学习书籍文档学习AI大模型离不开书籍文档我精选了一系列大模型技术的书籍和学习文档电子版它们由领域内的顶尖专家撰写内容全面、深入、详尽为你学习大模型提供坚实的理论基础。④ AI大模型最新行业报告2025最新行业报告针对不同行业的现状、趋势、问题、机会等进行系统地调研和评估以了解哪些行业更适合引入大模型的技术和应用以及在哪些方面可以发挥大模型的优势。⑤ 大模型项目实战配套源码学以致用在项目实战中检验和巩固你所学到的知识同时为你找工作就业和职业发展打下坚实的基础。⑥ 大模型大厂面试真题面试不仅是技术的较量更需要充分的准备。在你已经掌握了大模型技术之后就需要开始准备面试我精心整理了一份大模型面试题库涵盖当前面试中可能遇到的各种技术问题让你在面试中游刃有余。以上资料如何领取为什么大家都在学大模型最近科技巨头英特尔宣布裁员2万人传统岗位不断缩减但AI相关技术岗疯狂扩招有3-5年经验大厂薪资就能给到50K*20薪不出1年“有AI项目经验”将成为投递简历的门槛。风口之下与其像“温水煮青蛙”一样坐等被行业淘汰不如先人一步掌握AI大模型原理应用技术项目实操经验“顺风”翻盘这些资料真的有用吗这份资料由我和鲁为民博士(北京清华大学学士和美国加州理工学院博士)共同整理现任上海殷泊信息科技CEO其创立的MoPaaS云平台获Forrester全球’强劲表现者’认证服务航天科工、国家电网等1000企业以第一作者在IEEE Transactions发表论文50篇获NASA JPL火星探测系统强化学习专利等35项中美专利。本套AI大模型课程由清华大学-加州理工双料博士、吴文俊人工智能奖得主鲁为民教授领衔研发。资料内容涵盖了从入门到进阶的各类视频教程和实战项目无论你是小白还是有些技术基础的技术人员这份资料都绝对能帮助你提升薪资待遇转行大模型岗位。以上全套大模型资料如何领取