Building Agent Memory: A Practical Guide to Architecture and Implementation
This article explains why AI agents need a dedicated memory layer and how to build one. It covers a layered memory model (working, episodic, semantic, procedural, and graph memory), core technical options such as summarization, vector retrieval, hybrid search, and structured or graph storage, along with write, consolidation, and forgetting strategies. A reference implementation skeleton and engineering best practices for privacy, observability, cost, and evaluation are included to help developers design long-term, reusable memory for agents.
1. Why Agents Need a Dedicated Memory Layer
Large language models are inherently stateless: once a session ends, the model does not automatically retain any information from the previous turn. Although the context window can hold a large amount of text, it is constrained by three factors at once—cost, latency, and attention dilution. The more content you pack in, the higher the chance that critical information gets ignored. For this reason, memory cannot be treated in engineering terms as simply concatenating the entire history into the prompt.
A more sound abstraction is to treat memory as an independent data subsystem responsible for four things: recording what happened, deciding what is worth keeping in the long term, retrieving relevant content when needed, and consolidating or retiring information when conflicts and outdated data appear. This is exactly what separates an agent from a simple question-answering bot: an agent must maintain goals, constraints, and experience across multiple steps and multiple sessions. Otherwise, it has to plan from scratch every turn and can never accumulate capability.
2. A Layered Memory Model
The layered approach widely accepted in the industry is as follows, and you can trim it to fit your needs during implementation:
- Working memory (short-term): the intermediate state of the current task, such as planned steps, tools already called and their return values, and unfinished subgoals. Its lifecycle is bound to the task.
- Episodic memory (mid-term): session-level or task-level summaries of history, used for cross-turn reference resolution and preference retention.
- Semantic memory (long-term): stable facts and user profiles, for example “the deployment environment is a container platform” or “prefers concise answers.”
- Procedural memory (skills): reusable sequences of operations and tool-use experience, essentially retrievable process templates.
- Structured/graph memory: an explicit representation of entities and relationships, suitable for multi-hop reasoning and consistency checks.
The key value of layering is that different layers use different storage and different eviction strategies, rather than stuffing everything into the same vector collection.
3. Core Technical Approaches and Selection
3.1 Summarization and a Rolling Window
The lightest approach: keep the most recent N turns verbatim and generate structured summaries (goals, constraints, conclusions, to-dos) for earlier content with the model. The advantages are zero external dependencies and fast implementation; the downside is that summaries lose detail and the compression itself consumes calls. It works well as a fallback and a first-layer filter.
3.2 Vector Retrieval Memory
Split content into chunks, embed them, and write them into a vector store, then retrieve the Top-K by semantic similarity. The engineering effort concentrates on three areas: chunk granularity (split by semantic paragraphs rather than a fixed character count), metadata design (time, source, session, permission tags), and similarity thresholds plus reranking. Similarity alone is often not enough; it is recommended to add time decay and an importance weight:
def score(item, sim, now, lam=0.02, w=0.7):age_days = (now - item.ts).daysrecency = 0.5 ** (age_days / 30) # 30-day half-lifeimportance = item.meta.get("importance", 0.5)return w * sim + (1 - w) * (0.5 * recency + 0.5 * importance)
3.3 Keyword and Hybrid Retrieval
Pure vector search is insensitive to proper nouns, IDs, and error codes. Adding an inverted index/keyword channel and fusing it with vector results (for example, reciprocal rank fusion) can significantly improve recall. In practice, hybrid retrieval is usually the most cost-effective optimization step.
3.4 Structured Memory and Graph Memory
Put user profiles, project configurations, and task states into relational or document stores, and read/write them precisely by primary key; put entity relationships into a graph structure to support multi-hop queries like “which config item does this service depend on.” Graph memory is relatively costly to maintain for consistency, so it is recommended to enable it only in domains with clear relationship semantics.
3.5 Writing, Consolidation, and Forgetting
Before writing, perform a “worth-keeping” check: does the content contain stable facts, preferences, conclusions, or lessons? Discard greetings and one-off small talk outright. The consolidation stage handles three types of conflicts: new values overriding old ones (with timestamps), merging synonyms, and keeping contradictions while annotating their sources. Forgetting strategies include time decay, eviction at a capacity limit, and cleanup of low-value tags. A memory system without a forgetting mechanism will quickly be drowned in noise.
4. Reference Implementation Skeleton
class Memory:def __init__(self, store, embed, summarizer):self.store, self.embed, self.summarizer = store, embed, summarizerdef write(self, text, meta):if not self.summarizer.is_worth_keeping(text):returnself.store.upsert(self.embed(text), text, meta)def recall(self, query, k=6):hits = self.store.search(self.embed(query), top_k=20)hits = sorted(hits, key=lambda h: score(h, h.sim, NOW), reverse=True)return [h.text for h in hits[:k]]
The sample code only expresses the structure: the four parts—embedding, storage, scoring, and retrieval—are decoupled to make implementations easy to swap.
5. Engineering Best Practices and Common Pitfalls
- Permissions and isolation: memory must carry tenant and user dimension tags, with filtering enforced during retrieval to avoid cross-user contamination.
- Privacy and compliance: define retention periods and deletion channels, and desensitize sensitive fields before storing them.
- Observability: log the hit chunks and scores for each recall to make it easier to review “why the answer was wrong.”
- Cost and latency: summarize before retrieving, cache high-frequency queries, and control Top-K and context length.
- Evaluation loop: build an annotated memory Q&A set and measure recall, answer accuracy, and redundancy separately.
- Cloud implementation: general-purpose capabilities such as vector retrieval, object storage, message queues, log services, and monitoring/alerting are enough to cover the needs; the relevant general product categories from Baidu AI Cloud can serve as the underlying foundation, with specific selection based on your own scale and compliance requirements.
6. Conclusion
Memory capability is not a single-point component but systems engineering that combines layered modeling, hybrid retrieval, consolidation and forgetting, and evaluation governance. It is recommended to start with a rolling summary, gradually introduce vector and hybrid retrieval, and then add structured and graph memory in scenarios with clear relationships, using observability data to drive iteration. Only then can an agent truly possess long-term capabilities that can be accumulated and reused.
