AI / Memory Augmented Generation (MAG) Interview questions
Last updated
1. What is Memory-Augmented Generation (MAG)?
Memory-Augmented Generation (MAG) is a pattern where a language model is paired with an external memory it can write to and read from. That lets it use information that is neither in the current prompt nor in its trained weights.
The memory typically holds past conversations, user preferences, task outcomes and learned facts. Before each reply, the system pulls the relevant entries into the prompt. After the reply, it decides what new information is worth saving.
The model itself stays stateless. The persistence comes from the application layer around it, which is what creates the feeling of continuity across turns and sessions.
Take quiz
Inside the model weights, updated after every chat
In an external memory the system reads and writes
Only inside the current prompt window
Retrained nightly on each user's chats
Permanently bound to one session object
Stateless between calls
2. What is the purpose of memory augmentation in LLMs?
It gives an otherwise stateless model continuity. A plain LLM call knows nothing about earlier sessions, and its context window is finite, so anything outside the prompt is simply gone.
Memory augmentation solves three practical problems:
- Personalization - remembering a user's name, stack, tone or constraints.
- Long-running tasks - carrying decisions and progress across sessions or context resets.
- Cost - retrieving a few relevant facts is cheaper than replaying a whole transcript every turn.
It also avoids retraining: new knowledge is a database write, not a fine-tuning job.
Take quiz
Slow tokenization of long prompts
GPU memory fragmentation during training
Stateless calls forgetting earlier sessions
It is just a write, with no retraining needed
It permanently changes the model's attention heads
It guarantees the model will never hallucinate
3. What are the main types of memory in MAG systems?
Most MAG designs borrow terms from cognitive science and split memory into four types.
| Type | What it stores | Example |
| Working | Current task state inside the context window | Last few turns, scratchpad, tool results |
| Episodic | Specific past events with time and context | "Last Tuesday the deploy failed on step 3" |
| Semantic | Distilled facts and preferences | "User prefers Python and tabs" |
| Procedural | How to do things: skills, prompts, workflows | A saved runbook or tool-use recipe |
Real systems usually mix them: working memory lives in the prompt, while the other three sit in external stores.
Take quiz
Semantic memory
Working memory
Procedural memory
Working memory
Episodic memory
Semantic memory
Procedural memory
4. What is working memory in an LLM agent?
Working memory is whatever the model can see right now: the system prompt, recent messages, retrieved memories, tool outputs and any scratchpad notes inside the context window.
It is fast and fully visible to the model, but it is small and temporary. Once a message is trimmed or the session ends, it is gone unless something copied it to long-term storage.
Good agent design treats working memory as a limited budget and fills it deliberately, rather than dumping every stored item in.
Take quiz
The full archive of every past session
The content currently in the context window
The model's pretrained weights
It is automatically merged into the model weights
It is mirrored to every other user's agent
It disappears unless saved to long-term storage
5. What is episodic memory in MAG?
Episodic memory records specific events the agent lived through, usually with a timestamp and some context: who was involved, what was tried, and what happened.
Think of it as a diary. An entry might say that on 3 March the user asked for a CSV export, the first attempt failed on encoding, and switching to UTF-8 fixed it.
It is useful for questions like "what did we try last time?" and for learning from past successes and failures. Episodes are often later summarized into semantic facts so they don't pile up forever.
Take quiz
A timeless general fact about the world
A reusable function the agent can call
A timestamped record of a specific past event
"What did we try last time?"
"What is the syntax of a for loop?"
"How many parameters does the model have?"
6. What is semantic memory in MAG?
Semantic memory stores general facts and preferences detached from the moment they were learned, such as "the user works in healthcare" or "the staging database is Postgres 15".
It is usually produced by extracting or summarizing episodes: the date and chat are dropped, the durable fact is kept. That makes entries short, cheap to retrieve and easy to update when a fact changes.
The trade-off is lost nuance. An extracted fact like "likes dark mode" no longer says when or why it was said.
Take quiz
By extracting durable facts from episodes
By copying raw chat logs verbatim
By re-training the embedding model
Entries can never be updated
Extraction can lose context and nuance
It requires a GPU cluster to query
7. What is procedural memory in an agent?
Procedural memory holds how to do things: reusable skills, workflows, tool-call patterns or refined instructions, rather than facts about the world.
A well-known example is Voyager, a Minecraft agent that stored working code snippets in a skill library and retrieved them for new tasks. In everyday agents it can be a saved runbook, a prompt template that worked, or a learned rule like "always run the linter before committing".
Updating it often means rewriting instructions or adding a new skill entry.
Take quiz
Reflexion
Voyager
kNN-LM
Raw conversation timestamps only
Embeddings of the user's profile photo
Reusable skills and how-to knowledge
8. Define long-term memory in a MAG system?
Long-term memory is any information that outlives a single context window or session and is kept in an external store, such as a vector database, key-value store or graph.
It is not seen by the model until retrieved. A retrieval step searches it using the current query, picks the best entries and injects them into the prompt.
Because it is external, its size is bounded by storage and retrieval quality, not by the model's context length.
Typical contents are user profiles, past decisions and distilled lessons. Entries are usually tagged with timestamps and owners so retrieval can filter and rank them, and so they can be expired or deleted later.
Take quiz
Is always fully visible to the model
Lives only in the KV cache
Persists outside the context window in an external store
Storage and retrieval quality
The model's maximum context length
The number of attention heads
9. What are the core operations of a memory module?
Nearly every memory module reduces to four operations:
- Write - decide what to save and store it with metadata.
- Retrieve - find the entries relevant to the current input.
- Update - merge or correct entries when new information overlaps or conflicts.
- Forget - expire, archive or delete entries that are stale, low value or must be erased.
Many early prototypes only implement write and retrieve, which is why their memory gets noisy over time. Update and forget are what keep it healthy.
Take quiz
Update and forget
Only write
Only retrieve
Write
Retrieve
Quantize
Forget
10. What is a memory store in MAG?
A memory store is the backing storage that holds saved memories. The right choice depends on how you need to query them.
| Store | Good for |
| Vector database | Semantic similarity search over text |
| Key-value / relational DB | Exact lookups: user profile, settings, counters |
| Graph database | Entities and relationships, multi-hop questions |
| Full-text index | Exact keywords, IDs, error codes |
Production systems often combine two or more, since similarity search alone is weak at exact matches and structured filters.
Pick based on the dominant query pattern, not fashion. A support bot that mostly looks up a customer's plan needs a plain table; a research assistant recalling loosely related notes needs embeddings.
Take quiz
A vector database only
A key-value or relational database
A GPU texture cache
Vector databases cannot store text
Graph databases cannot be queried
Similarity search alone is weak at exact and structured queries
11. How do you use a vector database for agent memory?
The basic flow is embed, store, search. Each memory is turned into an embedding and saved with metadata. At query time you embed the current message and fetch the nearest neighbors.
def remember(text, user_id): vec = embed(text) db.upsert(id=new_id(), vector=vec, payload={"text": text, "user": user_id, "ts": now()}) def recall(query, user_id, k=5): return db.search(vector=embed(query), k=k, filter={"user": user_id})
Always filter by user or tenant at query time, and keep timestamps in the payload so you can rank by recency later.
Tune k and add a similarity cutoff so weak matches never reach the prompt. Returning five poor matches is worse than returning none.
Take quiz
The entire vector database
The model's system prompt only
The current query or message
To keep one user's memories from leaking into another's
To make embeddings shorter
To disable approximate search
12. What is memory summarization?
Memory summarization compresses older conversation turns into a shorter note so the context window doesn't overflow. Typically a model is asked to summarize the oldest messages, and the summary replaces them in the prompt.
It keeps cost and latency down and preserves the gist of long chats. The risk is information loss: a summary may drop an exact number or a user's exact wording, and summarizing a summary repeatedly makes this worse.
Many systems keep the raw text in an archive so details can still be retrieved later.
Take quiz
Losing exact details through compression
The context window grows larger
Embeddings can no longer be computed
Delete the summary after one turn
Keep the raw text archived for later retrieval
Summarize only the newest message
13. What is a memory write policy?
A write policy is the rule set that decides what gets saved, when, and in what form. Without one, an agent either stores everything and drowns in noise, or stores nothing useful.
Common policies include:
- Write after every turn, then deduplicate later.
- Write only when an extractor flags a durable fact or preference.
- Write when the user says "remember this".
- Write a summary at session end.
Good policies also set what must never be saved, such as passwords or payment details.
Take quiz
Which GPU runs the embedding model
What is saved, when, and in what form
How many tokens the model can generate
The user's preferred language
Today's task goals
Secrets such as passwords and payment details
14. What is a sliding window buffer memory?
A sliding window keeps only the last N messages or tokens of the conversation and drops older ones as new ones arrive. It is the simplest form of short-term memory.
It is cheap, predictable and needs no extra infrastructure. The downside is hard forgetting: if the user mentioned their deadline 30 turns ago and the window holds 20, the model no longer knows it.
That is why windows are usually paired with a summary of dropped turns or a long-term store.
Take quiz
Moves them into model weights
Duplicates them in every new message
Drops them once the window is full
Important facts fall outside the last N messages
The user sends very short messages
The model has no system prompt
15. What is MemGPT?
MemGPT is a research system (Packer et al., 2023) that treats an LLM's context like an operating system treats RAM. The model gets a small main context plus larger external storage, and it moves data between them itself using function calls.
The external side has recall storage (searchable conversation history) and archival storage (long-term notes and documents). When context fills up, the system warns the model, which can save key facts and evict old messages.
The idea lives on in the open-source Letta framework.
Take quiz
RAM managed by an operating system
A relational schema
A GPU shader cache
Hot cache and cold weights
Recall storage and archival storage
Prompt store and token store
16. What is Mem0?
Mem0 is an open-source memory layer for AI applications that sits between your app and the LLM. It watches conversations, extracts salient facts, and stores them so they can be retrieved in later sessions.
A notable design choice is that, for each candidate fact, the system compares it against similar existing memories and chooses an operation: add, update, delete or do nothing. That keeps memory from filling with duplicates and contradictions.
It supports user-, session- and agent-level scoping so memories stay separated.
Take quiz
Compile, link or run
Add, update, delete or no-op
Train, validate or test
To lower the embedding dimension
To skip tokenization
To avoid duplicates and contradictions
17. What is a knowledge graph memory?
Knowledge graph memory stores information as entities and relationships - nodes and edges - instead of free-text chunks. For example: (Priya) -[works_at]-> (Acme), (Acme) -[uses]-> (Postgres).
It shines on questions that chain facts together, like "which database does Priya's employer use?", where plain similarity search might retrieve unrelated chunks.
The cost is extra work at write time: an LLM or parser must extract clean entities and relations, and mistakes there become wrong edges.
Systems in this space often pair the graph with embeddings on nodes and edges, so you find the starting entity by similarity and then walk the relationships from there.
Take quiz
Flat lists of raw tokens
Sorted arrays of timestamps
Entities connected by relationships
Multi-hop questions chaining several facts
Counting tokens in a prompt
Compressing images
18. List common metadata stored with a memory entry?
Metadata turns a pile of text into something you can filter, rank and audit. Typical fields:
- user_id / tenant_id - ownership and isolation
- created_at, last_accessed_at - recency and decay
- importance - a score, often rated by the model
- type - episodic, semantic or procedural
- source - which conversation or document it came from
- confidence and expiry - how sure you are and when it should lapse
Add only fields you will actually query on. Every extra field is something you must keep consistent through updates and deletions.
Take quiz
created_at or last_accessed_at
tenant_id
source
To shrink the vector size
To audit where a memory came from
To pick the embedding model
19. What is memory decay (forgetting) in MAG?
Memory decay lowers the weight of old or unused memories over time, or removes them outright. Without it, stores grow forever and retrieval fills up with outdated, low-value entries.
Common approaches are an exponential recency decay in the ranking score, a time-to-live on entries, and pruning memories that are never retrieved. Some systems boost items each time they're accessed, similar to how human recall works.
Forgetting is a feature, not a bug - but important items need protection through high importance scores.
Take quiz
Doubling the embedding size monthly
Exponential recency weighting or a TTL
Re-tokenizing entries weekly
It speeds up model training
It increases the context window
It prevents stale, low-value entries from crowding retrieval
20. What is a memory embedding?
A memory embedding is a vector, usually hundreds or a few thousand numbers, produced by an embedding model to capture the meaning of a memory's text. Similar meanings land close together in vector space.
That is what makes "I'm vegetarian" retrievable when the user later asks "suggest a dinner recipe" - the two texts share no keywords but sit near each other.
Use the same embedding model for writing and querying. Mixing models gives meaningless distances.
Re-embedding becomes necessary if you ever switch models, so keep the original text next to the vector instead of storing vectors alone.
Take quiz
They share exact keywords
The database sorts alphabetically
Their embeddings sit close in vector space
The embedding model
The user's browser
The log level
21. What is the difference between MAG and RAG?
Both retrieve text into the prompt, but they retrieve different things and treat the store differently. RAG pulls from a mostly static knowledge corpus (docs, wikis, manuals). MAG pulls from a memory the system keeps writing to as it interacts.
| Aspect | RAG | MAG |
| Source | Pre-built document corpus | Interaction history and learned facts |
| Writes at runtime | Rare; offline indexing | Constant; part of the loop |
| Scope | Usually shared across users | Often per user, session or agent |
| Main challenge | Retrieval relevance | Write quality, updates, forgetting |
In practice they overlap: a MAG system often uses RAG-style retrieval machinery for reading, and many agents use both at once.
Take quiz
The store is continuously written to by the system itself
MAG never uses embeddings
RAG requires fine-tuning the model
Splitting PDFs into chunks
Deciding what to write, update and forget
Indexing a fixed wiki once
22. How does the retrieve-then-generate loop work in MAG?
Each turn follows the same cycle: retrieve, generate, write.
- The user message arrives and is used (sometimes rewritten) as a search query.
- The memory store returns the top-ranked entries.
- The app builds a prompt from system instructions, retrieved memories and recent turns.
- The model generates a reply.
- A writer step extracts anything worth keeping and updates the store.
sequenceDiagram participant U as User participant A as App participant M as Memory store participant L as LLM U->>A: message A->>M: search with query M-->>A: top memories A->>L: prompt plus memories L-->>A: reply A->>M: write or update memories A-->>U: reply
The write step often runs asynchronously so it doesn't add latency to the reply.
Take quiz
Write, delete, retrain
Retrieve, generate, write
Generate, retrain, retrieve
Because the model cannot write synchronously
To avoid using embeddings
So it does not delay the user's reply
23. Why is a bigger context window not a replacement for memory?
A long context only helps within a single call. Four things still break:
- Persistence - the window resets with each new session.
- Cost and latency - re-sending huge histories every turn is expensive and slow.
- Attention quality - models tend to use information in the middle of very long prompts less reliably (the "lost in the middle" effect).
- Noise - dumping everything in means irrelevant text competes with the useful parts.
Memory selects what deserves to be in the window. Bigger windows make that budget larger; they don't remove the need for selection.
A useful rule of thumb: use the window for the active task, and use memory for everything the task might need to look up.
Take quiz
Vanishing gradient
Catastrophic forgetting
Lost in the middle
Persists across sessions and selects what to include
Increases the model's parameter count
Removes the need for embeddings
24. How does the Generative Agents memory stream score memories?
In the Generative Agents paper (Park et al., 2023), every observation is saved to a natural-language memory stream. When the agent needs context, each memory gets a score from three components:
- Recency - exponential decay since the memory was last accessed.
- Importance - the LLM rates how significant the event is on a 1-10 scale.
- Relevance - embedding similarity to the current situation.
Each is normalized and summed, and the top-scoring memories go into the prompt.
score = a1*recency + a2*importance + a3*relevance top = sorted(memories, key=score, reverse=True)[:k]
The same paper adds reflection: periodically the agent synthesizes higher-level insights from recent memories and stores them back in the stream.
Take quiz
Recency, importance and relevance
Length, language and format
Cost, latency and throughput
The user clicks a button
The LLM rates it on a numeric scale
A hash function
25. How does MemGPT manage context like an operating system?
MemGPT splits memory into a small main context (what the model sees) and large external context (recall and archival storage), then lets the model manage movement between them through function calls.
The main context holds system instructions, a writable working-context block, and a FIFO queue of recent messages. When the queue nears its limit, the system signals memory pressure. The model then calls functions to save key facts to archival storage, search recall storage, or edit its own working context before old messages are evicted.
flowchart LR
A["New message"] --> B["Main context"]
B --> C{Near token limit?}
C -- No --> D["Generate reply"]
C -- Yes --> E["Model saves facts via function call"]
E --> F["Evict old messages to recall storage"]
F --> D
The takeaway is that the model itself decides what to page in and out, instead of fixed rules deciding for it.
Take quiz
A user-issued restart command
A memory-pressure signal as the token limit nears
A scheduled nightly cron job
The embedding model
The tokenizer
The model, through function calls
26. What is the difference between parametric and non-parametric memory?
Parametric memory is knowledge baked into model weights during training or fine-tuning. Non-parametric memory is knowledge kept outside the weights and looked up at inference time.
| Aspect | Parametric | Non-parametric |
| Location | Model weights | External store |
| Updating | Needs training or editing | Insert, update or delete a record |
| Deleting a fact | Hard to guarantee | Straightforward |
| Traceability | Opaque | Can cite the source entry |
| Read cost | Free at inference | Retrieval latency |
MAG is mainly non-parametric. That's why it suits fast-changing, personal or deletable information, while stable general knowledge stays in the weights.
A common split is to let weights carry language skills and broad world knowledge, while memory carries user-specific, time-sensitive or removable data. Model-editing techniques exist for weights, but they are still less predictable than deleting a record.
Take quiz
Parametric memory
Both are equally easy
Non-parametric memory
In the model weights
In a vector database
In the user's browser cookies
27. How does kNN-LM use an external datastore?
kNN-LM (Khandelwal et al., 2019) builds a datastore where each key is a hidden representation of a text prefix and each value is the token that followed it in the training data.
At inference, the model's current hidden state queries the datastore for its nearest neighbors. Their distances become a probability distribution over next tokens, which is interpolated with the normal language-model distribution:
p(next) = lam * p_knn(next) + (1 - lam) * p_lm(next)
It improved perplexity without retraining, especially for rare patterns and domain-specific text. Retrieval happens at every token, so it is heavier than prompt-level retrieval.
One practical drawback: for large corpora the datastore can hold billions of entries, so storage and search cost grow with the data. That makes it more of a research technique than a typical agent pattern.
Take quiz
The next token that followed that context
The full source document
The user's ID
Picks whichever is shorter
Interpolates the kNN and LM distributions
Averages the model weights
28. How do Memorizing Transformers differ from RAG?
RAG retrieves text and pastes it into the prompt, so the model reads it like any other input. Memorizing Transformers (Wu et al., 2022) retrieve at the attention level instead.
They cache past key-value pairs from earlier segments in an external memory and, in one chosen layer, do a kNN lookup for each query. The retrieved keys and values are attended to alongside local context, blended by a learned gate. The memory isn't trained by gradients, so it can be extended with new data.
| Aspect | RAG | Memorizing Transformers |
| Retrieved unit | Text chunks | Cached keys and values |
| Where it enters | Prompt | Attention layer |
| Needs architecture change | No | Yes |
Take quiz
Raw text chunks pasted into the prompt
Cached attention keys and values
Whole documents from a search engine
Standard RAG
Prompt caching only
Memorizing Transformers
29. How does Titans' neural long-term memory update at test time?
Titans (Google, 2024) adds a neural memory module, a small deep network whose weights act as the memory, that keeps learning while the model is running.
Each new token is treated as a key-value association, and the memory takes a gradient step to reduce its recall error on it. The size of that gradient is the surprise signal: unexpected inputs cause bigger updates. A momentum term carries surprise across nearby tokens, and an adaptive forgetting gate decays old content so capacity isn't wasted.
The paper proposes three ways to combine it with attention: Memory as Context (MAC), Memory as Gate (MAG) and Memory as Layer (MAL).
Note the naming clash. In Titans, "MAG" means Memory as Gate; in this topic it means the broader Memory-Augmented Generation pattern.
Take quiz
User thumbs-up counts
Token length
Surprise, measured by the gradient
Memory as Gate
Memory as Graph
Memory as Generation
30. When should you summarize versus store raw messages?
Summarize when you need the gist and tokens are tight. Store raw when exact wording matters.
- Summarize: long chit-chat, brainstorming, status updates, older context that just needs orienting.
- Keep raw: numbers, code, names, legal or medical statements, commitments, and anything a user might quote back.
A solid hybrid is to keep recent turns verbatim, summarize older ones into the prompt, and archive the raw text in a searchable store. That way the summary keeps the prompt small, and retrieval can still recover exact details when a question needs them.
A quick test: if a wrong digit or reworded clause would cause a wrong answer or real harm, keep the original text.
Take quiz
Exact figures, code and commitments
Greetings and small talk
Repeated acknowledgements
Delete raw text immediately
Summarize in the prompt, archive raw text for retrieval
Summarize only the first message
31. How do you decide what is worth writing to memory?
Not everything said is worth keeping. A practical filter asks whether the information is durable, reusable and specific.
- Durable - will it still be true next week? "I'm in Berlin this month" may not be.
- Reusable - will it change a future answer? A preferred language does; a one-off typo fix doesn't.
- Specific - is it concrete enough to act on?
- Safe - is it free of secrets and sensitive data you shouldn't hold?
Teams implement this with an extraction prompt that returns candidate facts with an importance score, then drop anything below a threshold or already known. Explicit user instructions like "remember that..." should always pass.
Take quiz
"Thanks, that helps"
"I always want answers in metric units"
"Hold on, one second"
Any message under ten words
Any message with an emoji
An explicit 'remember this' from the user
32. How does an LLM-based memory extractor work?
After a turn or session, the conversation is sent to an LLM with instructions to output structured candidate memories, usually as JSON, instead of prose.
[{"fact": "Prefers TypeScript over JavaScript", "type": "semantic", "importance": 7, "ttl_days": null}]
The system then runs each candidate through checks: search for similar existing memories, decide add/update/ignore, and apply policy filters for sensitive data. Only surviving entries get embedded and stored.
Prompt wording matters a lot. Tell it to extract only stated facts, not guesses, and to return an empty list when nothing is worth saving.
Measure extractor precision and recall on a small set of conversations with known correct facts, since this step silently caps the quality of everything downstream.
Take quiz
Binary model checkpoints
Image thumbnails
Structured JSON candidates
Extract only facts the user actually stated
Infer as many traits as possible
Always return at least five items
33. What happens when a new memory contradicts an old one?
If you simply append, retrieval may return both and the model gets confused: "lives in Austin" and "moved to Denver". Conflict handling has to be a deliberate step.
The usual flow is: search for similar memories, let a model or rule judge whether the new fact replaces, refines or coexists with the old one, then act.
- Replace - overwrite the old value when it is simply outdated.
- Invalidate - mark the old one expired with an end date, keeping history.
- Coexist - keep both if they aren't really in conflict (a user can like tea and coffee).
- Ask - if confidence is low, confirm with the user.
Temporal fields like valid-from and valid-to make this much easier to reason about.
Take quiz
Invalidate it with an end date and keep history
Delete the entire user profile
Randomly pick one
Both mention the same city
They aren't truly in conflict, like liking tea and coffee
One is older than the other
34. How do you handle memory consolidation?
Consolidation turns a growing pile of fine-grained memories into a smaller, cleaner set, similar to how sleep is thought to organize human memory.
A background job typically runs periodically and does four things:
- Deduplicate near-identical entries using embedding similarity.
- Merge related episodes into one semantic fact.
- Generate reflections - higher-level insights across many events, as in Generative Agents.
- Prune low-value or expired entries.
Run it offline so it doesn't hurt latency, keep the originals archived for a while, and log what was merged so mistakes can be reversed.
A common failure is over-merging, where two different facts about similar entities collapse into one. Sample merged entries regularly and check that each source fact can still be recovered from the result.
Take quiz
Inside every user request
In a background job, off the request path
Inside the tokenizer
To increase the embedding size
To speed up inference
So wrong merges can be reversed
35. When would you choose graph memory over vector memory?
Choose a graph when the questions depend on relationships and multi-hop reasoning, and vectors when they depend on fuzzy semantic similarity.
| Question type | Better fit |
| "What did the user say about deployment?" | Vector |
| "Which of my teammates work on services that use Redis?" | Graph |
| "Anything similar to this error message?" | Vector |
| "Who reports to the manager of Priya?" | Graph |
Graphs also give cleaner updates: changing an employer is one edge edit, not hunting through paraphrased chunks. The costs are heavier extraction at write time and schema upkeep.
Many teams combine both: a vector index for recall and a graph for structured entity facts.
If you're unsure, begin with vectors plus structured metadata. Move to a graph once you see recurring multi-hop failures, because that's a clear sign relationships are doing real work.
Take quiz
"Find text similar to this error"
"Summarize the last chat"
"Which teammates work on services that use Redis?"
Heavier entity extraction at write time
It cannot store relationships
It needs no schema thinking at all
36. How does temporal knowledge graph memory handle changing facts?
Temporal graphs, as in Zep's Graphiti, attach time information to facts instead of treating the graph as a snapshot. Edges carry validity timestamps such as when a fact became true and when it stopped being true.
When a new fact contradicts an existing edge, the old edge is invalidated (given an end time), not deleted. The new edge starts from the new date.
This lets the system answer both "where does the user live now?" and "where did they live in March?", and it avoids returning outdated facts as if they were current. The price is added complexity in extraction, since the system must infer dates from natural language.
Retrieval then filters by time: current-state questions use only edges with no end date, while historical questions use edges that were valid at the time being asked about.
Take quiz
It is given an end time, not deleted
It is rewritten as an embedding
It is moved to the model weights
"What is 2 plus 2?"
"Where did the user live in March?"
"List Python keywords"
37. How do you evaluate a MAG system?
Evaluate the memory and the end answers separately, otherwise you can't tell whether failures came from retrieval or generation.
- Retrieval metrics - recall@k and precision@k against a labeled set of "which memory should have been fetched".
- Answer quality - accuracy on questions that need prior context, judged by humans or an LLM judge.
- Benchmarks - LoCoMo tests QA over very long multi-session conversations; LongMemEval covers information extraction, multi-session reasoning, temporal reasoning, knowledge updates and abstention.
- Operational - latency, token cost per turn, memory growth.
Don't skip abstention: a good memory system says "I don't know" when nothing relevant was stored, instead of inventing.
Build a small in-house test set from real conversations too. Public benchmarks measure general memory skills, but only your own data reveals domain-specific failures such as product names or internal jargon.
Take quiz
To avoid running benchmarks
To tell whether failures come from retrieval or generation
To skip human review
Compression
Tokenization
Abstention
38. Why can poorly retrieved memories hurt answer quality?
Retrieved text is treated by the model as trusted context. If the wrong memory shows up, the model often uses it anyway, and the answer gets worse than with no memory at all.
Typical failure modes:
- Irrelevant but similar entries, such as another project's config, steer the answer off course.
- Stale facts are presented as current.
- Too many entries bury the useful one, and long prompts dilute attention.
- Wrong user data causes leaks.
Mitigate with similarity thresholds, reranking, small k, recency and importance weighting, and a prompt that tells the model memory may be incomplete or outdated.
Log every injected memory with its score so you can inspect bad answers afterward, and consider having the model cite which memory it relied on.
Take quiz
Retrieval always lowers model temperature
The embeddings overwrite the weights
The model tends to trust retrieved context as true
A similarity threshold plus reranking
Increasing k to 100
Removing timestamps
39. How can you optimize memory retrieval latency?
Start by finding where time goes: embedding the query, the search itself, reranking, or network hops. Then fix the biggest piece.
- Approximate nearest neighbor indexes such as HNSW trade a little recall for much faster search.
- Metadata pre-filtering by user or type shrinks the search space.
- Cache query embeddings and frequent results.
- Run retrieval in parallel with other prep work, such as tool setup.
- Limit rerank candidates - rerank 20, not 200, or use a lighter reranker.
- Move writes off the hot path so they don't block the reply.
Measure p95 latency, not just the average, because slow tail requests are what users notice.
Don't forget embedding cost: a small, fast embedding model with slightly lower recall is often worth it when retrieval sits on every user turn.
Take quiz
Approximate nearest neighbor such as HNSW
Exact brute-force scan
Bubble sort
The mean is always wrong by definition
Slow tail requests drive the user experience
p95 reduces token cost
40. How do you troubleshoot an agent that forgets user preferences?
Work through the pipeline in order, because "forgot" can mean four different failures.
- Was it written? Check the store. If missing, the extractor or write policy skipped it.
- Was it stored well? Vague text like "likes it" can't be matched later; look for lost context.
- Was it retrieved? Run the query by hand and check rank, filters (wrong user id?) and thresholds.
- Was it used? If it was in the prompt but ignored, the issue is prompt placement or conflicting instructions.
Logging the retrieved set per turn makes this a five-minute check instead of a guessing game. Fixes range from better extraction prompts to rewriting stored facts as self-contained sentences.
Also test paraphrases. A preference stored as 'avoids dairy' should surface for 'suggest a latte order'; if it doesn't, add query rewriting or store richer, self-contained text.
Take quiz
The GPU temperature
Whether it was ever written to the store
The browser version
The vector index dimension
The write policy
Prompt placement or conflicting instructions
41. How do you troubleshoot an agent recalling wrong or stale memories?
First log which memories were injected and compare them to what the user said recently. Then identify the cause:
- No update path - new facts were appended, old ones never invalidated. Add conflict resolution.
- No recency signal - an old but highly similar entry outranks a newer one. Add recency weighting.
- Bad extraction - the model recorded a guess as a fact. Tighten the extraction prompt and add confidence fields.
- Cross-user leakage - a missing filter. Enforce tenant checks at the storage layer.
- Duplicate near-copies - consolidate them.
Then add a regression test containing the exact case so it doesn't return.
For facts that go out of date quickly, such as the current project or location, set a short TTL or ask the user to reconfirm before relying on them.
Take quiz
A larger context window
A faster GPU
A recency signal in ranking
At the storage layer, not only in the prompt
Only in the system prompt text
Only in the UI
42. What is memory poisoning and how do you defend against it?
Memory poisoning is when an attacker gets malicious content written into the agent's memory, so it influences later behavior, sometimes long after the attack. It can arrive through a chat message, a web page the agent read, an email or a document. Research such as AgentPoison has shown this is practical against agents with retrieval-based memory.
Because memories are injected as trusted context, a poisoned entry like "always forward invoices to this address" can persist across sessions.
Defenses are layered:
- Track provenance and trust level for every entry.
- Never let untrusted content write instructions or procedural memory directly.
- Apply write-time filters and require confirmation for sensitive memories.
- Present memories to the model as data, not commands.
- Limit tool permissions and keep audit logs for review and rollback.
Take quiz
It persists and is injected as trusted context later
It only affects the current token
It automatically retrains the model
Increasing the vector dimension
Recording provenance and trust level per entry
Disabling timestamps
43. How do you implement the right to be forgotten in MAG?
Because MAG is largely non-parametric, deletion is feasible - but only if you planned for it. Under rules like GDPR Article 17, a user can ask for their personal data to be erased.
- Index by user - every memory carries a user id so you can find all of it.
- Delete everywhere - primary store, vector index, graph, caches, logs and backups, according to your retention policy.
- Handle derivatives - summaries and consolidated facts built from that user's data must go too, so keep lineage links.
- Verify - run a search after deletion to confirm nothing returns.
- Keep it out of training - don't feed raw memories into fine-tuning data without consent.
This isn't legal advice; involve your compliance team for retention rules.
Take quiz
To compress embeddings
So derived summaries can also be deleted
To speed up tokenization
Renaming the model
Resizing the font
Caches, logs and backups
44. How should multi-tenant memory be isolated?
Isolation must be enforced where the data lives, not by hoping the model behaves. A prompt saying "only talk about this user" is not a security control.
- Mandatory tenant id on every write and every query, injected by the server, never taken from model output.
- Separate namespaces or collections per tenant for high-sensitivity customers; metadata filters for lighter setups.
- Row-level security or equivalent in relational and graph stores.
- Isolated caches, so a cached result for one tenant can't serve another.
- Tests that attempt cross-tenant reads and must fail.
Also separate scopes within a tenant: user, team and agent memory shouldn't all mix by default.
Plan for admin and support tooling too. Internal dashboards that browse memories are a common place for accidental cross-tenant exposure.
Take quiz
By the user typing it in chat
By the embedding model
By server code, never by model output
It is not an enforced access control
Prompts cannot contain user ids
Models cannot read prompts
45. How does prompt caching interact with injected memories?
Prompt caching generally works on a stable prefix: if the beginning of the prompt is identical across requests, its processing can be reused. Change something early and everything after it misses the cache.
Retrieved memories change every turn, so where you put them matters.
- Keep the system prompt, tool definitions and static instructions first so they stay cacheable.
- Place per-turn retrieved memories after that stable block.
- Keep slowly changing items, such as a user profile block, ahead of fast-changing ones.
- Avoid inserting timestamps or random IDs near the top.
flowchart LR A["System prompt and tools - cached"] --> B["User profile block - changes rarely"] B --> C["Retrieved memories - change each turn"] C --> D["Recent messages and new input"]
Check your provider's caching rules and minimum length, as details vary.
Take quiz
After the stable system prompt and tools
At the very top of the prompt
Inside the tool schema
A short user message at the end
A timestamp or random ID near the top
Using lowercase letters
46. How do you budget tokens for retrieved memories?
Treat the context window as a budget split into fixed and flexible parts, and cap memory so it never crowds out the user's actual request.
| Slice | Typical handling |
| System prompt and tools | Fixed, kept small |
| Profile / pinned facts | Small fixed block |
| Retrieved memories | Capped, e.g. top 5-10 or a token ceiling |
| Recent turns | Sliding window |
| Output reserve | Always left free for the reply |
Rank first, then fill until the cap. Drop low-score entries instead of truncating mid-sentence. Shorter, self-contained memories pack better, so rewrite them at write time. Review average injected tokens per turn - if it creeps up, tighten k or thresholds.
Dynamic budgets work well: give memory more room on simple chat turns and less when the task already carries large documents or tool output.
Take quiz
Space for old unrelated chats
Room for the model's output
Extra duplicated memories
Cutting every memory in half
Padding with filler
Dropping lower-ranked entries entirely
47. How do hybrid search and reranking improve memory recall?
Vector search finds meaning but can miss exact tokens; keyword search (BM25) finds exact tokens but misses paraphrases. Hybrid search runs both and merges the lists, often with reciprocal rank fusion.
That matters for memory, where users mention IDs, error codes, names and product versions that embeddings blur together.
A reranker then rescores the top candidates, typically 20-50, using a cross-encoder or an LLM that reads the query and each memory together. It's slower but much more precise than embedding distance.
If latency allows, retrieve more candidates than you need, rerank, then keep only the top few. Reranking is where most of the precision gain comes from.
flowchart LR Q[Query] --> V["Vector search"] Q --> K["Keyword search"] V --> F["Fuse ranked lists"] K --> F F --> R["Rerank top candidates"] R --> T["Top k memories to prompt"]
Take quiz
To shrink the embedding model
To avoid storing text
To catch exact IDs, names and error codes
Rescores top candidates by reading query and memory together
Generates new embeddings for the whole store
Deletes low-score memories permanently
48. Explain the lifecycle of a memory entry in MAG?
A memory isn't static; it moves through stages from creation to retirement.
- Capture - raw interaction is observed.
- Extract and filter - candidate facts are pulled out and checked against the write policy.
- Dedupe and resolve - compared with existing entries; added, merged or used to update an old one.
- Store - embedded and saved with metadata.
- Retrieve and use - ranked, injected, and its access time refreshed.
- Consolidate - merged into higher-level facts in background jobs.
- Expire or delete - removed by decay, TTL, supersession or user request.
flowchart TD A[Capture] --> B["Extract and filter"] B --> C["Dedupe and resolve conflicts"] C --> D["Store with metadata"] D --> E["Retrieve and inject"] E --> F[Consolidate] F --> G["Expire or delete"] E --> D
Take quiz
Dedupe and conflict resolution
Expiry
Consolidation
Its owner is changed
Its last-accessed time is refreshed
It is deleted
49. How would you design memory for a long-running support agent?
Start from what the agent must remember and how long, then pick stores to match.
| Need | Memory | Store |
| Current ticket thread | Working memory | Context window, recent turns |
| Customer plan, product, stack | Semantic profile | Key-value or relational row |
| Past tickets and resolutions | Episodic | Vector index plus keyword filter |
| Known fixes and escalation steps | Procedural | Versioned runbooks, retrieved on demand |
Key design decisions:
- Scope every read and write by customer id; support data is sensitive.
- Write a short summary and resolution at ticket close, and keep raw text archived.
- Invalidate old facts when the customer upgrades or changes setup.
- Escalate to a human instead of answering when retrieval confidence is low.
- Evaluate with replayed historical tickets and track repeat-contact rate.
Finally, give users and staff a way to correct memory, such as a visible profile page or a 'that's wrong' command. It fixes errors faster than any automated cleanup.
Take quiz
Only in embeddings of chat logs
In a structured profile row
Inside the system prompt forever
Guess confidently
Delete the customer's history
Escalate to a human or abstain
50. Explain the internal working of a production MAG architecture end-to-end?
A production setup separates the read path (fast, on the request) from the write path (can be slower, asynchronous), with governance cutting across both.
Read path: authenticate and resolve tenant, rewrite the query if needed, run hybrid retrieval with tenant filters, rerank, apply recency and importance weighting, trim to the token budget, assemble the prompt with stable content first, and call the model.
Write path: after the response, a queue worker runs the extractor, filters for sensitive data, checks similar entries, and then adds, updates or invalidates. Embeddings are computed and indexes updated.
Background: consolidation, decay, reindexing, and metrics collection.
Governance: provenance, audit logs, deletion APIs, access control and evaluation dashboards.
flowchart TD U["User request"] --> A["Auth and tenant resolve"] A --> R["Hybrid retrieve and rerank"] R --> P["Budget and build prompt"] P --> L[LLM] L --> O[Response] L --> Q["Write queue"] Q --> X["Extract and filter"] X --> C["Resolve and upsert"] C --> S[(Memory stores)] S --> R S --> B["Consolidate and decay jobs"]
The main design principle: reads must be cheap and safe, writes must be careful, and every memory must be traceable and deletable.