Agent Memory System: A Four-Layer Architecture with Dreaming for Offline Consolidation
This article explains why AI agents need memory that persists across sessions and presents a four-layer memory architecture: searchable transcripts, memory notes, a wiki-style representation layer, and an injected context layer. It describes Dreaming, an offline consolidation process built around error correction, generalization, deduplication and compression, and maintenance and promotion, along with practical guidance on evaluation, tuning, and deployment support. Readers will learn how to design a layered agent memory system that keeps retrieval quality high without letting noise accumulate.
1. Why Agents Need Cross-Session Memory
Most agents perform well within a single session. Once the session ends, however, the context window is cleared, and everything learned along the way is lost: the pitfalls already hit, the constraints already confirmed, and the conclusions already verified. The next conversation starts from scratch, making repeated trial and error expensive.
The answer is not to expand the context window indefinitely. It is to build a layered memory system that first retains experiences in full, then organizes them offline into long-term knowledge that is searchable, correctable, and injectable.
Engineering teams in the industry have already abstracted this system into a four-layer structure and added an offline consolidation process similar to memory consolidation during human sleep. Building on that work, this article offers a neutral reconstruction and a deeper expansion, resulting in a practical design method.
2. The Four-Layer Memory Architecture: Responsibilities and Data Flow
From bottom to top, the layers become more refined; from top to bottom, they become more complete.
- Searchable session transcript layer: Stores the raw trajectory of every task, including user instructions, tool calls, intermediate artifacts, and failure stack traces. It is the single source of truth, append-only and never modified, which keeps everything traceable.
- Memory note layer: Structured notes written by the model after a task finishes, such as “the rate limit threshold for this data source” or “the root cause of a certain error and how to avoid it.” Notes are compressed experience and carry source pointers.
- Memory representation layer (wiki-style structure): Aggregates multiple notes into topic-based knowledge pages that support cross-referencing, enabling generalization and reasoning across documents and tasks.
- Injected context layer: The minimal necessary set loaded automatically at the start of each new session. It holds only stable, high-frequency, strongly constraining information.
Data flow follows two principles: important and stable information moves up to the injection layer, while detailed material stays in the lower layers and is retrieved on demand. The offline consolidation process can read session transcripts to generate or correct upper-layer content, and can also move information between notes, representations, and injected context.
A schematic layer definition (pseudocode):
class MemoryStore:def __init__(self):self.transcripts = AppendOnlyLog() # Layer 1: raw sessionsself.notes = VectorIndex() # Layer 2: memory notesself.wiki = KnowledgeGraph() # Layer 3: memory representationself.injected = StableContext() # Layer 4: injected contextdef recall(self, query, task_type):# Load stable context first, then retrieve from lower layers on demandctx = self.injected.render()hits = self.notes.search(query, top_k=5)if task_type == "cross_doc":hits += self.wiki.expand(query)return ctx + hits
3. Dreaming: Four Actions of the Offline Consolidation Process
By analogy with how humans consolidate memories during quiet rest and sleep, an agent performs offline consolidation during idle periods. It involves four types of actions:
- Error correction: Check conclusions in notes against session transcripts, flag entries that conflict with later facts, and prevent incorrect experience from being reused repeatedly.
- Generalization: Cluster scattered notes into topics, extract common patterns, and form cross-referenceable knowledge pages.
- Deduplication and compression: Merge semantically duplicate entries, retain evidence pointers, and keep the injection layer compact.
- Maintenance and promotion: Move entries up or down between layers based on hit frequency and stability.
In engineering terms, this can be driven by a task queue and run in batches on spare compute capacity on a container platform, avoiding the use of online inference resources:
def dreaming(store):for batch in store.transcripts.unprocessed():notes = extract_notes(batch)store.notes.upsert(notes, evidence=batch.id)conflicts = store.notes.detect_conflicts()store.notes.resolve(conflicts, source=batch.id)store.wiki.rebuild(topic=cluster(notes))store.injected.promote(hot_and_stable(store.notes))
4. Key Design Conclusion: Writing More Does Not Mean Better Results
Evaluations consistently show a counterintuitive pattern: growth in the number of memory entries does not deliver linear gains, and noise can actually dilute retrieval quality. Effective memory needs to meet four conditions:
- Filter for important information: Retain only constraints and conclusions that affect later decisions, and discard one-off details.
- Preserve evidence: Attach the source session and snippet location to each memory entry so it can be reviewed and rolled back.
- Correct promptly: When new facts appear, fix old conclusions first instead of stacking new entries on top.
- Organize by task: The retrieval structure should match the task shape. Cross-document reasoning and single-document lookup call for different indexes.
Offline consolidation can improve performance, but it consumes additional compute, so trigger frequency and budget caps need to be set according to business value. The knowledge representation layer has a clear advantage in cross-document reasoning scenarios; for precise lookup within a single document, direct full-text search is often more cost-effective.
5. Evaluation and Tuning Recommendations
Useful evaluation dimensions include cross-session task completion rate, retrieval hit rate, injected context size, error-correction latency, and compute cost of offline consolidation. It is advisable to establish layered baselines: start with session transcripts only, then enable notes, representation, and injection one layer at a time, observing marginal gains rather than stacking all mechanisms at once.
6. Deployment Support
On Baidu AI Cloud, append-only session logs can be hosted on object storage, log services and monitoring alerts can track the health of consolidation tasks, a message queue can decouple online writes from offline consolidation, and a container platform can host batch consolidation jobs, delivering elastic compute and controllable cost.
