Community编程与开发github.com

记忆系统设计

此技能用于智能体系统中的持久化语义记忆:跨会话知识保留、实体追踪、时间有效性、图或向量检索、记忆巩固以及记忆基准选择。将文件支持的便签路由到文件系统上下文,将交接摘要路由到上下文压缩,将令牌效率策略路由到上下文优化。

记忆系统设计 是什么?

记忆系统设计技能为 AI 智能体提供了一套全面的指导,用于构建能够跨会话保留知识的持久化内存架构。它涵盖了从简单的基于文件的存储到复杂的时间知识图谱的多种框架,帮助开发者根据检索需求选择合适的方案。该技能详细介绍了 Mem0、Zep/Graphiti、Letta、Cognee 和 LangMem 等框架的优缺点,并提供了基准性能数据(如 DMR 准确率、LoCoMo 和 HotPotQA)以供比较。关键建议是“从简开始,按需增加复杂性”,并强调时间有效性追踪、混合检索策略和定期记忆巩固的重要性。该技能适用于 Cursor、Claude Code 和 Codex 等平台,指导开发者设计可扩展、高性能的记忆系统,同时避免常见陷阱(如上下文过载、过时信息中毒和过度设计)。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/memory-systems

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

记忆系统设计 是做什么的?

记忆提供了持久化层,使智能体能够跨会话保持连续性,并基于累积的知识进行推理。简单的智能体完全依赖上下文作为记忆,会话结束后所有状态都会丢失。复杂的智能体会实现分层记忆架构,以平衡即时上下文需求与长期知识保留。从向量存储到知识图谱,再到时间知识图谱的演进,代表着对结构化记忆的投入增加,以提升检索和推理能力。

何时激活

在以下情况激活此技能:

  • 构建必须跨会话持久化知识的智能体
  • 在记忆框架(Mem0、Zep/Graphiti、Letta、LangMem、Cognee)之间进行选择
  • 需要在跨对话中维护实体一致性
  • 实现基于累积知识的推理
  • 设计可投入生产环境的可扩展记忆架构
  • 根据基准(LoCoMo、LongMemEval、DMR)评估记忆系统
  • 构建具有自动实体/关系提取和自我改进记忆的动态记忆系统(Cognee)

不要将此技能用于由其他技能负责的相邻工作:

  • 基于文件的便签、运行日志和工具输出卸载:文件系统上下文。
  • 对话压缩或人类可读的交接摘要:上下文压缩。
  • 同一次轨迹内的掩码、前缀缓存、令牌预算或检索范围限制:上下文优化。
  • 基于 RDF 状态的正式信念/愿望/意图模型:BDI 心智状态。

核心概念

将记忆视为从易失的上下文窗口到持久化存储的频谱。默认使用能够满足检索需求的最简单层级,因为基准证据表明,对于某些记忆工作负载(claim-memory-locomo-filesystem-baseline),工具复杂性不如可靠检索重要。仅在检索质量下降或智能体需要多跳推理、关系遍历或时间旅行查询时,才增加结构(如图、时间有效性)。

详细主题

生产框架概览

根据智能体所需的主要检索模式选择框架。使用下表缩小候选范围,然后使用下面的基准数据进行验证。

框架架构最适合权衡
Mem0向量存储 + 图记忆,可插拔后端多租户系统,广泛集成多智能体场景下专业化程度较低
Zep/Graphiti时间知识图谱,双时间模型需要关系建模 + 时间推理的企业高级功能受云服务限制
Letta自编辑记忆,分层存储(上下文内/核心/归档)完整的智能体内省,有状态服务对简单用例过于复杂
Cognee多层语义图,通过可定制的 ECL 管道和任务实现自适应学习的演进式智能体记忆;多跳推理较重的摄取时处理
LangMem用于 LangGraph 工作流的记忆工具已使用 LangGraph 的团队与 LangGraph 紧密耦合
文件系统纯文本文件,带有命名约定简单智能体,原型开发无语义搜索,无关系处理

当智能体需要双时间建模(同时追踪事件发生时间和被摄取时间)时,选择 Zep/Graphiti,因为其三层知识图谱(事件、语义实体、社区子图)在时间查询方面表现出色。当优先考虑使用托管基础设施快速投入生产时,选择 Mem0。当智能体需要通过其智能体开发环境进行深度自省时,选择 Letta。当智能体必须构建密集的多层语义图时,选择 Cognee——它将文本块和实体类型作为节点,并带有详细的关系边,并且每个核心部分(摄取、实体提取、后处理、检索)都是可定制的。

基准性能比较

参考这些基准来设定预期,但应将其视为针对检索维度的特定信号,而非绝对排名。没有单一的基准是决定性的。

系统DMR 准确率LoCoMoHotPotQA(多跳)延迟
Cognee——公布的高分可变
Zep(时间知识图谱)公布的高分—各项指标中等报告低延迟
Letta(文件系统)—公布的文件系统基线——
Mem0—公布的专业工具基线一次比较中较低—
MemGPT公布的高分——可变
GraphRAG公布的中/高范围——可变
向量 RAG 基线公布的较低范围——快速

关键要点:根据检索形态而非品牌比较记忆系统。使用基准数字作为需要重新验证的证据,不可用于产品宣传;稳定的设计规则是:从浅层开始,衡量检索质量,仅当较简单的层失败时才添加语义或图结构。

记忆层(决策点)

选择满足持久化需求的最浅层记忆。每一个更深的层都会增加基础设施成本和运维复杂性,因此仅当较浅的层无法满足检索或耐用性需求时才升级。

层持久性实现使用时机
工作层仅限上下文窗口系统提示中的便签始终使用——利用注意力优先位置进行优化
短期层会话范围文件系统,内存缓存中间工具结果,对话状态
长期层跨会话键值存储 → 图数据库用户偏好,领域知识,实体注册表
实体层跨会话实体注册表 + 属性维护身份(“张三”=跨对话中的同一个人)
时间知识图谱层跨会话 + 历史带有有效时间间隔的图随时间变化的事实,时间旅行查询,防止上下文冲突

检索策略

根据查询形态匹配检索策略。语义搜索擅长直接事实查询,但在多跳推理上会退化;基于实体的遍历擅长“关于 X 的所有信息”查询,但需要图结构;时间过滤擅长处理变化的事实,但需要有效性元数据。当准确性至关重要且基础设施预算允许时,可将多种策略组合为混合检索。

策略使用时机局限性
语义(嵌入相似度)直接事实查询多跳推理时退化
基于实体(图遍历)“告诉我关于 X 的一切”需要图结构
时间(有效性过滤)事实随时间变化需要有效性元数据
混合(语义 + 关键词 + 图)总体最佳准确性基础设施要求最高

混合方法通过仅检索相关的子图或记忆来减少活动上下文。Cognee 通过跨图、向量和关系存储的多种搜索模式实现混合检索,让智能体选择适合查询类型的检索策略,而非一刀切的方法。

记忆巩固

定期执行巩固以防止记忆无限制增长,因为不受控制的记忆累积会随时间降低检索质量。使其失效但不要丢弃——保留历史对于需要重建过去状态的时间查询至关重要。在达到记忆计数阈值、检索质量下降或按计划时间间隔触发巩固。有关可运行的巩固代码,请参见实现参考。

实践指导

选择记忆架构

从最简单的可行层开始,仅在检索质量下降时增加复杂性。 大多数智能体在第一天并不需要时间知识图谱。请遵循此升级路径:

  1. 原型阶段:使用文件系统记忆。将事实存储为带有时间戳的结构化 JSON。这可以在投入基础设施之前验证智能体行为。
  2. 扩展阶段:当智能体需要语义搜索和多租户隔离时,迁移到 Mem0 或带有元数据的向量存储,因为基于文件的查找无法处理相似度查询。
  3. 复杂推理:当智能体需要关系遍历、时间有效性或跨会话综合时,添加 Zep/Graphiti。Graphiti 使用带有通用关系的结构化连接,保持图简单且易于推理;Cognee 构建更密集的多层语义图,带有详细的关系边——根据智能体是需要时间双模建模(Graphiti)还是更丰富的互联知识结构(Cognee)来选择。
  4. 完全控制:当智能体必须通过深度内省自我管理记忆时,使用 Letta 或 Cognee,因为这些框架将记忆操作暴露为一等智能体操作。

与上下文集成

按需加载记忆,而不是预先加载所有内容,因为大的上下文负载成本高昂且会降低注意力质量。将检索到的记忆放在注意力优先的位置(上下文的开头或结尾),以最大化其对生成的影响。

错误恢复

优雅地处理检索失败,因为记忆系统本质上是嘈杂的。按顺序应用以下恢复策略:

  • 空检索:回退到更广泛的搜索(移除实体过滤器,扩大时间范围)。如果仍然为空,则提示用户澄清。
  • 过时结果:检查 valid_until 时间戳。如果大多数结果已过期,在重试之前触发巩固。
  • 冲突事实:优先选择 valid_from 最新的事实。如果置信度低,则将冲突呈现给用户。
  • 存储故障:将写入操作排队等待重试。永远不要因为记忆写入而阻塞智能体的响应。

示例

示例 1:Mem0 集成

from mem0 import Memory

m = Memory()
m.add("用户偏好深色模式和 Python 3.12", user_id="alice")
m.add("用户切换到了浅色模式", user_id="alice")

# 检索当前偏好(浅色模式),而非过时的
results = m.search("用户偏好什么主题?", user_id="alice")

示例 2:时间查询

# 使用有效时间周期追踪实体
graph.create_temporal_relationship(
    source_id=user_node,
    rel_type="LIVES_AT",
    target_id=address_node,
    valid_from=datetime(2024, 1, 15),
    valid_until=datetime(2024, 9, 1),  # 已搬离
)

# 查询:2024年3月1日用户住在哪里?
results = graph.query_at_time(
    {"type": "LIVES_AT", "source_label": "User"},
    query_time=datetime(2024, 3, 1)
)

示例 3:Cognee 记忆摄取与搜索

import cognee
from cognee.modules.search.types import SearchType

# 摄取并构建知识图谱
await cognee.add("./docs/")
await cognee.add("任何数据")
await cognee.cognify()

# 丰富记忆
await cognee.memify()

# 智能体检索关系感知的上下文
results = await cognee.search(
    query_text="对您记忆的任何查询",
    query_type=SearchType.GRAPH_COMPLETION,
)

指导原则

  1. 从文件系统记忆开始;仅在检索质量要求时才增加复杂性
  2. 为任何可能随时间变化的事实追踪时间有效性
  3. 使用混合检索(语义 + 关键词 + 图)以获得最佳准确性
  4. 定期巩固记忆——使其失效但不要丢弃
  5. 为检索失败做好设计:当记忆查找无结果时,始终有备用方案
  6. 考虑持久化记忆的隐私影响(保留策略、删除权)
  7. 在变更前后使用 LoCoMo 或 LongMemEval 对记忆系统进行基准测试
  8. 在生产环境中监控记忆增长和检索延迟

常见陷阱

  1. 将一切塞入上下文:将所有可用的记忆加载到提示中成本高昂且会降低注意力质量。应使用按需检索并辅以相关性过滤。
  2. 忽略时间有效性:事实会过时。没有有效性追踪,过时信息会污染上下文,导致智能体基于错误假设行动。
  3. 过早过度设计:简单的文件系统记忆在某些基准上可能胜过更专业的工具(claim-memory-locomo-filesystem-baseline)。仅在简单方法明显失败时才增加复杂性。
  4. 缺乏巩固策略:无限制的记忆增长会随时间降低检索质量。设置记忆计数阈值或计划间隔来触发巩固。
  5. 嵌入模型不匹配:使用一个嵌入模型写入记忆,再用另一个模型读取,由于向量空间不可互换,会导致检索效果差。为每个记忆存储固定使用一个嵌入模型,并在模型更改时重新嵌入所有条目。
  6. 图模式僵化:过度结构化的图模式(严格的节点类型、固定的关系标签)会在领域演变时失效。优先使用通用关系类型和灵活的属性包,以便新的实体类型不需要模式迁移。
  7. 过时记忆中毒:与当前状态相矛盾的老记忆会悄无声息地破坏智能体行为。实施过期策略或置信度衰减机制,使智能体降低老化事实的优先级,并在检测到矛盾时明确呈现。
  8. 记忆-上下文不匹配:检索到的记忆在主题上相关但在上下文中错误(例如,智能体讨论的是 Python 语言,但检索到关于“蟒蛇”的记忆)。通过在记忆条目中包含会话或领域元数据,并在检索时进行过滤来缓解。

集成

此技能负责持久化语义记忆。相邻技能负责临时存储、压缩和上下文策略:

  • 文件系统上下文:基于文件的便签、日志和简单运行。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

advanced-evaluation

This skill should be used for advanced LLM evaluation: LLM-as-judge systems, direct scoring, pairwise comparison, rubric calibration, evaluator bias mitigation, confidence scoring, and automated quality assessment.

bdi-mental-states

This skill should be used when modeling agent mental states with BDI concepts: beliefs, desires, intentions, RDF-to-belief transformations, rational agency traces, cognitive agents, BDI ontologies, and neuro-symbolic AI integration.

book-sft-pipeline

This skill should be used for book-to-SFT pipelines: ePub extraction, literary segmentation, author-voice dataset construction, style-transfer training, LoRA workflows, and model evaluation for voice replication.

compaction-control-profiling

This skill should be used when deciding, for a specific model and workload, whether the harness or the model should control compaction, and when qualifying or calibrating that choice with measurements: context-budget sweeps that compare harness-driven and model-driven compaction on one harness, the context-pressure regime where delegation pays, a per-model compaction behavior profile (interface uptake, compression factor per call, reopen rate of archived content, context fill at first compaction, response to pressure warnings), context anxiety and timing-instruction calibration, reversible collapse-and-archive interfaces, and re-qualification after a model or prompt change. Route the editable-file protocol, harness invariants, and edit-position cache cost of self-editing agents to self-managed-context, summary content to context-compression, harness thresholds and cache layout to context-optimization, and general evaluation design to evaluation.

comprehensive-research-agent

Ensure thorough validation, error recovery, and transparent reasoning in research tasks with multiple tool calls

context-compression

This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions.

context-degradation

This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.

context-fundamentals

This skill should be used to explain or reason about the foundational concepts of context engineering: what context is, the anatomy of a context window, how attention mechanics work, the U-shaped attention curve, why context quality matters more than quantity, and the mental models needed to interpret every other context-engineering decision. Use this for conceptual explanation, onboarding, and background reading. Route operational work to the specialized skills: debugging attention failures goes to context-degradation, token-efficiency work goes to context-optimization, conversation summarization goes to context-compression, and project-shape decisions go to project-development.

context-optimization

This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.

evaluation

This skill should be used when building agent evaluation systems: deterministic checks, regression suites, multi-dimensional rubrics, quality gates, production monitoring, baseline comparison, and outcome measurement for agent pipelines.

filesystem-context

This skill should be used when agent work needs file-backed context: durable scratchpads, tool-output offloading, just-in-time discovery, cross-agent handoff files, filesystem memory, or cleanup policies for context stored outside the prompt.

harness-engineering

This skill should be used when designing autonomous agent harnesses: research loops, evaluation scaffolds, locked and editable surfaces, durable logs, novelty gates, pruning, rollback, PR preparation, and human approval boundaries.

hosted-agents

This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes.

instruction-surface-security

Hardens agent runtimes against persistent prompt injection or unauthorized changes to instructions and permissions. Use to audit what agents auto-load, design reviewed activation for project rules, skills, memory, or tool configuration, and test whether trust boundaries hold after reload, restart, or delegation.

latent-briefing

This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

long-horizon-prompting

This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

multi-agent-patterns

This skill should be used when designing multi-agent systems that need context isolation, supervisor or swarm coordination, explicit handoffs, parallel execution, or a decision on whether multiple agents are justified.

project-development

This skill should be used for project-level decisions about LLM-powered systems: whether an LLM is the right primitive for the task at hand, the shape of a multi-stage batch or agent pipeline, token and cost estimation, choosing between single-agent and multi-agent at the project level, structured output design for downstream parsing, and structuring agent-assisted iteration. Use this when the unit of work is a whole project or a multi-stage pipeline. Route individual tool design to tool-design and individual skill-loading or context-budget tactics to context-optimization.

self-improvement-loops

This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

self-managed-context

This skill should be used when a model gets read-write control over its own live context window instead of a harness-scheduled compaction policy: the context exposed as an editable file the model rewrites with code tools, model-driven eviction and in-place updates, the harness invariants that keep self-editing safe (pinned prefix, edit gate, edit receipts, budget readouts, rollback on overflow), the prefix-cache cost of mid-context edits, and steering or training the model's own context-editing strategy. Route note content and fixed-threshold summarization to context-compression, cache-stable layout under harness control to context-optimization, file offloading to filesystem-context, and loop governance to self-improvement-loops.

相关技能