{"title_zh":"让智能体记住该记的:面向 openKylin 的长期记忆设计与实践","body_zh":"# 让智能体记住该记的:面向 openKylin 的长期记忆设计与实践\n\n2026 年,大模型智能体正在从演示走向办公、研发和个人助理等长期使用场景。此时,决定体验的往往不再只是模型回答得是否聪明,而是它能否在几周甚至几个月后仍然记住用户真正有价值的偏好,同时忘掉临时信息、隐私内容和危险指令。\n\n这也是上海开源软件应用创新大赛 openKylin 专属赛题值得关注的地方:智能体记忆不是简单地把聊天记录塞进向量数据库,而是一套包含提取、分类、存储、检索、更新和遗忘的控制系统。\n\n## 长期记忆与会话上下文不是一回事\n\n会话上下文服务于当前任务。例如,用户刚刚说“把这份报告改成三段式”,相关内容通常只在本次任务中有效。长期记忆则保存跨会话仍然有用的信息,例如:\n\n- 用户偏好使用 Markdown 输出;\n- 用户习惯先看结论,再看详细解释;\n- 某个项目采用 Python 和 openKylin 环境;\n- 用户经常使用某个报告模板。\n\n如果把所有对话都长期保存,系统会遇到三个问题。第一,检索结果会被大量噪声淹没;第二,过时信息会持续影响回答;第三,隐私和安全边界难以控制。因此,记忆系统需要回答四个问题:这条信息是否值得长期保存?它属于什么类型?什么时候可以使用?何时必须删除或失效?\n\n## 记忆流水线需要明确的边界\n\n一个可落地的实现可以拆成以下步骤:\n\n1. 候选提取:从用户输入和任务结果中识别可能有长期价值的事实。\n2. 风险过滤:拒绝密码、令牌、身份证号等敏感数据,也拒绝把用户临时提出的危险指令写成偏好。\n3. 分类与打分:区分偏好、事实、工作流、模板和临时上下文,并为稳定性、置信度和时效性打分。\n4. 持久化:使用结构化字段保存来源、创建时间、更新时间和过期策略。\n5. 检索与重排:按照当前任务相关性、置信度和新鲜度选择记忆,而不是无条件注入全部内容。\n6. 更新与遗忘:新的明确陈述应覆盖旧值;长期未使用或用户要求删除的记忆必须失效。\n\n这里的关键是“记忆是可治理的数据”,而不是模型的隐式人格。系统应该允许用户查看、修改和删除记忆,也应该保留最小必要的审计信息,便于定位错误行为。\n\n## 一个可以改造的最小实现\n\n下面的 Python 示例不依赖外部服务,演示如何在写入前做敏感信息过滤,并用简单规则判断一条内容是否适合进入长期记忆。生产环境可以将 MemoryStore 替换为 SQLite、PostgreSQL 或向量数据库,并把分类器替换为模型调用。\n\n运行前需要 Python 3.10 或更高版本。将代码保存为 memory_gate.py 后执行 python memory_gate.py。\n\npython\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime, timezone\nimport json\nimport re\n\nSENSITIVE = [\n re.compile(r"(?i)\\b(sk-[a-z0-9]{20,}|ghp_[a-z0-9]{20,})\\b"),\n re.compile(r"(?i)(password|passwd|token|secret)\\s*[:=]\\s*\\S+"),\n re.compile(r"\\b1[3-9]\\d{9}\\b"),\n]\n\n@dataclass\nclass Memory:\n text: str\n kind: str\n confidence: float\n created_at: str\n expires_at: str | None = None\n\ndef contains_sensitive(text: str) -> bool:\n return any(pattern.search(text) for pattern in SENSITIVE)\n\ndef should_persist(text: str, kind: str, confidence: float) -> bool:\n durable_kinds = {"preference", "workflow", "template", "fact"}\n return (\n kind in durable_kinds\n and confidence >= 0.80\n and len(text) <= 300\n and not contains_sensitive(text)\n )\n\ndef build_memory(text: str, kind: str, confidence: float) -> Memory | None:\n if not should_persist(text, kind, confidence):\n return None\n now = datetime.now(timezone.utc).isoformat()\n return Memory(text, kind, confidence, now)\n\nif __name__ == "__main__":\n candidates = [\n ("我习惯先看结论,再看详细分析。", "preference", 0.96),\n ("这次任务的临时文件放在 /tmp/report。", "context", 0.95),\n ("token=sk-123456789012345678901234", "fact", 0.99),\n ]\n saved = [\n asdict(memory)\n for text, kind, confidence in candidates\n if (memory := build_memory(text, kind, confidence))\n ]\n print(json.dumps(saved, ensure_ascii=False, indent=2))\n\n\n这个示例有意保持保守:只有被定义为稳定类型、置信度足够高且未命中敏感规则的内容才会保存。实际系统还应增加用户确认机制,例如对“我以后都使用某模板”这类明确表达直接建议保存,对模型推断出的弱事实则先询问用户。\n\n## openKylin 场景下值得重点验证什么\n\n赛题如果面向真实桌面或开发环境,记忆能力不能只用“回答是否连贯”评价。更有价值的指标包括:\n\n- 准确记忆率:系统是否保存了用户明确要求保留的信息。\n- 错误记忆率:系统是否把临时内容或模型猜测当成事实。\n- 敏感信息拦截率:密码、令牌和个人身份信息是否在持久化前被阻断。\n- 检索有效性:相关记忆是否在正确任务中被召回。\n- 遗忘成功率:用户删除后,主存储、缓存、索引和备份是否都不再返回该信息。\n- 延迟与资源占用:本地部署时,记忆处理是否影响交互速度和设备资源。\n\n本地运行还带来一个现实取舍:数据留在设备上有利于隐私和离线使用,但存储、索引、备份和升级都由应用负责。若使用远程模型或远程数据库,则必须明确传输范围、加密方式、租户隔离和日志保留周期。\n\n## 落地前的检查清单\n\n建议把以下规则写进架构和测试,而不是只写在产品说明中:\n\n- 为每条记忆记录来源、类型、置信度、时间和删除状态。\n- 将秘密扫描放在持久化之前,并对日志做同样的脱敏处理。\n- 对过期信息设置 TTL,对用户确认的稳定偏好设置可更新而非永久不可变。\n- 检索时限制注入数量和长度,防止旧记忆压过当前用户指令。\n- 明确当前任务指令优先级,长期记忆不能绕过权限和安全策略。\n- 提供可见的记忆管理入口,支持查看、编辑和一键删除。\n- 用包含冲突偏好、过期数据、敏感信息和恶意指令的测试集持续回归。\n\n智能体的长期记忆最终考验的是工程治理能力。一个真正可用的方案,不是让系统“记得越多越好”,而是让它在正确的时间记住正确的信息,并且能够解释、纠正和忘记。","title_en":"Building Governed Long-Term Memory for AI Agents on openKylin","body_en":"# Building Governed Long-Term Memory for AI Agents on openKylin\n\nIn 2026, AI agents are moving from demos into office work, software development, and personal assistance. Once an agent is used over weeks or months, answer quality depends on more than the underlying model. The agent must preserve durable preferences without carrying temporary context, sensitive data, or risky instructions into future tasks.\n\nThat is the central engineering challenge behind the openKylin-focused track of the Shanghai Open Source Software Application Innovation Competition. Agent memory is not simply a matter of putting chat logs into a vector database. It is a controlled pipeline for extracting, classifying, storing, retrieving, updating, and forgetting information.\n\n## Long-Term Memory Is Not Session Context\n\nSession context supports the current task. If a user says, “Rewrite this report into three sections,” that instruction may only matter for the current interaction. Long-term memory contains information that remains useful across sessions, such as a preferred output format, a recurring workflow, a project technology stack, or a frequently used template.\n\nPersisting every message creates three predictable problems: retrieval becomes noisy, stale facts keep influencing answers, and privacy boundaries become difficult to enforce. A memory system therefore needs explicit answers to four questions: Is this worth retaining? What kind of information is it? When may it be used? When should it expire or be deleted?\n\n## A Memory Pipeline With Explicit Boundaries\n\nA practical design can be divided into six stages:\n\n1. Candidate extraction identifies facts that may have value beyond the current task.\n2. Risk filtering blocks passwords, tokens, identity data, and dangerous instructions before persistence.\n3. Classification and scoring separates preferences, facts, workflows, templates, and temporary context, while assigning confidence and freshness signals.\n4. Persistence stores the content together with its source, timestamps, and expiration policy.\n5. Retrieval and reranking selects only memories relevant to the current task.\n6. Update and forgetting replaces outdated values and honors explicit deletion requests.\n\nThe important design decision is to treat memory as governed data, not as an invisible personality layer. Users should be able to inspect, edit, and delete stored memories. Minimal audit metadata should also be retained so incorrect behavior can be diagnosed.\n\n## A Small Implementation You Can Adapt\n\nThe following Python example uses no external service. It demonstrates a persistence gate that filters sensitive data and admits only high-confidence, durable memory types. In production, replace the in-memory flow with SQLite, PostgreSQL, or a vector store, and replace the rule-based classifier with an appropriate model workflow.\n\nSave it as memory_gate.py and run it with Python 3.10 or later: python memory_gate.py.\n\npython\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime, timezone\nimport json\nimport re\n\nSENSITIVE = [\n re.compile(r"(?i)\\b(sk-[a-z0-9]{20,}|ghp_[a-z0-9]{20,})\\b"),\n re.compile(r"(?i)(password|passwd|token|secret)\\s*[:=]\\s*\\S+"),\n re.compile(r"\\b1[3-9]\\d{9}\\b"),\n]\n\n@dataclass\nclass Memory:\n text: str\n kind: str\n confidence: float\n created_at: str\n expires_at: str | None = None\n\ndef contains_sensitive(text: str) -> bool:\n return any(pattern.search(text) for pattern in SENSITIVE)\n\ndef should_persist(text: str, kind: str, confidence: float) -> bool:\n return (\n kind in {"preference", "workflow", "template", "fact"}\n and confidence >= 0.80\n and len(text) <= 300\n and not contains_sensitive(text)\n )\n\ndef build_memory(text: str, kind: str, confidence: float) -> Memory | None:\n if not should_persist(text, kind, confidence):\n return None\n return Memory(\n text=text,\n kind=kind,\n confidence=confidence,\n created_at=datetime.now(timezone.utc).isoformat(),\n )\n\nif __name__ == "__main__":\n candidates = [\n ("I prefer conclusions before detailed analysis.", "preference", 0.96),\n ("The temporary file for this task is in /tmp/report.", "context", 0.95),\n ("token=sk-123456789012345678901234", "fact", 0.99),\n ]\n saved = [\n asdict(memory)\n for text, kind, confidence in candidates\n if (memory := build_memory(text, kind, confidence))\n ]\n print(json.dumps(saved, indent=2))\n\n\nThe conservative behavior is intentional. Only durable, high-confidence, non-sensitive candidates are saved. A production agent should add user confirmation: explicit statements such as “Use this template from now on” can be proposed for storage, while weak model inferences should be confirmed first.\n\n## What to Measure on openKylin\n\nFor a desktop or development environment, memory quality should not be reduced to conversational coherence. Useful metrics include:\n\n- Correct retention rate: whether explicitly requested memories are stored.\n- False memory rate: whether temporary context or guesses become persistent facts.\n- Sensitive-data blocking rate: whether credentials and identity data are stopped before persistence.\n- Retrieval usefulness: whether relevant memories are recalled for the right tasks.\n- Deletion success rate: whether deletion removes data from primary storage, caches, indexes, and backups.\n- Latency and resource usage: whether local processing affects responsiveness or device capacity.\n\nLocal deployment improves privacy and offline operation, but the application then owns storage, indexing, backups, and migrations. Remote models or databases require clear controls for data transfer, encryption, tenant isolation, and log retention.\n\n## A Practical Adoption Checklist\n\nTurn these rules into architecture constraints and regression tests:\n\n- Store the source, type, confidence, timestamps, and deletion state for every memory.\n- Scan for secrets before persistence, and apply the same redaction to logs.\n- Use TTLs for temporary facts and updateable records for confirmed preferences.\n- Limit the number and length of injected memories so stale context cannot overwhelm the current task.\n- Keep current task instructions, permissions, and safety policies above long-term memory.\n- Provide an interface for users to inspect, edit, and delete memories.\n- Test conflicts, expired facts, sensitive inputs, deletion requests, and malicious instructions continuously.\n\nLong-term agent memory is ultimately an engineering governance problem. A useful system does not remember everything. It remembers the right information at the right time, while remaining explainable, correctable, and capable of forgetting.","seo_description_en":"Practical openKylin guidance for building AI agent memory with retention rules, privacy filtering, retrieval controls, and deletion workflows."}
开放报名 | 上海开源软件应用创新大赛openKylin专属赛题
2026-08-25
27
预计阅读时间: 1 分钟
Disclaimer: This article is an AI-assisted summary. Read it together with the original source when precision matters. The summary may omit context, version differences, or edge cases and is not official documentation.
预计阅读时间:14 分钟