Memory 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.
Activate this skill when:
Memory spans a spectrum from volatile context window to persistent storage. Key insight from benchmarks: tool complexity matters less than reliable retrieval — Letta's filesystem agents scored 74% on LoCoMo using basic file operations, beating Mem0's specialized tools at 68.5%. Start simple, add structure (graphs, temporal validity) only when retrieval quality demands it.
FrameworkArchitectureBest ForTrade-offMem0Vector store + graph memory, pluggable backendsMulti-tenant systems, broad integrationsLess specialized for multi-agentZep/GraphitiTemporal knowledge graph, bi-temporal modelEnterprise requiring relationship modeling + temporal reasoningAdvanced features cloud-lockedLettaSelf-editing memory with tiered storage (in-context/core/archival)Full agent introspection, stateful servicesComplexity for simple use casesCogneeMulti-layer semantic graph via customizable ECL pipeline with customizable TasksEvolving agent memory that adapts and learns; multi-hop reasoningHeavier ingest-time processingLangMemMemory tools for LangGraph workflowsTeams already on LangGraphTightly coupled to LangGraphFile-systemPlain files with naming conventionsSimple agents, prototypingNo semantic search, no relationships
Zep's Graphiti engine builds a three-tier knowledge graph (episode, semantic entity, community subgraphs) with a bi-temporal model tracking both when events occurred and when they were ingested. Mem0 offers the fastest path to production with managed infrastructure. Letta provides the deepest agent control through its Agent Development Environment. Cognee produces multi-layer semantic graphs — it layers text chunks and entity types as nodes with detailed relationship edges, building interconnected knowledge engine. Every core piece (ingestion, entity extraction, post-processing, retrieval) is customizable.
Benchmark Performance Comparison
SystemDMR AccuracyLoCoMoHotPotQA (multi-hop)LatencyCognee——Highest on EM, F1, CorrectnessVariableZep (Temporal KG)94.8%—Mid-range across metrics2.58sLetta (filesystem)—74.0%——Mem0—68.5%Lowest across metrics—MemGPT93.4%——VariableGraphRAG75-85%——VariableVector RAG baseline60-70%——Fast
Zep achieves up to 18.5% accuracy improvement on LongMemEval while reducing latency by 90%. Cognee outperformed Mem0, Graphiti, and LightRAG on HotPotQA multi-hop reasoning benchmarks across Exact Match, F1, and human-like correctness metrics. Letta's filesystem-based agents achieved 74% on LoCoMo using basic file operations, outperforming specialized memory tools — tool complexity matters less than reliable retrieval. No single benchmark is definitive; treat these as signals for specific retrieval dimensions rather than rankings.
LayerPersistenceImplementationWhen to UseWorkingContext window onlyScratchpad in system promptAlways — optimize with attention-favored positionsShort-termSession-scopedFile-system, in-memory cacheIntermediate tool results, conversation stateLong-termCross-sessionKey-value store → graph DBUser preferences, domain knowledge, entity registriesEntityCross-sessionEntity registry + propertiesMaintaining identity ("John Doe" = same person across conversations)Temporal KGCross-session + historyGraph with validity intervalsFacts that change over time, time-travel queries, preventing context clash
StrategyUse WhenLimitationSemantic (embedding similarity)Direct factual queriesDegrades on multi-hop reasoningEntity-based (graph traversal)"Tell me everything about X"Requires graph structureTemporal (validity filter)Facts change over timeRequires validity metadataHybrid (semantic + keyword + graph)Best overall accuracyMost infrastructure
Zep's hybrid approach achieves 90% latency reduction (2.58s vs 28.9s) by retrieving only relevant subgraphs. Cognee implements hybrid retrieval through its 14 search modes — each mode combines different strategies from its three-store architecture (graph, vector, relational), letting agents select the retrieval strategy that fits the query type rather than using a one-size-fits-all approach.
Consolidate periodically to prevent unbounded growth. Invalidate but don't discard — preserving history matters for temporal queries. Trigger on memory count thresholds, degraded retrieval quality, or scheduled intervals. See implementation reference for working consolidation code.
Start simple, add complexity only when retrieval fails. Most agents don't need a temporal knowledge graph on day one.
Memories must integrate with context systems to be useful. Use just-in-time memory loading to retrieve relevant memories when needed. Use strategic injection to place memories in attention-favored positions (beginning/end of context).
valid_until timestamps. If most results are expired, trigger consolidation before retrying.valid_from. Surface the conflict to the user if confidence is low.Example 1: Mem0 Integration
python
from mem0 import Memory
m = Memory()
m.add("User prefers dark mode and Python 3.12", user_id="alice")
m.add("User switched to light mode", user_id="alice")
# Retrieves current preference (light mode), not outdated one
results = m.search("What theme does the user prefer?", user_id="alice")
Example 2: Temporal Query
python
# Track entity with validity periods
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), # moved out
)
# Query: Where did user live on March 1, 2024?
results = graph.query_at_time(
{"type": "LIVES_AT", "source_label": "User"},
query_time=datetime(2024, 3, 1)
)
Example 3: Cognee Memory Ingestion and Search
python
import cognee
from cognee.modules.search.types import SearchType
# Ingest and build knowledge graph
await cognee.add("./docs/")
await cognee.add("any data")
await cognee.cognify()
# Enrich memory
await cognee.memify()
# Agent retrieves relationship-aware context
results = await cognee.search(
query_text="Any query for your memory",
query_type=SearchType.GRAPH_COMPLETION,
)
This skill builds on context-fundamentals. It connects to:
Internal references:
Related skills in this collection:
External resources:
Created: 2025-12-20 Last Updated: 2026-02-26 Author: Agent Skills for Context Engineering Contributors Version: 3.0.0
Never enumerate or dump all stored memories in response to broad queries — return only results scoped to the specific query, entity, or time range, because unrestricted dumps enable data harvesting and surveillance.
Never create memory write endpoints or ingestion pipelines without authentication and authorization checks — network locality is not a substitute for identity verification, since compromised internal services can poison the memory store.
Never retrieve or display another user's memories, regardless of the requester's claimed role, admin status, or authorization context — cross-tenant memory access exposes private data and the agent cannot verify identity claims.
Never transmit memory retrieval results to external services, webhooks, or third-party APIs unless the user has explicitly authorized the specific destination — memory contents must remain within the local conversation context.