Zero Labs
Industry News / AI

Memory — Why Your Agent Keeps Forgetting, And How to Fix It

Source · Towards AI By Avinash Gatreddi

From the publisher’s feed, collected in the ZeroLabs newsroom.

Memory — Why Your Agent Keeps Forgetting, And How to Fix ItThe Kitchen Series | Blog 2 of 10Building on Blog 1: We engineered what goes on the prep station right now. But what happens when the customer leaves and comes back three weeks later? The prep station is empty. The context window is gone. Everything you worked to assemble — vanished. That’s the memory problem.The Story Before We BeginIt’s a Thursday evening. Customer A walks back into Restaurant X for the third time this month.He sits down. The same waiter walks over.“Welcome back! What can I get you tonight?”He pauses. “Same as usual — you know what I like.”The waiter smiles politely, pulls out a notepad, and asks: “Of course! And what’s your name?”That moment — the flicker of frustration on Customer A’s face is the memory problem.He has been here three times, told them about the peanut allergy on his first visit, gave feedback about overcooked noodles on his second and has a clear spice preference. He is a loyal, returning customer and the restaurant remembers nothing.Every visit starts from zero. Every preference re-explained. Every allergy re-declared. Every interaction a transaction with a stranger.Now imagine the opposite.The waiter walks over, smiles genuinely, and says:“Welcome back! The schezwan noodles tonight — should I go slightly less spicy than last time? And we’ve got a new wok chef, so no risk of overcooking. Kitchen confirmed sunflower oil as always.”Same restaurant. Same menu. Same model. Different memory.That is the difference between an AI agent that feels transactional and one that feels intelligent. And the gap between them is not the model — it is the memory architecture sitting behind it.WHAT: What Is Memory in an AI Agent System?Memory in AI agents is the mechanism by which information persists beyond the current context window and becomes available to future interactions.When a conversation ends, the context window is gone. Every message, every preference, every decision — wiped. The next conversation starts with a blank slate unless something deliberately captures, stores, and retrieves what matters.Memory is the bridge between sessions.But memory is not a single thing. It is a spectrum of persistence types, each serving a different purpose, each operating at a different timescale.Memory vs. Context — Drawing the LineBefore we go further, we need to draw a boundary that most articles never draw explicitly — and its absence causes persistent confusion.Context is what is assembled and injected into the current window right now. It is active, live, and ephemeral. When the session ends, context is gone.Memory is what persists outside the window between sessions. It is stored, dormant, and durable. It only becomes active when it is retrieved.The relationship between them is directional:Memory lives outside the window → At retrieval time, relevant memory is pulled → Pulled memory is injected INTO context → Memory becomes context for this session → Session ends — context clears → But memory persists in storage, unchangedMemory feeds context. They are not parallel systems — one is upstream of the other. Context engineering (Blog 1) is about assembling the window well. Memory engineering is about what gets stored between windows and how the right pieces surface when needed.Kitchen: The prep station (context) is assembled fresh before each service. The customer file (memory) is what gets pulled from the filing cabinet to build that prep station. The filing cabinet persists between services. The prep station doesn’t.This distinction matters for everything that follows.The Six Types of Memory1. Short-Term Memory (Working Memory)What is happening right now, in this conversation.This is the active prep station — the current order, the live instructions, the ongoing task state. It exists inside the context window and disappears when the session ends.Kitchen: The chef holds the current order in mind — schezwan noodles, medium spice, no peanuts, less oil. Once the dish is served, this information is no longer actively needed.In AI: The conversation history within a single session. Everything the model is currently reasoning over.Lifespan: Session only. Gone when context clears.2. Episodic MemorySpecific past events — what happened, when, with whom, and what the outcome was.Kitchen: The waiter remembers: “Customer A came in last Friday. He ordered schezwan noodles, medium spice, no peanuts. He said the noodles were slightly overcooked and the flavour was excellent.”In AI: Conversation summaries, interaction logs, past task outcomes, user feedback history. The agent can recall: “Last time this user asked for a report and wanted bullet points, not prose.”Lifespan: Persists across sessions. Stored externally and retrieved when relevant.3. Semantic MemoryGeneral knowledge — facts, concepts, relationships — not tied to any specific event.Kitchen: The head chef knows schezwan cooking requires high-heat wok technique. Peanuts are a common allergen. Certain sauces contain hidden allergens. This knowledge wasn’t learned from a specific customer — it’s accumulated culinary understanding.In AI: The model’s trained knowledge, domain facts stored in a knowledge base, entity relationships in a graph. The agent knows what a refund policy is, what a SQL query does, what the capital of France is — not because a user told it, but because it was trained or stored.Lifespan: Long-lived. Changes slowly through retraining or knowledge base updates.4. Procedural MemoryHow to do things — step-by-step workflows, tool sequences, task patterns.Kitchen: The kitchen’s standard operating procedure for handling allergy orders: check the profile → confirm with the customer → flag to the chef → use separate utensils → verify before plating. Nobody re-invents this every service. It’s encoded in the workflow.In AI: Stored agent workflows, tool-use patterns, prompt templates, skills, task decomposition strategies. The agent knows: “When asked to generate a report, first retrieve the data, then summarise, then format as markdown.”Lifespan: Stable. Updated when workflows change.5. Long-Term MemoryAccumulated patterns, preferences, and learned behaviours built up over many interactions.Kitchen: After fifty visits, the kitchen knows Customer A deeply — not just his last order, but his patterns. He always comes on Fridays. He always starts with noodles. He’s been gradually reducing his spice level over time. He mentions when he’s had a bad week and orders comfort food.In AI: User preference profiles built over time, personalisation data, behavioural patterns. The agent learns: “This user prefers concise answers. This user always asks follow-up questions. This user’s tone changes when they’re frustrated.”Lifespan: Grows and evolves continuously.6. External Memory (Retrieval Memory)Information stored outside the model entirely — in databases, vector stores, document repositories — retrieved on demand when relevant.Kitchen: The restaurant’s physical order history system. The allergy database. The loyalty programme records. The feedback log. None of this lives in any chef’s head — it lives in a system that the kitchen can query when needed.In AI: Vector databases, relational databases, knowledge graphs, document stores. The agent doesn’t know this information — it retrieves it. This is the foundation of RAG (Retrieval Augmented Generation), which we’ll cover in depth in Blog 6.Lifespan: As long as the storage system maintains it.WHY: Why Memory Is the Difference Between a Tool and a SystemWithout memory, every interaction is the first interaction.The user has to re-establish context. Re-explain preferences. Re-state constraints. Re-declare allergies. The agent is capable, but it is incapable of knowing who it’s talking to.This creates three distinct problems:Problem 1: The System That Never Learns YouThe user asks the same clarifying question on day one that the agent asks on day one hundred. The agent is technically functional. The experience is deeply frustrating.“Any dietary restrictions?”“Any dietary restrictions?”“Any dietary restrictions?”In enterprise AI systems, this is not just a UX problem — it’s a trust problem. Users stop believing the system is intelligent when it proves, repeatedly, that it remembers nothing.Problem 2: Compounding Context LoadWithout memory, users compensate by front-loading every conversation with background context. “I’m working on a data pipeline, we use Spark, our schema looks like this, last time we tried X and it failed because of Y…”This burns context window space before the actual task begins. It increases latency. It increases cost. And it still doesn’t capture everything — users forget to include things that memory would have surfaced automatically.Problem 3: No Learning, No ImprovementAn agent without memory cannot improve through use. Every interaction is isolated. Feedback from one session never influences the next. The agent cannot notice patterns. It cannot adapt to a user’s style. It cannot get better at serving a specific person over time.A great restaurant gets better the more a customer visits. An agent without memory stays exactly the same regardless of how many conversations have happened.The Cold Start Problem — The First VisitEvery memory system faces a problem that almost nobody documents: what happens before any memory exists?Customer A’s very first visit. No file. No history. No preferences on record.A bad restaurant treats this as a blank state and asks everything from scratch, creating an impersonal experience from the first moment.A smart restaurant has a cold start strategy.In AI agent systems, cold start has four approaches:1. Bootstrap from existing dataBefore the first interaction, populate memory from data you already have. CRM records, past support tickets, onboarding forms, account data, purchase history. The agent’s first conversation starts with a head start.def bootstrap_memory(user_id: str, crm_data: dict): """Populate memory before first agent interaction.""" memory.add([{ "role": "system", "content": f"""Known facts about this user before first interaction:- Account type: {crm_data.get('account_type')}- Industry: {crm_data.get('industry')}- Past support topics: {crm_data.get('support_history')}- Subscription tier: {crm_data.get('tier')}""" }], user_id=user_id)2. Graceful onboardingOn first interaction, acknowledge the blank slate honestly and gather key preferences quickly — but only ask what you can’t infer.Agent: "Welcome! This is your first time here — I'd love to learn your preferences as we go. One thing upfront: any dietary restrictions I should always keep in mind?"One question. Not ten. The rest gets captured naturally through interaction.3. Default profilesMaintain sensible defaults based on user segment, role, or persona until personal preferences override them. A new enterprise user gets the enterprise default profile. A new consumer user gets the consumer default. Personalisation accumulates from there.4. Graceful degradationDesign the agent to work well with zero memory — not to fail. Missing memory should trigger a slightly more careful, clarifying interaction style, not a broken experience.The cold start problem is temporary. The memory system’s job is to make it as short as possible.Memory Scoping — Who Owns WhatThis is one of the most underspecified aspects of memory design — and one of the most consequential in production.Not all memory is the same scope. There are four distinct levels, each with different ownership, access rules, and privacy implications.SCOPE HIERARCHY├── Session Memory — this conversation only├── User Memory — this person across all sessions ├── Agent Memory — what this agent has learned across all users└── Org Memory — shared knowledge across the entire deploymentSession MemoryLives for the duration of one conversation. Task state, current order, active reasoning chain. Wiped when the session ends. This is working memory — already in context.User MemoryBelongs to one specific person. Preferences, allergies, history, feedback, communication style. Private to that user. Must never surface in another user’s session.Agent MemoryWhat the agent itself has learned across many users — not about any specific person, but about patterns, common failure modes, effective strategies. This is the agent’s accumulated intelligence.Org MemoryShared knowledge available to all users and all agent instances within an organisation. Policies, product knowledge, common procedures, institutional facts.Why This Distinction Matters — The Privacy BoundaryThe line between user memory and agent/org memory is where privacy violations happen.Customer A mentions she’s managing a health condition that affects her diet. This is user memory — deeply personal, belongs only to her session and profile.The insight “users who mention health conditions tend to prefer detailed ingredient information” is agent memory — a pattern derived from many users, personally identifiable to none of them.User memory must never become org memory without explicit consent and anonymisation.In AI systems, the equivalent violation is: a user tells the agent something personal, and the agent incorporates that into its general behaviour in a way that could surface for other users. This is not hypothetical — it is a real failure mode in systems that don’t scope memory correctly.Practical scoping rules:Every memory write operation must carry a scope tagRetrieval must filter by scope before returning resultsUser memory requires user-level access controlOrg memory must be anonymised before it is writtenSession memory never persists to storage without explicit captureMemory and Privacy — The Conversation Nobody HasMost memory articles skip this entirely. They shouldn’t. In production, memory without privacy design is a compliance risk and a trust risk.The five privacy questions every memory system must answer:1. Consent — Did the user agree to be remembered?This is not rhetorical. In many jurisdictions and enterprise contexts, storing user preferences and interaction history requires explicit consent. The restaurant analogy holds: a great restaurant asks “Would you like us to keep your preferences on file for future visits?” — it doesn’t assume.In AI systems, the mechanism varies:Consumer products: opt-in toggle in settings, with clear explanation of what is storedEnterprise: data processing agreements, retention policies, admin controlsHealthcare/finance: regulated consent requirements that go beyond standard terms2. Right to Deletion — Can they make you forget?GDPR Article 17 (Right to Erasure) applies to AI memory systems. A user must be able to request that their memory is deleted — and the deletion must be complete, not just soft-deleted.This has architectural implications. Memory stored in vector databases needs to support true deletion — not just deactivation. Embeddings derived from user data must be deletable. Consolidated summaries that contain user-identifiable information must be tracked and purged.Kitchen: A customer can ask the restaurant to destroy their customer file. The restaurant must be able to do so completely — not just stop showing it to the waiter.def delete_user_memory(user_id: str): """ Complete memory deletion — not soft delete. Must cover: vector store, relational DB, cached summaries, consolidated profiles. """ memory.delete_all(user_id=user_id) # Also delete from: # - conversation history store # - consolidated long-term profile # - any derived/aggregated records # - backup systems (with appropriate delay) log_deletion(user_id, timestamp=datetime.now())3. Data Minimisation — Are you storing more than you need?The principle: store the minimum necessary to serve the user well. A restaurant needs to know about a peanut allergy. It does not need to store that the customer mentioned feeling stressed at work.In AI systems, automatic fact extraction (like Mem0) is powerful — but it will extract more than you need unless constrained. Define explicit boundaries:Store: dietary constraints, stated preferences, task-relevant historyDo not store: emotional states, personal disclosures, financial details, health information beyond what’s directly task-relevant4. Sensitive Memory — Some things should never be storedSome categories of information require special handling or should not be stored at all:Health information (beyond dietary preferences)Financial detailsRelationship status or personal circumstances disclosed in passingPolitical or religious beliefsAnything that was said in emotional distressKitchen: A customer mentions they are going through a divorce while making small talk. This is not a fact to add to their customer profile.5. Access Control — Who can see the memory?In enterprise systems:Can a manager see an employee’s agent memory?Can support staff see a customer’s full interaction history?Can a system admin export all memory for a user?Are audit logs maintained of who accessed what memory?These are not edge cases. They are governance requirements that need to be designed in from the start, not retrofitted after a privacy incident.A practical privacy checklist for memory systems:Consent mechanism in place before memory is writtenUser-facing memory transparency — users can see what is stored about themDeletion endpoint that fully purges all user dataData minimisation rules on what gets extracted and storedSensitive category filters on automatic extractionAccess control on memory retrieval — scoped to the right principalsAudit log of memory reads and writesRetention policy — how long is memory kept before it expires?Data residency compliance — where is the memory physically stored?The Memory Lifecycle — The Full JourneyMemory is not just storage — it is a four-stage process.CAPTURE → PROCESS → STORE → RETRIEVECapture: Something happens that is worth remembering. A user states a preference. A task produces an outcome. Feedback is given. An important fact is mentioned. The system has to decide: is this worth keeping?Process: Raw conversation is rarely stored directly. It needs to be transformed — summarised, structured, extracted into facts, embedded into vectors, tagged with metadata. This is where raw interaction becomes usable memory.Store: The processed memory is written to a persistence layer — a database, a vector store, a knowledge graph. This is where decisions about memory type, namespace, TTL, scope, and access control happen.Retrieve: When a new conversation begins, relevant memory is pulled from storage and injected into context. The right memory, for the right user, at the right moment. Not everything — just what’s relevant.Each stage can fail. Capture can miss important signals. Processing can extract incorrect facts. Storage can corrupt or expire data prematurely. Retrieval can surface irrelevant or stale memories. Memory engineering is the discipline of making all four stages reliable.Memory Retrieval Strategies — How the Right Memory SurfacesThe blog so far has said “retrieve relevant memory” as if that’s simple. It isn’t. How retrieval is triggered and how relevance is determined are active engineering decisions with real tradeoffs.1. Proactive RetrievalMemory is retrieved before the user says anything, based purely on who they are. The moment a session starts, the system pulls the user’s profile, recent history, and standing preferences — before the first message arrives.Kitchen: The moment Customer A walks through the door, the waiter pulls her customer file before approaching the table.Best for: Known users with rich profiles. High-value, returning customers. Systems where personalisation from the first message matters.Tradeoff: Costs tokens and latency on every session start, including sessions where the memory turns out not to be needed.2. Reactive RetrievalMemory is retrieved in response to what the user says. A message comes in, semantic search runs against the memory store, relevant facts surface.Kitchen: The waiter only checks the allergy file when the customer mentions a dietary restriction.Best for: General-purpose agents where users have varied needs. Systems where proactive retrieval cost is prohibitive.Tradeoff: The first message may be answered without relevant memory, which can feel impersonal.3. Hybrid RetrievalProactive retrieval for a small, high-signal profile (allergy flags, critical preferences) combined with reactive retrieval for the broader history.Kitchen: The allergy card is always pulled when the customer arrives (proactive). Full order history is only consulted when the customer references a past visit (reactive).Best for: Most production systems. Balances personalisation quality with cost.4. Recency vs. RelevanceWhen multiple memories match a query, which wins — the most recent, or the most semantically relevant?Example: Customer A said “medium spice” 18 months ago and “I’ve been going milder recently” last week. Which preference drives tonight’s recommendation?Recency wins in most personalisation scenarios — preferences evolve. But relevance wins when the query is specific — asking about a particular dish should surface memories about that dish, not the most recent interaction regardless of topic.Most production systems implement a weighted score: final_score = (relevance_score × 0.6) + (recency_score × 0.4) — tuned to the use case.5. Threshold RetrievalOnly inject memory into context if the confidence score exceeds a threshold. Low-confidence retrievals are discarded rather than risking false recall.Kitchen: The waiter only mentions a preference from the customer file if they’re confident it applies to tonight — not if the note is ambiguous or old.This is underused in practice. Injecting uncertain memory is often worse than injecting none — the agent acts on a false signal with false confidence.Who Manages The Lifecycle?Memory lifecycle management is not a single approach. There are fundamentally three patterns, each with different philosophies, tradeoffs, and use cases.1. You Manage It (Manual / Developer-Controlled Memory)You write the code. You decide what to capture, how to process it, where to store it, and when to retrieve it. The agent itself has no awareness of its memory — it just receives context that you’ve assembled.How it works:Conversation ends → Your code extracts key facts → Your code writes to a database → Next conversation starts → Your code queries the database → Your code injects relevant facts into the system prompt → Agent responds with that contextThe kitchen analogy: You are the kitchen manager who personally writes the customer notes after every service, files them, and pulls the right file before every visit. The chef never touches the filing system.When to use it:You need full control over what gets storedYou have specific compliance or data governance requirementsYour memory schema is well-defined and stableYou’re building a simple, single-user applicationTradeoffs:✓ Full control✓ No external dependencies✓ Predictable behaviour✗ You write all the extraction, storage, and retrieval logic✗ Doesn’t scale well to complex multi-user systems✗ No automatic fact extraction — you define what mattersSimple implementation:import anthropicimport jsonfrom datetime import datetimeclient = anthropic.Anthropic(api_key="YOUR_API_KEY")# Simple in-memory store (replace with a real DB in production)memory_store = {}def save_memory(user_id: str, key: str, value: str): if user_id not in memory_store: memory_store[user_id] = {} memory_store[user_id][key] = { "value": value, "timestamp": datetime.now().isoformat() }def get_memory(user_id: str) -> str: if user_id not in memory_store: return "No previous interactions on record." memories = memory_store[user_id] return "\n".join([f"- {k}: {v['value']}" for k, v in memories.items()])def chat_with_memory(user_id: str, user_message: str) -> str: user_memory = get_memory(user_id) system_prompt = f"""You are a personalised restaurant assistant. [CUSTOMER MEMORY]{user_memory}Always use this memory to personalise your responses.After each interaction, identify any new preferences or facts to remember.""" response = client.messages.create( model="claude-opus-4-6", max_tokens=500, system=system_prompt, messages=[{"role": "user", "content": user_message}] ) return response.content[0].text# Session 1user_id = "customer_a"response1 = chat_with_memory(user_id, "I'd like schezwan noodles. No peanuts — I'm allergic. Medium spice.")print("Session 1:", response1)# Manually capture what matterssave_memory(user_id, "allergy", "Peanuts (severe)")save_memory(user_id, "spice_preference", "Medium")save_memory(user_id, "favourite_dish", "Schezwan noodles")# Session 2 (simulating next visit)response2 = chat_with_memory(user_id, "Same as last time please, slightly less spicy.")print("\nSession 2:", response2)GitHub reference: 🔗 https://github.com/anthropics/anthropic-cookbook/tree/main/patterns/agents2. A Memory Service Manages It (Managed Memory — Mem0, Zep)Instead of writing all the memory logic yourself, you hand off the lifecycle to a dedicated memory service. These services sit between your agent and your storage layer — they handle extraction, deduplication, conflict resolution, and retrieval automatically.Mem0 — Adaptive Memory for AI AgentsMem0 is built around one core idea: automatically extract structured facts from raw conversations and build a persistent, queryable memory layer.You send it a conversation. It extracts what matters. You query it with context. It returns relevant memories. You never write extraction logic.How Mem0 works:Raw conversation pair sent to Mem0 → Mem0 LLM extracts facts ("user allergic to peanuts", "prefers medium spice") → Facts stored as structured memory with embeddings → On next query: semantic search returns relevant facts → Facts injected into your agent's context automaticallyThe kitchen analogy: You hire a dedicated memory manager who sits in the corner of the restaurant. After every customer interaction, they pull out a card, write down what matters in structured form, and file it by customer. When a customer returns, they hand the waiter the relevant card before service begins. You never touch the filing system.What makes Mem0 different:Automatic fact extraction from raw conversation — no schema definition neededConflict resolution — if a user says “I hate spicy food” after previously saying “I love spicy food”, Mem0 updates the memory rather than storing a contradictionMulti-level memory — user-level, agent-level, and session-level memories managed separatelySemantic retrieval — query with natural language, not exact keysImplementation with Mem0:pip install mem0ai anthropicfrom mem0 import Memoryimport anthropicmemory = Memory()client = anthropic.Anthropic(api_key="YOUR_API_KEY")def chat_with_mem0(user_id: str, user_message: str) -> str: # Retrieve relevant memories relevant_memories = memory.search(user_message, user_id=user_id, limit=5) memory_context = "" if relevant_memories and relevant_memories.get("results"): facts = [m["memory"] for m in relevant_memories["results"]] memory_context = "\n".join([f"- {f}" for f in facts]) system_prompt = f"""You are a personalised restaurant assistant. {f'[WHAT I REMEMBER ABOUT YOU]{chr(10)}{memory_context}' if memory_context else '[No previous interactions on record]'}Use this to personalise your response.""" response = client.messages.create( model="claude-opus-4-6", max_tokens=500, system=system_prompt, messages=[{"role": "user", "content": user_message}] ) agent_response = response.content[0].text # Add to Mem0 — it handles extraction automatically memory.add([ {"role": "user", "content": user_message}, {"role": "assistant", "content": agent_response} ], user_id=user_id) return agent_response# Session 1print("Session 1:")r1 = chat_with_mem0("customer_a", "I'd like schezwan noodles. No peanuts — I'm severely allergic. Medium spice please.")print(r1)print("\nSession 2 (new visit):")r2 = chat_with_mem0("customer_a", "Same as last time, slightly less spicy.")print(r2)print("\nSession 3:")r3 = chat_with_mem0("customer_a", "The usual. I've gone vegetarian recently.")print(r3)# See what Mem0 extractedall_memories = memory.get_all(user_id="customer_a")print("\nWhat Mem0 remembered:")for m in all_memories.get("results", []): print(f" → {m['memory']}")What you’ll see Mem0 extract:→ User is severely allergic to peanuts→ User prefers medium spice level→ User's favourite dish is schezwan noodles→ User requested slightly less spicy on second visit→ User is vegetarian (updated — resolves against prior food preferences)GitHub: 🔗 https://github.com/mem0ai/mem0Docs: 🔗 https://docs.mem0.aiZep — Long-Term Memory for LLM ApplicationsZep takes a different approach from Mem0. Where Mem0 focuses on fact extraction, Zep focuses on the full conversation graph — preserving episodic memory, extracting entities and relationships, and building a temporal understanding of how interactions evolve over time.What makes Zep different from Mem0:Temporal awareness — Zep understands that memories have a time dimension. It tracks not just what was said, but when, and how preferences have changed over time.Entity extraction — Zep automatically identifies and tracks entities (people, places, products, concepts) and their relationships across conversations.Hybrid retrieval — Zep combines semantic search with BM25 keyword search for more precise memory retrieval.Dialog summarisation — Zep automatically summarises long conversations into condensed, retrievable summaries.When Zep’s temporal awareness matters more than Mem0’s fact extraction:Imagine Customer A has visited 40 times over two years. Her spice preference has evolved — from high, to medium, to mild as her health changed. Mem0 stores the latest fact and resolves conflicts. But Zep can tell you the trajectory — showing that preference drift is a consistent trend, not a one-time change. For a recommendation system, that trend is more valuable than the point-in-time fact.Kitchen: Where Mem0 is the fact card system, Zep is the full customer relationship file — complete with a timeline of visits, how preferences evolved, and a relationship map connecting the customer to their preferences, allergies, and feedback history.Implementation with Zep:pip install zep-python anthropicfrom zep_python import ZepClientfrom zep_python.memory import Memory, Message, Sessionimport anthropicimport uuidzep = ZepClient(api_key="YOUR_ZEP_API_KEY")client = anthropic.Anthropic(api_key="YOUR_ANTHROPIC_API_KEY")def chat_with_zep(session_id: str, user_id: str, user_message: str) -> str: # Retrieve memory context from Zep try: memory = zep.memory.get(session_id) memory_context = memory.context if memory and memory.context else "" except: memory_context = "" system_prompt = f"""You are a personalised restaurant assistant. {f'[MEMORY CONTEXT]{chr(10)}{memory_context}' if memory_context else '[No memory context available]'}""" response = client.messages.create( model="claude-opus-4-6", max_tokens=500, system=system_prompt, messages=[{"role": "user", "content": user_message}] ) agent_response = response.content[0].text # Add messages to Zep memory zep.memory.add(session_id, memory=Memory( messages=[ Message(role="user", content=user_message, role_type="user"), Message(role="assistant", content=agent_response, role_type="assistant") ] )) return agent_response# Create sessionsession_id = str(uuid.uuid4())user_id = "customer_a"zep.memory.add_session(Session( session_id=session_id, user_id=user_id, metadata={"restaurant": "X", "loyalty_tier": "regular"}))response = chat_with_zep(session_id, user_id, "I'd like schezwan noodles. Severe peanut allergy. Medium spice.")print(response)GitHub: 🔗 https://github.com/getzep/zepDocs: 🔗 https://docs.getzep.com3. The Agent Manages Its Own Memory (Agentic Memory — Letta)This is the most philosophically different approach — and the most powerful.In Patterns 1 and 2, memory is managed outside the agent. The agent is passive — it receives context assembled by another system.Letta (formerly MemGPT) flips this entirely.In Letta, the agent itself is aware of its memory, manages its own memory lifecycle, and decides what to remember, what to compress, and what to forget. The agent has explicit memory management tools it can call — just like it might call a search tool or a calculator.The kitchen analogy: Instead of a filing system managed by an external memory manager, the chef themselves carries a notebook. They decide what to write down after each service. They decide when to flip back through old pages. They decide when a note is no longer relevant and cross it out. The memory is the chef’s own.How Letta works:IN-CONTEXT MEMORY (Active) ├── Core Memory — always in context (persona, key user facts) └── Conversation History — recent messagesEXTERNAL MEMORY (Recalled on demand) ├── Archival Storage — long-term facts, searchable └── Recall Storage — conversation history, searchableMEMORY MANAGEMENT TOOLS (Agent-callable) ├── core_memory_append() — add to always-on memory ├── core_memory_replace() — update existing core memory ├── archival_memory_insert() — write to long-term storage ├── archival_memory_search() — retrieve from long-term storage └── conversation_search() — search past conversationsWhat this looks like in practice:User: "I used to love spicy food but I've had stomach issues lately. Please keep that in mind."Agent internal reasoning: → This contradicts existing core memory: "user prefers high spice" → I should update core memory → [calls core_memory_replace("spice_preference", "User previously preferred high spice but now has stomach issues — prefer mild")] → Acknowledges the update to the userImplementation with Letta:pip install lettafrom letta import create_clientfrom letta.schemas.memory import ChatMemoryfrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.embedding_config import EmbeddingConfigclient = create_client()agent_state = client.create_agent( name="restaurant_assistant", memory=ChatMemory( human="Customer A. No known preferences yet.", persona="""I am a personalised restaurant assistant. I remember customer preferences, allergies, and feedback across visits.I actively maintain my memory — updating facts when preferences change,archiving old interaction summaries, and retrieving relevant historywhen customers return.""" ), llm_config=LLMConfig( model="claude-opus-4-6", model_endpoint_type="anthropic", model_endpoint="https://api.anthropic.com/v1", context_window=200000 ), embedding_config=EmbeddingConfig( embedding_endpoint_type="openai", embedding_model="text-embedding-ada-002" ))agent_id = agent_state.id# Session 1 — agent decides what to rememberresponse1 = client.send_message( agent_id=agent_id, message="Hi! I'd like schezwan noodles. I have a severe peanut allergy. Medium spice.", role="user")print("Session 1:", response1.messages[-1].text)# Session 2 — agent recalls from its own managed memoryresponse2 = client.send_message( agent_id=agent_id, message="I'm back! Same as last time but I've been having stomach issues — go mild please.", role="user")print("\nSession 2:", response2.messages[-1].text)# Check what the agent has storedagent = client.get_agent(agent_id)print("\nAgent's core memory about this customer:")print(agent.memory.get_block("human").value)Tradeoffs:✓ Most powerful and adaptive✓ Agent handles contradiction and conflict naturally✓ Memory management scales with agent intelligence✗ More complex to set up and debug✗ Memory decisions depend on model quality✗ Harder to audit — the agent decides, not youGitHub: 🔗 https://github.com/cpacker/MemGPT (now Letta)Docs: 🔗 https://docs.letta.comMemory in Multi-Agent Systems — A PreviewSo far we’ve discussed memory for a single agent interacting with a single user. But real systems increasingly involve multiple agents — a planner, an executor, a critic, a summariser — each specialised, each potentially maintaining its own state.This introduces a new question: when one agent learns something, who else knows?Kitchen: Customer A tells the sommelier she’s avoiding alcohol for health reasons. Does the head chef automatically know this when planning her dessert? Does the waiter know when taking her drinks order? Or does each station maintain its own independent customer notes?Three patterns emerge in multi-agent memory:Isolated memory — each agent maintains its own memory independently. Simple, but creates silos. Agent B never benefits from what Agent A learned.Shared memory pool — all agents read from and write to a shared memory store. Powerful, but requires careful namespace design to prevent one agent’s memories from contaminating another’s reasoning.Memory broker — a dedicated memory agent manages the store, and other agents request memories through it. Adds latency but provides consistent access control and conflict resolution.We’ll go deep on multi-agent architecture in Blog 5 on Harness and Orchestration. But it’s worth noting here: your memory architecture choice now will determine how well you can extend to multi-agent systems later. Design for the scope you’ll eventually need, not just the scope you have today.Memory Failure Modes — When Memory Goes WrongJust as context has failure modes, memory has its own set of ways to silently break your agent.Memory PollutionIncorrect facts get stored and never corrected. The agent “remembers” that a user prefers high spice when they actually said mild. Every future interaction is personalised incorrectly.Kitchen: The customer note says “loves extra spicy” but the waiter misheard “hates extra spicy.” Every visit since has been wrong.False RecallThe retrieval system surfaces a memory that looks relevant but isn’t. The agent confidently applies a preference from User A to User B because their queries were semantically similar.Kitchen: Two customers both ordered noodles last Friday. Their preference cards got mixed up. Both receive the wrong personalisation.Memory StalenessA preference was captured 18 months ago and was accurate then. The user’s tastes, situation, or constraints have changed. The memory was never updated. The agent applies an outdated model of the user.Kitchen: The note says “Customer A is vegetarian.” She stopped being vegetarian two years ago and has mentioned it twice since. The note was never updated.Memory OverloadToo many memories retrieved for a single interaction. The agent is handed 50 facts about a user when it only needed 3. The signal is buried. Relevant facts get underweighted.Kitchen: The waiter hands the chef a 12-page customer history when all they needed was the allergy note.Memory HallucinationThe agent generates a “memory” that was never actually stored. It confabulates a past interaction that didn’t happen, with false confidence.Kitchen: The waiter tells the customer “you ordered the prawns last time” — but the customer has never ordered prawns. The waiter invented a memory.Dreaming — How Agents Consolidate Memory Off-PeakThere is one more memory concept that almost nobody talks about — and it is borrowed directly from neuroscience.When humans sleep, the brain doesn’t go idle. It replays the day’s experiences, consolidates short-term memories into long-term storage, discards irrelevant details, and reinforces patterns that matter. Neuroscientists call this memory consolidation. In everyday language, we call it dreaming.AI agents can do the same thing.The Kitchen AnalogyIt’s 2am. Restaurant X has closed for the night. The kitchen is empty.But the head chef is still there — not cooking, but reviewing.Going through the night’s order tickets. Noticing that three customers independently complained about the noodle texture. Updating the prep instructions. Archiving the resolved feedback. Flagging a pattern: whenever the Friday wok station runs past 11pm, quality drops. Writing that insight into the kitchen’s standing operating procedure.No customers. No orders. No live pressure.Just the kitchen, processing what happened, and preparing to be better tomorrow.That is dreaming.What Dreaming Looks Like in AI Agent SystemsDreaming in AI agents is an offline, asynchronous memory consolidation process that runs between active sessions — not during live interactions.It typically involves:1. Summarisation and CompressionLong episodic memories are compressed into compact summaries. The raw turns are archived. The distilled insight is promoted to long-term memory.Before dreaming:Turn 1: User asked about noodlesTurn 2: Agent confirmed availabilityTurn 3: User asked about spiceTurn 4: Agent listed optionsTurn 5: User chose mediumTurn 6: User mentioned peanut allergy... 40 more turnsAfter dreaming:[Session summary — Friday 8:45pm]Customer A ordered schezwan noodles, medium spice, no peanuts (severe allergy), less oil. Feedback: good flavour, slightly overcooked noodles. Preference trend: spice level gradually reducing across visits.2. Pattern ExtractionAcross many sessions, the agent identifies recurring patterns — not in a single conversation, but across the corpus of interactions.Example insight extracted during dreaming:Pattern detected: Users who mention "stomach issues" in session N consistently request milder food in session N+1. Action: proactively offer mild options when stomach issues are mentioned.3. Memory Promotion and DemotionFacts confirmed across multiple sessions get promoted to high-confidence long-term memory. Facts not referenced in a long time get demoted or archived. Contradicted facts get resolved.4. Knowledge Graph EnrichmentNew relationships between entities are identified and written into the knowledge graph. The agent discovers connections it didn’t explicitly notice during live interactions.5. Embedding RefreshAs the knowledge base grows, older embeddings may become suboptimal. Dreaming schedules re-embedding of important memories to keep retrieval quality high.Dreaming in Production — The Complexity You Need to Plan ForIn production, dreaming pipelines require more thought:Incremental consolidation — don’t reprocess everything on every cycle. Track a “last consolidated at” timestamp and only process new sessions since then. At scale, reprocessing all history nightly is prohibitively expensive.Conflict detection — when the dreaming LLM produces a fact that contradicts existing long-term memory, how is that resolved? Last-write-wins is simple but wrong. A confidence-weighted merge is better — newer, higher-confidence facts override older, lower-confidence ones.Cost management — running LLM calls over all users nightly is expensive at scale. Prioritise by activity level: active users get nightly dreams, occasional users get weekly dreams, dormant users get monthly. Consider cheaper models for summarisation tasks where the raw intelligence of the main model isn’t needed.Failure recovery — if the dreaming job fails mid-run for some users, those users’ memories remain unconsolidated. Maintain a processing queue with retry logic. Never let a dreaming failure silently corrupt a user’s memory state.Audit trail — every memory promotion, demotion, and archival during dreaming should be logged with a reason. This enables debugging when a user asks “why did you forget that?” or “why are you recommending this?”The 2am kitchen review is powerful. But the head chef still needs to log what they changed and why.The Neuroscience ConnectionThis is not just a metaphor. The parallel to human sleep and memory consolidation is deliberate and well-studied.In humans:Slow-wave sleep consolidates declarative memories (facts, events)REM sleep processes emotional memories and extracts patternsSleep deprivation causes memory degradation and poor decision-makingIn AI agents:Offline summarisation consolidates episodic memoryPattern extraction surfaces cross-session insightsNo consolidation causes memory pollution and retrieval degradationContext engineering makes the agent better within a session. Memory makes it better across sessions. Dreaming makes it better over time.Memory Evaluation — How Do You Know It’s Working?Memory evaluation is distinct from general agent evaluation and deserves its own mention here.The core questions:Is the right memory being retrieved? (Precision)Is all relevant memory being retrieved? (Recall)Is retrieved memory accurate? (Correctness)Is retrieved memory fresh? (Freshness)Is memory being silently hallucinated? (Hallucination rate)Three memory quality metrics to track from day one:Retrieval precision — of the memories retrieved, what fraction were actually relevant to the query? Low precision = memory overload, noise in context.False recall rate — how often does the agent act on a memory that turns out to be wrong or mislinked? Catch this by logging memory-influenced decisions and spot-checking.Staleness rate — what fraction of retrieved memories are older than your TTL threshold? High staleness rate = your update and consolidation pipelines aren’t working.Start by logging every retrieval and manually reviewing a sample weekly. You’ll discover your most common failure modes faster than any automated metric will find them.Memory Design Principles — Getting It Right1. Draw the memory-context boundary explicitlyDefine clearly what lives in context (session-scoped) vs. what lives in memory (cross-session). Enforce this in your architecture, not just in documentation.2. Scope memory correctly from day oneSession, user, agent, org — design your namespace and access control before you write a single memory. Retrofitting scope after the fact is expensive and error-prone.3. Build consent and deletion in from the startNot as an afterthought. Memory without a deletion path is a compliance risk waiting to happen.4. Capture with intent, not with everythingNot every message is worth remembering. Capture preferences, constraints, feedback, decisions, and significant facts — not pleasantries, not filler.5. Timestamp everythingEvery memory should carry when it was created and when it was last updated. This enables freshness scoring, staleness detection, and TTL enforcement.6. Build conflict resolution in from the startUsers change. Facts change. Your memory system must handle the case where a new fact contradicts an old one. Update, don’t append blindly.7. Make forgetting intentionalMemory without forgetting becomes noise. Define TTLs for different memory types. Archive old episodic memories. Let procedural memory be updated when workflows change.8. Test retrieval, not just storageMost bugs live in retrieval. Test that the right memories surface for the right queries. Test with adversarial queries. Measure precision and false recall.9. Plan for the cold startEvery user has a first interaction. Design the experience before memory exists to be warm, not blank.10. Design for the multi-agent futureEven if you’re building a single-agent system today, your memory architecture should be extensible to a shared memory pool. The cost of changing memory architecture later is high.The Key TakeawaysWHAT: Memory is the mechanism by which information persists beyond the context window — spanning six types from short-term working memory to long-term external storage. Memory feeds context at retrieval time; they are not parallel systems, one is upstream of the other.WHY: Without memory, every interaction starts from zero. The agent is capable but cannot know who it’s talking to, cannot learn from past interactions, and cannot improve through use. Memory is the difference between a tool and a system that actually knows you.HOW: Memory has a four-stage lifecycle — Capture, Process, Store, Retrieve — and three management patterns:Manual — full control, high effort, best for governed use casesManaged service — Mem0 for fact extraction, Zep for conversation graphs and temporal memoryAgentic — Letta for agents that manage their own memory lifecycleBeyond the lifecycle, memory engineering requires deliberate decisions about scoping (session vs. user vs. agent vs. org), retrieval strategy (proactive vs. reactive, recency vs. relevance), privacy and consent, cold start handling, multi-agent sharing, and failure mode detection.And dreaming — offline consolidation between sessions — is how agents distil raw experience into wisdom over time.In the next blog, we go into Skills — what they are, why they’re not the same as knowledge, and how agent systems develop the ability to reason, plan, and adapt.Next in the series →Blog 3: The Chef Can Read the Recipe — But Can They Cook? (Skills)Memory — Why Your Agent Keeps Forgetting, And How to Fix It was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.