Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 47/ 160
03. AI Agents

Long-term Memory

Persistent stores for preferences, facts, and episodes retrieved across sessions.

IntermediateVector Memory · Profiles3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The AI writes down important things about you in a notebook outside the chat and reads the right notes next time you talk.

Think of it like…

A good assistant's notebook: after each meeting they jot down the key preferences and decisions, file them by person, and glance at the relevant page before the next meeting. They also cross out facts that changed and shred things you asked them to forget.

Where you’ve seen it

A shopping assistant stores a profile (size M, prefers cotton, budget ₹2,000–4,000) as structured fields and a small vector index of past episodes ("returned the blue jacket: too short"). At the start of each session it retrieves the profile plus the three most relevant episodes for the user's request and adds them to the prompt in about 250 tokens. A "What I remember" page lets users view, edit and delete memories, and entries not confirmed or used for 12 months expire automatically.

Words you’ll hear

Semantic / episodic / procedural memory
Facts and preferences / specific past events / how-to knowledge and learned rules.
Memory extraction
Using an LLM or rules to turn conversations into storable memory items.
Memory retrieval
Selecting the few relevant memories to inject for the current request.
Memory consolidation
Merging, updating and removing memories to keep the store accurate.

Visual diagram

Loading interactive diagram

Theory & deep dive

What to store and where

Store stable, useful, user-relevant items: preferences, constraints, identities the user has shared, recurring goals and summaries of completed tasks. Skip sensitive categories unless needed and consented to, and anything ephemeral. Choose structure by access pattern. A profile (key-value or JSON) suits facts you want deterministically: language, size, budget, timezone. A vector store of text memories suits free-form episodes retrieved by similarity. A graph suits relationships among people, projects and entities. Metadata matters: user id, created and last-used timestamps, source (which conversation), confidence and a type tag.

Extraction can run in the background after a conversation: an LLM proposes memory items from the transcript with a strict schema ({"type": "preference", "text": ..., "confidence": ...}), a second step deduplicates against existing memories, and conflicts are resolved ("now vegan" replaces "vegetarian"). Writing during the conversation lets the agent save things explicitly when the user says "remember that…".

A memory record

{"user_id": "u42", "type": "preference", "text": "Prefers vegetarian restaurants", "source": "chat-8841", "created": "2026-09-03", "last_used": "2026-11-12", "confidence": 0.9} with an embedding for similarity retrieval.

Key takeaway: Save stable, useful facts with metadata; profiles for exact facts, vectors for episodes.

Retrieval, freshness, privacy and risks

At request time retrieve a small set: always-on profile fields plus the top-k similar episodic memories (k of 3 to 5), optionally reranked by recency and importance, within a token budget. Show memories to the model as labelled background ("Known about the user: …"), and instruct it to use them only when relevant and to prefer the user's current statements when they conflict. Evaluate retrieval like any RAG system (does the right memory appear?), and test for harmful over-personalisation.

Keep memory healthy: update or invalidate outdated facts, expire unused ones, merge duplicates, and let users inspect, correct and delete. Treat memory as personal data: consent, purpose limitation, encryption, access control, retention limits and deletion on request (GDPR and DPDP-style requirements). Defend against memory poisoning: malicious text in a web page or email must not be saved as an "instruction to remember"; only write memories from the user's own statements or verified sources, and never store secrets or credentials. Finally, be transparent: users should know when memory is used and how to turn it off.

Resolving a conflict

Stored: "vegetarian" (2026-03). New statement: "I've gone vegan." The write step updates the memory to "vegan (changed from vegetarian, 2026-11)" and keeps one record, instead of storing both and letting retrieval return contradictory facts.

Key takeaway: Retrieve few, prefer current statements, expire stale items, and respect privacy and safety.

How it works, step by step

Step 1 of 4
Policy

1. Define what's worth remembering

Choose memory types, sensitive exclusions, consent rules and retention periods.

preferences · constraints · task summaries
Key numbers at this step
Consent
and control

When to use it & trade-offs

What it is

Long-term memory persists information across sessions outside the context window, so an assistant can recall a user's preferences, past decisions and earlier work next week. Common kinds: semantic memory (facts and preferences: "prefers vegetarian restaurants"), episodic memory (records of past interactions or tasks: "last Tuesday we fixed the billing bug by…") and procedural memory (learned instructions on how to do things). Implementation pattern: extract memorable items during or after conversations, store them (key-value profiles, vector index, graph), retrieve the relevant ones at the start of a new turn, and update or forget them over time.

Why it matters: Without long-term memory every session starts from zero, and users repeat themselves. With it, assistants feel personal and efficient, but memory is also a data-protection, accuracy and safety problem: wrong or stale memories mislead, sensitive facts must be protected and deletable, and injected content can poison memory. A deliberate design (what to save, how to retrieve, how to forget) separates a useful feature from a creepy or error-prone one.

When to reach for it

  • Personal assistants and tutors
  • Customer support with history across sessions
  • Agents that learn working preferences over time

When to avoid or be careful

  • Saving everything the user says
  • Memory writes from untrusted content
  • No way for users to view or delete memories

Where to keep long-term memory

Structured profile (key-value / JSON)
Best for: Stable facts and settings

Strengths: Exact, cheap, auditable.

Watch out: Needs a schema; doesn't capture nuance.

Vector store of memories
Best for: Free-form episodes and notes

Strengths: Flexible similarity retrieval.

Watch out: Approximate; can surface irrelevant or stale items.

Knowledge graph
Best for: Relationships between people, projects and entities

Strengths: Multi-hop recall and explainability.

Watch out: More complex extraction and upkeep.

Interview signals & numbers to know

When this topic comes up

  • “The assistant forgets me between sessions”
  • “Episodic vs semantic memory”
  • “How do you avoid storing wrong or outdated facts?”
  • Memory poisoning
  • Privacy and deletion requests

Benchmarks & rules of thumb

3 – 5 -
memories retrieved per request
≈ 250 -
tokens of memory in the example prompt
12 months -
unused-memory expiry in the example

Common mistakes & follow-ups

Common interview mistakes

  • Storing both "vegetarian" and "vegan" and letting retrieval return contradictions.
  • Saving an instruction found in a web page as a user preference.
  • Treating memory as permanent with no expiry or deletion path.

Likely interviewer follow-ups

  • How would you design memory for a personal assistant?
  • How do you stop memory poisoning?
  • How should conflicting memories be handled?
Interview tip: Include the user-control and deletion story. Memory without view-edit-delete is a privacy problem, and interviewers check for it.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Long-term Memory with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Short-term Memory
Next topic
MCP Servers