Community程式設計與開發github.com

memory-systems

為代理系統提供持久語義記憶:跨對話的知識留存、實體追蹤、時間有效性、圖形或向量檢索、記憶整合,以及記憶基準測試選擇。將檔案備份的暫存區路由至檔案系統上下文,將交接摘要路由至上下文壓縮,將令牌效率策略路由至上下文最佳化。

memory-systems 是什麼?

此技能專注於為 AI 代理設計和實現持久記憶系統,使其能夠跨對話維持連續性並基於累積的知識進行推理。它涵蓋了從簡單的檔案系統記憶到複雜的時序知識圖譜等多種架構,並提供了選擇適當記憶框架(如 Mem0、Zep/Graphiti、Letta、Cognee 和 LangMem)的實用指南。該技能詳細說明了何時激活不同記憶層(工作記憶、短期記憶、長期記憶、實體記憶和時序知識圖譜),並比較了語義檢索、基於實體的檢索、時序檢索和混合檢索等策略。它還引入了記憶整合的概念,以防止記憶無限增長,並提供了具體的程式碼範例(包括 Mem0、Zep/Graphiti 和 Cognee 的整合),展示了如何在實際代理工作流程中實現這些概念。對於需要跨會話保持狀態、追蹤隨時間變化的實體或處理複雜多跳查詢的代理系統,此技能至關重要。

相容平台~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)

請勿為其他技能負責的相鄰工作激活此技能:

  • 檔案備份的暫存區、運行日誌和工具輸出卸載:filesystem-context。
  • 對話壓縮或人類可讀的交接摘要:context-compression。
  • 單一軌跡內的遮罩、前綴快取、令牌預算或檢索範圍界定:context-optimization。
  • 基於 RDF 狀態的正式信念/願望/意圖模型:bdi-mental-states。

核心概念

將記憶想像成一個從易失的上下文視窗到持久儲存的頻譜。預設使用能滿足檢索需求的最簡單層次,因為基準測試證據表明,對於某些記憶工作負載(claim-memory-locomo-filesystem-baseline),工具複雜性的重要性低於可靠的檢索。僅在檢索品質下降或代理需要多跳推理、關係遍歷或時間旅行查詢時,才增加結構(圖、時序有效性)。

詳細主題

生產框架概覽

根據代理所需的主要檢索模式來選擇框架。使用下表來縮小候選範圍,然後使用下面的基準測試資料進行驗證。

框架架構最適合權衡
Mem0向量存儲 + 圖記憶,可插拔後端多租戶系統,廣泛集成對多代理場景專用性較低
Zep/Graphiti時序知識圖譜,雙時間模型需要關係建模 + 時序推理的企業進階功能鎖定於雲端
Letta具有分層存儲(上下文內/核心/存檔)的自編輯記憶完整的代理內省,有狀態服務對簡單用例來說過於複雜
Cognee透過可自訂 ECL 管線與可自訂 Task 實現的多層語義圖不斷演進和學習的代理記憶;多跳推理接收時處理負載較重
LangMem用於 LangGraph 工作流程的記憶工具已使用 LangGraph 的團隊與 LangGraph 緊密耦合
文件系統帶有命名約定的純文字檔案簡單代理,原型設計無語義搜索,無關係

當代理需要雙時間建模(追蹤事件發生的時間和它們被攝入的時間)時,選擇 Zep/Graphiti,因為其三層知識圖譜(事件、語義實體、社區子圖)在時序查詢方面表現出色。當優先考慮使用託管基礎設施快速上線時,選擇 Mem0。當代理需要透過其代理開發環境進行深度自我內省時,選擇 Letta。當代理必須建立密集的多層語義圖時,選擇 Cognee——它將文字塊和實體類型作為具有詳細關係邊的節點進行分層,並且每個核心部分(攝入、實體提取、後處理、檢索)都是可自訂的。

基準測試性能比較

參考這些基準測試來設定預期,但應將其視為針對檢索維度的特定來源信號,而非絕對排名。沒有任何單一基準測試是決定性的。

系統DMR 準確率LoCoMoHotPotQA (多跳)延遲
Cognee——公佈高分可變
Zep (時序 KG)公佈高分—跨指標中等報告低延遲
Letta (文件系統)—公佈文件系統基線——
Mem0—公佈專用工具基線在一次比較中較低—
MemGPT公佈高分——可變
GraphRAG公佈中/高分範圍——可變
向量 RAG 基線公佈較低範圍——快速

關鍵要點:根據檢索形狀而非品牌來比較記憶系統。使用基準測試數字作為有時間性的證據,在做出產品聲明之前必須重新核實;穩定的設計規則是從淺層開始,衡量檢索品質,然後僅在較簡單層次失敗時才添加語義或圖形結構。

記憶層次(決策點)

選擇能滿足持久性要求的最淺記憶層。每個較深的層次都會增加基礎設施成本和操作複雜性,因此僅在較淺層無法滿足檢索或持久性需求時才升級。

層次持久性實作使用時機
工作記憶僅上下文視窗系統提示中的暫存區始終如此——透過注意力偏好位置進行最佳化
短期記憶對話範圍文件系統,記憶體快取中間工具結果,對話狀態
長期記憶跨對話鍵值儲存 → 圖形資料庫用戶偏好,領域知識,實體註冊表
實體記憶跨對話實體註冊表 + 屬性維護身份(“張三”在不同對話中代表同一個人)
時序 KG跨對話 + 歷史帶有有效性區間的圖形隨時間變化的事實,時間旅行查詢,防止上下文衝突

檢索策略

根據查詢形狀匹配檢索策略。語義搜索擅長直接事實查找,但在多跳推理上表現不佳;基於實體的遍歷擅長處理“有關 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」時,檢索到關於蛇「Python」的記憶)。透過在記憶條目中包含對話或領域元資料,並在檢索時根據其進行過濾來緩解。

整合

此技能負責持久語義記憶。相鄰技能負責暫存儲存、壓縮和上下文策略:

  • filesystem-context:檔案備份的暫存區、日誌和簡單運行

…

[已截斷以進行翻譯]

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.

相關技能