6# Memory System Design
7
8Memory provides the persistence layer that allows agents to maintain continuity across sessions and reason over accumulated knowledge. Simple agents rely entirely on context for memory, losing all state when sessions end. Sophisticated agents implement layered memory architectures that balance immediate context needs with long-term knowledge retention. The evolution from vector stores to knowledge graphs to temporal knowledge graphs represents increasing investment in structured memory for improved retrieval and reasoning.
9
10## When to Activate
11
12Activate this skill when:
13- Building agents that must persist knowledge across sessions
14- Choosing between memory frameworks (Mem0, Zep/Graphiti, Letta, LangMem, Cognee)
15- Needing to maintain entity consistency across conversations
16- Implementing reasoning over accumulated knowledge
17- Designing memory architectures that scale in production
18- Evaluating memory systems against benchmarks (LoCoMo, LongMemEval, DMR)
19- Building dynamic memory with automatic entity/relationship extraction and self-improving memory (Cognee)
20
21Do not activate this skill for adjacent work owned by other skills:
22- File-backed scratchpads, run logs, and tool-output offloading: filesystem-context.
23- Conversation compaction or human-readable handoff summaries: context-compression.
24- Masking, prefix caching, token budgets, or retrieval scoping inside one trajectory: context-optimization.
25- Formal belief/desire/intention models over RDF state: bdi-mental-states.
26
27## Core Concepts
28
29Think of memory as a spectrum from volatile context window to persistent storage. Default to the simplest layer that meets retrieval needs, because benchmark evidence suggests tool complexity matters less than reliable retrieval for some memory workloads (claim-memory-locomo-filesystem-baseline). Add structure (graphs, temporal validity) only when retrieval quality degrades or the agent needs multi-hop reasoning, relationship traversal, or time-travel queries.
30
31## Detailed Topics
32
33### Production Framework Landscape
34
35Select a framework based on the dominant retrieval pattern the agent requires. Use this table to narrow the shortlist, then validate with the benchmark data below.
36
37| Framework | Architecture | Best For | Trade-off |
38|-----------|-------------|----------|-----------|
39| **Mem0** | Vector store + graph memory, pluggable backends | Multi-tenant systems, broad integrations | Less specialized for multi-agent |
40| **Zep/Graphiti** | Temporal knowledge graph, bi-temporal model | Enterprise requiring relationship modeling + temporal reasoning | Advanced features cloud-locked |
41| **Letta** | Self-editing memory with tiered storage (in-context/core/archival) | Full agent introspection, stateful services | Complexity for simple use cases |
42| **Cognee** | Multi-layer semantic graph via customizable ECL pipeline with customizable Tasks | Evolving agent memory that adapts and learns; multi-hop reasoning | Heavier ingest-time processing |
43| **LangMem** | Memory tools for LangGraph workflows | Teams already on LangGraph | Tightly coupled to LangGraph |
44| **File-system** | Plain files with naming conventions | Simple agents, prototyping | No semantic search, no relationships |
45
46Choose Zep/Graphiti when the agent needs bi-temporal modeling (tracking both when events occurred and when they were ingested) because its three-tier knowledge graph (episode, semantic entity, community subgraphs) excels at temporal queries. Choose Mem0 when the priority is fast time-to-production with managed infrastructure. Choose Letta when the agent needs deep self-introspection through its Agent Development Environment. Choose Cognee when the agent must build dense multi-layer semantic graphs — it layers text chunks and entity types as nodes with detailed relationship edges, and every core piece (ingestion, entity extraction, post-processing, retrieval) is customizable.
47
48**Benchmark Performance Comparison**
49
50Consult these benchmarks to set expectations, but treat them as source-specific signals for retrieval dimensions rather than absolute rankings. No single benchmark is definitive.
51
52| System | DMR Accuracy | LoCoMo | HotPotQA (multi-hop) | Latency |
53|--------|-------------|--------|---------------------|---------|
54| Cognee | — | — | Published high score | Variable |
55| Zep (Temporal KG) | Published high score | — | Mid-range across metrics | Low-latency reported |
56| Letta (filesystem) | — | Published filesystem baseline | — | — |
57| Mem0 | — | Published specialized-tool baseline | Lower in one comparison | — |
58| MemGPT | Published high score | — | — | Variable |
59| GraphRAG | Published mid/high range | — | — | Variable |
60| Vector RAG baseline | Published lower range | — | — | Fast |
61
62Key takeaway: compare memory systems by retrieval shape, not brand. Use benchmark numbers as dated evidence that must be rechecked before making product claims; the stable design rule is to start shallow, measure retrieval quality, then add semantic or graph structure only when a simpler layer fails.
63
64### Memory Layers (Decision Points)
65
66Pick the shallowest memory layer that satisfies the persistence requirement. Each deeper layer adds infrastructure cost and operational complexity, so only escalate when the shallower layer cannot meet the retrieval or durability need.
67
68| Layer | Persistence | Implementation | When to Use |
69|-------|------------|----------------|-------------|
70| **Working** | Context window only | Scratchpad in system prompt | Always — optimize with attention-favored positions |
71| **Short-term** | Session-scoped | File-system, in-memory cache | Intermediate tool results, conversation state |
72| **Long-term** | Cross-session | Key-value store → graph DB | User preferences, domain knowledge, entity registries |
73| **Entity** | Cross-session | Entity registry + properties | Maintaining identity ("John Doe" = same person across conversations) |
74| **Temporal KG** | Cross-session + history | Graph with validity intervals | Facts that change over time, time-travel queries, preventing context clash |
75
76### Retrieval Strategies
77
78Match the retrieval strategy to the query shape. Semantic search handles direct factual lookups well but degrades on multi-hop reasoning; entity-based traversal handles "everything about X" queries but requires graph structure; temporal filtering handles changing facts but requires validity metadata. When accuracy is paramount and infrastructure budget allows, combine strategies into hybrid retrieval.
79
80| Strategy | Use When | Limitation |
81|----------|----------|------------|
82| **Semantic** (embedding similarity) | Direct factual queries | Degrades on multi-hop reasoning |
83| **Entity-based** (graph traversal) | "Tell me everything about X" | Requires graph structure |
84| **Temporal** (validity filter) | Facts change over time | Requires validity metadata |
85| **Hybrid** (semantic + keyword + graph) | Best overall accuracy | Most infrastructure |
86
87Hybrid approaches reduce active context by retrieving only relevant subgraphs or memories. Cognee implements hybrid retrieval through multiple search modes across graph, vector, and relational stores, letting agents select the retrieval strategy that fits the query type rather than using a one-size-fits-all approach.
88
89### Memory Consolidation
90
91Run consolidation periodically to prevent unbounded growth, because unchecked memory accumulation degrades retrieval quality over time. **Invalidate but do not discard** — preserving history matters for temporal queries that need to reconstruct past states. Trigger consolidation on memory count thresholds, degraded retrieval quality, or scheduled intervals. See [Implementation Reference](./references/implementation.md) for working consolidation code.
92
93## Practical Guidance
94
95### Choosing a Memory Architecture
96
97**Start with the simplest viable layer and add complexity only when retrieval quality degrades.** Most agents do not need a temporal knowledge graph on day one. Follow this escalation path:
98
991. **Prototype**: Use file-system memory. Store facts as structured JSON with timestamps. This validates agent behavior before committing to infrastructure.
1002. **Scale**: Move to Mem0 or a vector store with metadata when the agent needs semantic search and multi-tenant isolation, because file-based lookup cannot handle similarity queries.
1013. **Complex reasoning**: Add Zep/Graphiti when the agent needs relationship traversal, temporal validity, or cross-session synthesis. Graphiti uses structured ties with generic relations, keeping graphs simple and easy to reason about; Cognee builds denser multi-layer semantic graphs with detailed relationship edges — choose based on whether the agent needs temporal bi-modeling (Graphiti) or richer interconnected knowledge structures (Cognee).
1024. **Full control**: Use Letta or Cognee when the agent must self-manage its own memory with deep introspection, because these frameworks expose memory operations as first-class agent actions.
103
104### Integration with Context
105
106Load memories just-in-time rather than preloading everything, because large context payloads are expensive and degrade attention quality. Place retrieved memories in attention-favored positions (beginning or end of context) to maximize their influence on generation.
107
108### Error Recovery
109
110Handle retrieval failures gracefully because memory systems are inherently noisy. Apply these recovery strategies in order:
111
112- **Empty retrieval**: Fall back to broader search (remove entity filter, widen time range). If still empty, prompt user for clarification.
113- **Stale results**: Check valid_until timestamps. If most results are expired, trigger consolidation before retrying.
114- **Conflicting facts**: Prefer the fact with the most recent valid_from. Surface the conflict to the user if confidence is low.
115- **Storage failure**: Queue writes for retry. Never block the agent's response on a memory write.
116
117## Examples
118
119**Example 1: Mem0 Integration**
120```python
121from mem0 import Memory
122
123m = Memory()
124m.add("User prefers dark mode and Python 3.12", user_id="alice")
125m.add("User switched to light mode", user_id="alice")
126
127# Retrieves current preference (light mode), not outdated one
128results = m.search("What theme does the user prefer?", user_id="alice")
129```
130
131**Example 2: Temporal Query**
132```python
133# Track entity with validity periods
134graph.create_temporal_relationship(
135 source_id=user_node,
136 rel_type="LIVES_AT",
137 target_id=address_node,
138 valid_from=datetime(2024, 1, 15),
139 valid_until=datetime(2024, 9, 1), # moved out
140)
141
142# Query: Where did user live on March 1, 2024?
143results = graph.query_at_time(
144 {"type": "LIVES_AT", "source_label": "User"},
145 query_time=datetime(2024, 3, 1)
146)
147```
148
149**Example 3: Cognee Memory Ingestion and Search**
150```python
151import cognee
152from cognee.modules.search.types import SearchType
153
154# Ingest and build knowledge graph
155await cognee.add("./docs/")
156await cognee.add("any data")
157await cognee.cognify()
158
159# Enrich memory
160await cognee.memify()
161
162# Agent retrieves relationship-aware context
163results = await cognee.search(
164 query_text="Any query for your memory",
165 query_type=SearchType.GRAPH_COMPLETION,
166)
167```
168
169## Guidelines
170
1711. Start with file-system memory; add complexity only when retrieval quality demands it
1722. Track temporal validity for any fact that can change over time
1733. Use hybrid retrieval (semantic + keyword + graph) for best accuracy
1744. Consolidate memories periodically — invalidate but don't discard
1755. Design for retrieval failure: always have a fallback when memory lookup returns nothing
1766. Consider privacy implications of persistent memory (retention policies, deletion rights)
1777. Benchmark your memory system against LoCoMo or LongMemEval before and after changes
1788. Monitor memory growth and retrieval latency in production
179
180## Gotchas
181
1821. **Stuffing everything into context**: Loading all available memories into the prompt is expensive and degrades attention quality. Use just-in-time retrieval with relevance filtering instead.
1832. **Ignoring temporal validity**: Facts go stale. Without validity tracking, outdated information poisons the context and the agent acts on wrong assumptions.
1843. **Over-engineering early**: Simple filesystem-backed memory can outperform more specialized tooling on some benchmarks (claim-memory-locomo-filesystem-baseline). Add sophistication only when simple approaches demonstrably fail.
1854. **No consolidation strategy**: Unbounded memory growth degrades retrieval quality over time. Set memory count thresholds or scheduled intervals to trigger consolidation.
1865. **Embedding model mismatch**: Writing memories with one embedding model and reading with another produces poor retrieval because vector spaces are not interchangeable. Pin a single embedding model for each memory store and re-embed all entries if the model changes.
1876. **Graph schema rigidity**: Over-structured graph schemas (rigid node types, fixed relationship labels) break when the domain evolves. Prefer generic relation types and flexible property bags so new entity kinds do not require schema migrations.
1887. **Stale memory poisoning**: Old memories that contradict the current state corrupt agent behavior silently. Implement expiry policies or confidence decay so the agent deprioritizes aged facts, and surface contradictions explicitly when detected.
1898. **Memory-context mismatch**: Retrieving memories that are topically related but contextually wrong (e.g., a memory about "Python" the snake when the agent is discussing Python the language). Mitigate by including session or domain metadata in memory entries and filtering on it during retrieval.
190
191## Integration
192
193This skill owns persistent semantic memory. Adjacent skills own scratch storage, compaction, and context tactics:
194
195- filesystem-context: file-backed scratchpads, logs, and simple run state before semantic retrieval is needed.
196- context-compression: summaries and handoffs that preserve session state in prose.
197- context-optimization: just-in-time memory loading and retrieval scoping inside active context budgets.
198- context-degradation: stale or conflicting memories as context poisoning or clash.
199- bdi-mental-states: formal mental-state modeling when beliefs, desires, intentions, and provenance chains matter.
200- multi-agent-patterns: shared memory across agents.
201- evaluation: memory quality, retrieval correctness, and benchmark selection.
202
203## References
204
205Internal references:
206- [Implementation Reference](./references/implementation.md) - Read when: implementing vector stores, property graphs, temporal queries, or memory consolidation logic from scratch
207
208Related skills in this collection:
209- context-fundamentals - Read when: designing the context layer that memory feeds into
210- multi-agent-patterns - Read when: multiple agents need to share or coordinate memory state
211
212External resources:
213- Zep temporal knowledge graph paper (arXiv:2501.13956) - Read when: evaluating bi-temporal modeling or Graphiti's architecture
214- Mem0 production architecture paper (arXiv:2504.19413) - Read when: assessing managed memory infrastructure trade-offs
215- Cognee optimized knowledge graph + LLM reasoning paper (arXiv:2505.24478) - Read when: comparing multi-layer semantic graph approaches
216- LoCoMo benchmark (Snap Research) - Read when: evaluating long-conversation memory retention
217- MemBench evaluation framework (ACL 2025) - Read when: designing memory evaluation suites
218- Graphiti open-source temporal KG engine (github.com/getzep/graphiti) - Read when: implementing temporal knowledge graphs
219- Cognee open-source knowledge graph memory (github.com/topoteretes/cognee) - Read when: building customizable ECL pipelines for memory
220- [Cognee comparison: Form vs Function](https://www.cognee.ai/blog/deep-dives/competition-comparison-form-vs-function) - Read when: comparing graph structures across Mem0, Graphiti, LightRAG, Cognee
221
222---
223
224## Skill Metadata
225
226**Created**: 2025-12-20
227**Last Updated**: 2026-05-15
228**Author**: Agent Skills for Context Engineering Contributors
229**Version**: 4.1.0
230