Prev Next

AI / AI agent memory Interview questions

Last updated

1. What is AI agent memory? 2. What is the purpose of memory in an AI agent? 3. What is short-term memory in an AI agent? 4. What is long-term memory in an AI agent? 5. What is working memory in AI agents? 6. What is episodic memory in AI agents? 7. What is semantic memory in AI agents? 8. What is procedural memory in AI agents? 9. What is a context window? 10. What are the types of AI agent memory? 11. What is a vector database in agent memory? 12. What are embeddings in agent memory? 13. What is conversation buffer memory? 14. What is summary memory? 15. What is a checkpointer in agent frameworks? 16. What is entity memory? 17. What is knowledge graph memory? 18. Define memory retrieval in AI agents? 19. What is a thread ID or session ID in agent memory? 20. Define memory consolidation in AI agents? 21. What is forgetting in AI agent memory? 22. What is MemGPT? 23. What is the memory tool in the Claude API? 24. What is memory poisoning in AI agents? 25. List common frameworks and tools used for AI agent memory? 26. What is the difference between short-term and long-term memory in agents? 27. What is the difference between RAG and agent memory? 28. How does an agent decide what to store in memory? 29. How does memory retrieval work in an agent loop? 30. Explain the lifecycle of a memory item in an AI agent? 31. Why does a bigger context window not replace agent memory? 32. How does the Generative Agents memory retrieval score work? 33. How does MemGPT manage memory like an operating system? 34. When should you use summary memory instead of a sliding window? 35. When would you choose a knowledge graph over a vector store for memory? 36. How do you handle conflicting or outdated memories in an agent? 37. How do you troubleshoot an agent that keeps forgetting facts? 38. How do you troubleshoot an agent recalling irrelevant memories? 39. Why can persistent memory be a security risk for AI agents? 40. How do you isolate agent memory across users in a multi-tenant system? 41. How can you optimize memory retrieval latency and cost? 42. How do you evaluate the quality of agent memory? 43. How do multiple agents share memory safely? 44. What happens when an agent's context window overflows? 45. Explain reflection in agent memory? 46. Why use hybrid search for agent memory? 47. What is the difference between hot-path and background memory writes? 48. How do you handle PII and deletion requests in agent memory? 49. What is the difference between context compaction and long-term memory? 50. Which is better for agent memory: file-based or vector-based, and why?

1. What is AI agent memory?

AI agent memory is the mechanism that lets an agent keep, retrieve, and reuse information beyond a single model call. A language model is stateless, so anything it should "remember" has to be stored somewhere and put back into the prompt when needed.

That storage can be as simple as the running chat transcript or as involved as a vector database, a knowledge graph, or a set of files the agent edits itself.

Good memory is what turns a one-off chatbot into an agent that tracks goals, learns user preferences, and avoids repeating mistakes across steps and sessions.

Take quiz
Why does an LLM-based agent need an explicit memory layer?
The model itself is stateless between calls
The model weights update after every message
The API stores every past call automatically
Memory is only needed for image inputs
Memory in an agent can be implemented as:
Only a relational database
A transcript, vector store, graph, or files
Only the model's weights
Only GPU cache

2. What is the purpose of memory in an AI agent?

Memory gives an agent continuity. Without it, every request starts from zero and the agent cannot follow a multi-step task, remember what the user already said, or learn from earlier outcomes.

  1. Keep task state across the steps of a single run.
  2. Carry user facts and preferences across sessions.
  3. Store lessons and past results so the agent does not repeat failed attempts.
  4. Hold knowledge that is too large to fit in the context window.
Take quiz
Which problem does agent memory mainly solve?
Making the tokenizer faster
Reducing the model's parameter count
Losing state between steps and sessions
Encrypting API keys
Carrying a user's preferred language into next week's chat needs:
Only a larger temperature
A shorter system prompt
Nothing, the model remembers by default
Long-term persistent memory

3. What is short-term memory in an AI agent?

Short-term memory holds information relevant to the current conversation or task run. In most agents it is just the message history plus tool results that get sent back to the model on every turn.

It lives inside the context window, so it is fast and always visible to the model, but it is limited in size and usually disappears when the session ends unless you checkpoint it.

Common ways to keep it under control are a sliding window of recent messages, summarising older turns, or trimming bulky tool outputs.

Take quiz
Short-term memory in an agent usually lives in:
The context window of the current session
A permanent external knowledge graph
The model's training data
The user's browser cookies only
A common way to keep short-term memory from growing too big is:
Increasing the number of tool calls
Trimming or summarising older turns
Disabling the system prompt
Duplicating every message

4. What is long-term memory in an AI agent?

Long-term memory is information stored outside the context window so it survives across sessions. The agent writes to it deliberately and reads from it by search or lookup when something relevant comes up.

Typical backends are vector databases, key-value stores, relational tables, graphs, or plain files. Only the retrieved pieces are injected into the prompt, which keeps token use manageable.

It is usually split into episodic, semantic, and procedural memory, borrowing terms from cognitive science.

Take quiz
Long-term memory differs from short-term memory because it:
Is erased after each model call
Is stored only in the system prompt
Persists outside the context window across sessions
Cannot be searched
Which is NOT a typical long-term memory backend?
A vector database
A key-value store
Plain files
The model's attention scores for one token

5. What is working memory in AI agents?

Working memory is the small scratchpad an agent uses while it is actively solving a task: the current goal, the plan, intermediate results, and the few facts it pulled from long-term memory.

In practice it is whatever sits in the prompt right now. Some frameworks make it explicit, for example MemGPT-style "core memory" blocks or a structured state object in LangGraph that every node can read and update.

It stays small on purpose. Anything that is no longer needed for the next step should be written to long-term storage or dropped, otherwise the scratchpad turns into clutter that distracts the model.

Take quiz
Working memory in an agent is best described as:
The scratchpad of goal, plan and facts currently in the prompt
The archive of all past users
The vector index on disk
The training dataset
In LangGraph, a structured state object passed between nodes acts like:
A model fine-tuning job
Working memory for the run
A rate limiter
A tokenizer

6. What is episodic memory in AI agents?

Episodic memory stores specific past events, such as "last Tuesday the user asked me to reschedule a flight and the airline API timed out." Each entry is tied to a time, a context, and an outcome.

Agents use it to recall how a similar situation went before, which makes it handy for few-shot examples and for avoiding repeated mistakes. Entries are often stored as logs or short summaries with timestamps and retrieved by similarity.

Take quiz
Which example is episodic memory?
The rule that Paris is in France
A reusable system prompt template
A log of a specific past booking attempt and its result
The tokenizer vocabulary
Episodic memory entries typically carry:
Only model weights
Only a hash of the user ID
No metadata
Time, context and outcome of an event

7. What is semantic memory in AI agents?

Semantic memory holds general facts and knowledge that are not tied to one event: "the user is vegetarian," "the company fiscal year starts in April," "the API rate limit is 100 requests per minute."

It is usually stored as short facts or profile fields, in a vector store, a document store, or a knowledge graph, and updated as new information replaces old. Mem0 and LangMem both focus heavily on extracting this kind of fact from conversations.

Take quiz
"The user is allergic to peanuts" is an example of:
Semantic memory
Procedural memory
Working memory only
A checkpoint
Semantic memory facts are usually:
Never changed once written
Updated when newer information replaces old facts
Stored only in the model weights
Always timestamped by the GPU

8. What is procedural memory in AI agents?

Procedural memory captures how to do things: instructions, skills, and learned workflows. For an agent this is most often the system prompt, tool descriptions, and any rules the agent refines over time.

Some designs let the agent rewrite its own instructions after feedback, so a lesson like "always confirm the date format before calling the calendar API" becomes a permanent behavior. Anthropic's skills and similar instruction files fit this idea too.

Take quiz
Procedural memory in agents mostly consists of:
Raw user chat logs
A list of past dates
Instructions, skills and learned workflows
GPU temperature logs
An agent that edits its own prompt after feedback is updating:
Episodic logs only
The tokenizer
The embedding model
Procedural memory

9. What is a context window?

The context window is the maximum amount of text, measured in tokens, that a model can read and produce in one request. System prompt, history, retrieved memories, tool results, and the new answer all share it.

Larger windows help, but they do not remove the need for memory. Cost and latency grow with input size, and models can miss details buried in the middle of a very long prompt.

As a rule of thumb, reserve room for the answer up front. If the prompt already fills most of the window, the reply can be cut off mid-sentence.

Take quiz
The context window limit applies to:
Input and output tokens combined in a request
Only the user's message
Only the system prompt
Only stored files
A larger context window:
Makes retrieval useless
Does not eliminate the cost and latency of long prompts
Guarantees perfect recall
Removes token pricing

10. What are the types of AI agent memory?

Agent memory is usually grouped by lifespan and by content.

Type What it holds Typical storage
Short-term / working Current task, recent messages Context window, graph state
Episodic Past events and outcomes Logs, timestamped summaries
Semantic Facts and preferences Vector store, graph, profile JSON
Procedural Rules, skills, workflows System prompt, skill files

Some teams add a fifth bucket, shared memory, for information several agents read and write together.

In interviews, mention that the boundaries are fuzzy: one stored item, like a user's diet, can be semantic fact today and feed a procedural rule tomorrow.

Take quiz
Which type of memory stores rules and workflows?
Episodic
Semantic
Procedural
Sensory
Facts and user preferences are best classified as:
Procedural memory
Working memory
Cache memory
Semantic memory

11. What is a vector database in agent memory?

A vector database stores embeddings, which are numeric representations of text, and finds the closest ones to a query using similarity search. Agents use it to pull back memories that are related in meaning even when the exact words differ.

Common choices include pgvector, Pinecone, Qdrant, Weaviate, and Chroma. The usual flow is: embed the memory, store it with metadata such as user ID and timestamp, then embed the query and fetch the top-k matches.

Take quiz
A vector database retrieves memories by:
Similarity between embeddings
Alphabetical order only
Random sampling
Exact primary-key joins only
Which metadata is useful beside each stored vector?
GPU model
User ID and timestamp
Browser theme
Model temperature

12. What are embeddings in agent memory?

Embeddings are fixed-length vectors produced by an embedding model so that texts with similar meaning land close together in vector space.

In an agent, each memory is embedded when written and the current query is embedded when reading. Cosine similarity or dot product then ranks the candidates.

One practical rule: use the same embedding model for writing and querying. If you switch models you must re-embed the whole store.

Dimension matters too: common models output vectors with 768 to 3072 numbers, and the index must be created with that exact size.

Take quiz
What must stay consistent between writing and querying memories?
The user's screen size
The log file name
The embedding model
The HTTP method
Embeddings place similar meanings:
At random positions
In separate databases
Only in the same language
Close together in vector space

13. What is conversation buffer memory?

Conversation buffer memory keeps the raw message history and sends all or part of it back to the model each turn. It is the simplest form of memory and the default in many tutorials.

Variants include a window buffer (last N messages) and a token buffer (as many recent messages as fit a token budget). It is lossless while it fits, but cost grows with each turn and old details eventually get cut.

Take quiz
A window buffer keeps:
The last N messages
Only the first message
Only tool errors
Summaries only
The main drawback of an unbounded conversation buffer is:
It cannot store text
Token cost grows every turn
It requires a graph database
It deletes the latest message

14. What is summary memory?

Summary memory compresses older conversation into a short running summary produced by an LLM, then keeps only the latest turns verbatim next to it.

It saves tokens and extends how long a session can run. The trade-off is lossy compression: names, numbers, or exact wording can be dropped, and summarisation errors can compound if the summary is re-summarised repeatedly.

A sensible safeguard is to keep names, dates, and numbers in a separate structured list, so they never depend on the summariser getting them right.

Take quiz
Summary memory trades:
Speed for hardware cost
Security for accuracy
Exact detail for lower token usage
Storage for GPU memory
A risk of repeatedly re-summarising is:
The context window growing
Embeddings becoming invalid
Tools being disabled
Details and errors compounding

15. What is a checkpointer in agent frameworks?

A checkpointer saves a snapshot of the agent's state after each step, keyed by a thread ID, so the run can be resumed, replayed, or inspected later. LangGraph is the best-known example, with in-memory, SQLite, and Postgres implementations.

It provides thread-level short-term memory and enables human-in-the-loop pauses and time travel debugging. It does not share information across threads; for that you need a separate store.

graph = builder.compile(checkpointer=PostgresSaver(conn))
graph.invoke(inputs, {"configurable": {"thread_id": "user-42-chat-1"}})

Take quiz
A checkpointer is keyed by:
A thread ID
The model name
The embedding dimension
The API key
A checkpointer alone does NOT provide:
Resuming a paused run
Memory shared across different threads
Replaying past steps
Per-thread state snapshots

16. What is entity memory?

Entity memory tracks named things the conversation mentions, such as people, products, projects, or accounts, along with what is known about each.

After every turn the agent extracts entities and updates a small record, for example Acme Corp: customer since 2021, prefers email. When the entity comes up again, only its record is injected, which is cheaper and more precise than replaying the whole history.

The main risk is wrong merges, for example treating two different people named Sam as one record, so good entity memory needs a stable ID per entity.

Take quiz
Entity memory stores:
Raw GPU metrics
Only the last user message
Facts about named people, products or accounts
Tokenizer merges
Why is entity memory efficient?
It disables retrieval
It doubles the context window
It removes the system prompt
Only the relevant entity record is injected

17. What is knowledge graph memory?

Knowledge graph memory stores facts as nodes (entities) and edges (relationships), for example (Priya) -[works_at]-> (Acme). The agent queries it by traversing relationships rather than only by text similarity.

It shines for multi-hop questions such as "who manages the person who approved this invoice?" Tools like Zep's Graphiti and Neo4j-backed Mem0 setups build and update these graphs from conversations, often with timestamps so facts can expire.

The cost is upfront effort: you need an extraction step to turn text into entities and relations, plus rules for merging duplicates such as "Bob" and "Robert."

Take quiz
In a knowledge graph memory, relationships are stored as:
Edges between entity nodes
Rows of raw embeddings only
Cached HTTP responses
Prompt templates
Graph memory is especially good for:
Compressing images
Multi-hop relationship questions
Reducing tokenizer size
Streaming audio

18. Define memory retrieval in AI agents?

Memory retrieval is the step where the agent decides which stored memories to bring back into the prompt for the current turn. It takes the user's message or the agent's current goal as a query and returns the most useful items.

Ranking can combine semantic similarity, keyword match, recency, importance, and metadata filters such as user ID. Retrieving too little causes forgetting; retrieving too much wastes tokens and distracts the model.

In short, retrieval quality sets the ceiling for memory quality, since a perfect store is useless if the right item never reaches the prompt.

Take quiz
Memory retrieval decides:
Which GPU runs the model
How the model is trained
Which stored items go into the prompt now
Which language the user speaks
Retrieving far too many memories mainly causes:
Faster inference
Better security
Smaller context
Wasted tokens and distraction

19. What is a thread ID or session ID in agent memory?

A thread ID (or session ID) labels one conversation so its history and state can be saved and loaded again. Everything in short-term memory is scoped to it.

It is different from a user ID, which groups memories across many threads. A good design uses both: the thread ID for conversation state, and the user ID or a namespace for long-term facts that should follow the person everywhere.

Reusing a thread ID resumes that conversation exactly where it stopped, while a fresh ID starts with a clean slate.

Take quiz
A thread ID scopes:
One conversation's state and history
All users' long-term facts
The embedding model
The model's weights
Facts that should follow a user across chats are best keyed by:
Thread ID only
User ID or namespace
Timestamp only
Token count

20. Define memory consolidation in AI agents?

Memory consolidation is the process of turning raw, noisy interaction logs into cleaner long-term memories. Think of it as the agent "sleeping on it."

A background job typically merges duplicates, resolves contradictions, summarises episodes into lessons, and promotes important facts into a profile. It is often scheduled between sessions so the user does not wait for it.

The result is a smaller, more accurate store, which also makes later retrieval cheaper and less noisy.

Take quiz
Memory consolidation typically does what?
Deletes the model
Increases temperature
Merges and cleans raw logs into durable memories
Disables embeddings
When is consolidation commonly run?
Only during token generation
Only at model training time
Never
In the background between sessions

21. What is forgetting in AI agent memory?

Forgetting is the deliberate removal or down-weighting of memories that are stale, low value, or wrong. It keeps retrieval sharp and storage bounded.

Common policies are time-to-live (TTL) expiry, decay of importance scores over time, capacity limits that evict the least useful items, and explicit user requests like "forget my address." Without any forgetting, stores fill with outdated and contradictory facts.

Forgetting also supports privacy, since data that is expired on schedule cannot leak or be misused later.

Take quiz
Which is a common forgetting policy?
TTL expiry
Doubling every entry
Re-embedding hourly
Raising the max tokens
Skipping forgetting entirely tends to cause:
Lower storage use
Stale and contradictory memories piling up
Perfect accuracy
Faster training

22. What is MemGPT?

MemGPT is a 2023 research approach, now continued as the open-source Letta framework, that treats an LLM's context like an operating system treats RAM. The model gets tools to move information between a small in-context area and a larger external store.

It has core memory blocks always in the prompt, recall memory for searchable conversation history, and archival memory for long-term documents. The agent itself decides when to save, search, or edit, using function calls.

Take quiz
MemGPT draws its idea from:
Image compression
Blockchain consensus
Operating system memory management
Database sharding only
In MemGPT, core memory is:
Stored only on disk
Deleted every turn
Used only for images
Always kept inside the prompt

23. What is the memory tool in the Claude API?

The memory tool lets Claude read, create, update, and delete files in a /memories directory so it can keep information between conversations. Claude decides when to use it, typically checking the directory at the start of a task.

It is client-side: Claude sends the tool calls and your application executes them against storage you control, such as local disk or a database. That means you own persistence, access control, and retention.

Take quiz
Where does the memory tool's data actually live?
In storage your application controls
Inside Claude's weights
On Anthropic's public CDN
In the user's browser history
Claude accesses memory tool files through:
Direct SQL queries to the model
A /memories directory via tool calls
The tokenizer
Email

24. What is memory poisoning in AI agents?

Memory poisoning is an attack where malicious or false content gets written into an agent's long-term memory and later influences its behavior. A web page or email containing hidden instructions can trick the agent into saving them as a "fact."

Because memories persist, the attack can outlive the original session and hit other tasks, or even other users if memory is shared. Defenses include validating what gets written, tagging memory by source and trust level, and letting users review stored memories.

Take quiz
Memory poisoning is dangerous mainly because:
It speeds up the model
It deletes the GPU driver
Malicious content persists and affects later sessions
It only affects logging
A sensible defense is to:
Trust every web page equally
Store everything with no checks
Disable the system prompt
Track the source and trust level of each memory

25. List common frameworks and tools used for AI agent memory?

Several open-source and managed options exist, and many agents combine more than one.

Tool Strength
LangGraph (checkpointers + Store) Thread state plus cross-thread long-term store
LangMem Memory extraction and prompt optimisation on top of LangGraph
Mem0 Fact extraction, user-scoped memory layer
Letta (MemGPT) Self-editing core, recall and archival memory
Zep / Graphiti Temporal knowledge graph memory
LlamaIndex memory modules Buffers, vector memory, fact extraction

Vector stores like pgvector, Qdrant, or Pinecone usually sit underneath.

Take quiz
Which tool is built around a temporal knowledge graph?
Zep / Graphiti
LangGraph checkpointer
pgvector alone
Pinecone alone
Letta is the continuation of:
Mem0
MemGPT
LlamaIndex
Chroma

26. What is the difference between short-term and long-term memory in agents?

Short-term memory is session-scoped and in-prompt; long-term memory is persistent and external. The first is always seen by the model, the second only appears if it is retrieved.

Aspect Short-term Long-term
Scope One thread/session Across sessions and users
Location Context window, graph state Vector DB, graph, files
Access Automatic every turn Needs retrieval or a tool call
Limit Context size Storage and retrieval quality
Risk Overflow, truncation Stale, wrong or poisoned data

A practical agent uses both: short-term for flow, long-term for continuity.

Take quiz
Which memory needs an explicit retrieval step to reach the prompt?
Short-term memory in the current prompt
The system prompt text
Long-term memory
Tool schemas
The main limit of short-term memory is:
Disk capacity
Embedding dimension
Network latency to the DB
Context window size

27. What is the difference between RAG and agent memory?

Both retrieve external text into the prompt, but they differ in what is stored and who writes it.

Aspect RAG Agent memory
Content Existing documents, mostly static Facts and events from the agent's own interactions
Writer Ingestion pipeline, humans The agent or a background extractor
Scope Shared knowledge base Per user, per agent or per task
Updates Re-index on doc change Continuous add, update, delete

Agent memory often reuses RAG machinery (embeddings, vector search), so the two blur together, but memory has to handle writes, conflicts, and forgetting that plain RAG can ignore.

Take quiz
Who typically writes entries in agent memory?
The agent or a background extractor
Only the document ingestion team
The tokenizer
The load balancer
Which concern is specific to memory but not classic RAG?
Chunking PDFs
Handling conflicting, outdated user facts
Using embeddings
Cosine similarity

28. How does an agent decide what to store in memory?

There are two broad patterns. In the hot path, the agent calls a save-memory tool during the conversation when it judges something worth keeping. In the background pattern, a separate process reads the finished conversation and extracts memories.

Either way, the decision usually relies on a prompt that asks: is this a durable fact, a stated preference, a correction, or a lesson, and is it likely to matter later? Small talk and one-off details should be skipped.

Good systems also check for duplicates and contradictions with existing entries before writing, so the store does not fill with near-identical lines.

Take quiz
In the hot-path approach, memories are saved:
Only by a nightly batch job
By the user's browser
By the agent during the conversation
By the embedding model alone
Before writing a new memory, a good system should:
Skip all checks for speed
Delete the whole store
Re-train the model
Check for duplicates and contradictions

29. How does memory retrieval work in an agent loop?

On each turn the agent builds a query, searches memory, injects the best hits into the prompt, lets the model reason and act, and then optionally writes new memories.

flowchart LR
  A["User message"] --> B["Build query"]
  B --> C["Search memory store"]
  C --> D["Rank and filter top-k"]
  D --> E["Inject into prompt"]
  E --> F["LLM reasons and calls tools"]
  F --> G{Worth remembering?}
  G -- yes --> H["Write or update memory"]
  G -- no --> I["Reply to user"]
  H --> I

The query can be the raw user message, a model-rewritten search query, or the current sub-goal. Rewriting usually improves recall for vague follow-ups like "what about the second one?"

Take quiz
After retrieving memories, the agent next:
Injects the top results into the prompt
Retrains the model
Deletes the query
Closes the session
Why rewrite the user's message before searching memory?
To reduce GPU cost to zero
Vague follow-ups retrieve poorly otherwise
To avoid using embeddings
To bypass the system prompt

30. Explain the lifecycle of a memory item in an AI agent?

A memory item goes through write, store, retrieve, update, and eventually expire.

stateDiagram-v2
  [*] --> Extracted
  Extracted --> Validated: dedupe and trust check
  Validated --> Stored: embed and save
  Stored --> Retrieved: matched by a query
  Retrieved --> Stored: used, importance bumped
  Stored --> Updated: new info conflicts
  Updated --> Stored
  Stored --> Expired: TTL or low score
  Expired --> [*]
  1. Extract the candidate from conversation or tool output.
  2. Validate it for duplicates, conflicts, and trust.
  3. Store it with embedding and metadata such as user, time, and source.
  4. Retrieve it when relevant, often raising its importance score.
  5. Update or expire it when newer facts arrive or its TTL passes.
Take quiz
Which stage happens right after validation?
Expiry
Retrieval by the user
Storing with embedding and metadata
Model retraining
What typically moves a memory to the expired state?
A successful retrieval
A new user login
A larger context window
TTL or low importance score

31. Why does a bigger context window not replace agent memory?

A larger window postpones the problem but does not solve it. Four things still break.

  1. Cost and latency: every turn re-sends and re-reads the whole prompt, so long histories get expensive and slow.
  2. Attention quality: models tend to use information in the middle of very long inputs less reliably, so recall degrades.
  3. Persistence: the window is wiped between sessions; it cannot remember last week.
  4. Noise: dumping everything in dilutes the signal. Selective retrieval gives the model only what matters.

Memory is about choosing what to show, not just fitting more in.

Take quiz
Which problem remains even with a huge context window?
Information is lost between separate sessions
Models can no longer read text
Embeddings stop working
Tool calls become illegal
Selective retrieval helps mainly by:
Increasing token price
Showing only the relevant information
Removing the user prompt
Hiding tool results from the model

32. How does the Generative Agents memory retrieval score work?

The Stanford Generative Agents paper (Park et al., 2023) ranks each memory in the stream by a weighted sum of three signals.

Signal Meaning How it is computed
Recency Newer memories score higher Exponential decay since last access
Importance How significant the event is LLM rates it, for example 1 to 10
Relevance Match to the current situation Embedding cosine similarity to the query

Each signal is normalised, then combined, and the top-scoring memories fill the prompt. This stops the agent from retrieving only the most similar item and ignoring recent or high-stakes events. Many later memory libraries borrow this three-factor idea.

Take quiz
Which three factors does the Generative Agents retrieval use?
Cost, speed, size
Length, tone, language
Recency, importance, relevance
Author, date, format
Importance in that scheme is typically assigned by:
The user's keyboard
A GPU benchmark
The tokenizer
An LLM rating of the event

33. How does MemGPT manage memory like an operating system?

MemGPT treats the prompt as main memory with a hard size limit and an external database as disk. The LLM acts as its own memory manager through function calls.

When the context nears its limit, a system message warns the model (memory pressure). The model can then call functions to write key facts to archival storage, edit its core memory blocks, or evict old messages that are summarised into recall storage. Later it calls search functions to page information back in.

flowchart TD
  A["Context near limit"] --> B["Warning to model"]
  B --> C["Model saves facts to archival"]
  C --> D["Old messages evicted and summarised"]
  D --> E["Model searches archive when needed"]
  E --> F["Relevant data paged into context"]

The key idea is that paging decisions are made by the agent itself, not by fixed truncation rules.

Take quiz
Who decides what to page in or out in MemGPT?
The LLM itself, via function calls
A fixed truncation rule only
The user manually
The database server
What triggers MemGPT to save or evict content?
A scheduled GPU reboot
A memory-pressure warning as context fills
User logout
A new embedding model

34. When should you use summary memory instead of a sliding window?

Choose by what the task needs to keep.

Situation Better choice Reason
Short chats where recent turns matter most Sliding window Lossless, no extra LLM call
Long sessions where early decisions still matter Summary memory Keeps the gist of old turns
Exact figures, IDs, code must survive Window plus extracted facts Summaries can drop exact values
Tight latency budget Sliding window Summarising adds a model call

A common hybrid keeps the last few turns verbatim, a rolling summary of everything older, and a separate structured list of key facts that is never summarised away.

Take quiz
A session needs exact order numbers preserved across 200 turns. Best approach?
Summary memory alone
Dropping all history
Window plus separately extracted key facts
Increasing temperature
A main cost of summary memory is:
It needs a graph database
It disables caching forever
It cannot run in Python
An extra LLM call and possible detail loss

35. When would you choose a knowledge graph over a vector store for memory?

Pick a graph when the answer depends on relationships and when facts change over time. Pick a vector store when you need fuzzy semantic recall over unstructured text.

Need Vector store Knowledge graph
Fuzzy "similar to this" lookup Strong Weak
Multi-hop questions (who reports to whom) Weak Strong
Tracking when a fact became invalid Awkward Natural with temporal edges
Setup effort Low Higher (schema, extraction)

Many production agents combine them: vectors for broad recall, a graph for entities and links.

Take quiz
Which question favors a knowledge graph?
Who is the manager of the approver of this invoice?
Find text similar to this paragraph
Summarise this chat
Translate this sentence
A drawback of graph memory compared with vectors is:
It cannot store names
Higher setup and extraction effort
It cannot be queried
It requires no schema at all

36. How do you handle conflicting or outdated memories in an agent?

Treat memory writes as updates, not appends. When the user says "I moved to Denver," the old "lives in Austin" fact should be superseded.

  1. On write, search for existing memories on the same subject.
  2. Ask an LLM (or rule) to decide: add, update, delete, or ignore.
  3. Keep timestamps and, if useful, mark the old fact as invalid rather than erasing it, which preserves history.
  4. At retrieval time, prefer the newest item when two disagree.
  5. For high-stakes facts, confirm with the user.

Mem0 uses exactly this ADD / UPDATE / DELETE / NOOP decision step, and temporal graphs like Graphiti store validity windows on each edge.

Take quiz
The user says they changed cities. The ideal memory action is to:
Append a duplicate and ignore the old one
Delete all memories
Update or supersede the old location fact
Do nothing
Marking an old fact invalid instead of deleting it:
Makes retrieval impossible
Breaks embeddings
Requires retraining
Preserves history while preferring the newest fact

37. How do you troubleshoot an agent that keeps forgetting facts?

Work from write to read and find where the fact got lost.

  1. Was it written? Inspect the store. If missing, the extraction prompt or save-tool trigger is too strict.
  2. Was it written under the wrong key? Check user ID, namespace, or thread ID. A mismatch is the most common bug.
  3. Was it retrieved? Log the query and top-k. If the fact exists but is not returned, tune the query rewriting, k, similarity threshold, or add keyword search.
  4. Was it in the prompt but ignored? Move it closer to the end, label it clearly, or shorten surrounding noise.
  5. Was it summarised away? Pull critical values into a structured fact list.
Take quiz
The fact exists in the store but is never returned. First check:
The retrieval query, top-k and threshold
The GPU fan speed
The user's browser
The model's license
A frequent cause of 'forgotten' facts is:
Using HTTPS
Writing under a different user or thread key
Using JSON
Using Python 3

38. How do you troubleshoot an agent recalling irrelevant memories?

Irrelevant recall usually means retrieval is too loose or the stored items are too vague.

  • Add a similarity threshold so weak matches are dropped instead of always filling top-k.
  • Filter by metadata such as user, topic, or memory type before ranking.
  • Rewrite the query with the current goal instead of using the raw last message.
  • Rerank the top 20 with a cross-encoder or small LLM, then keep the best 3 to 5.
  • Improve memory quality: store atomic, self-contained facts rather than long messy snippets.
Take quiz
A good first fix for always-returned weak matches is:
Increasing the temperature
Removing metadata
A similarity threshold
Embedding with a random model
Storing atomic, self-contained facts helps because:
It deletes duplicates automatically
It disables reranking
It speeds up the GPU
Each memory matches queries more precisely

39. Why can persistent memory be a security risk for AI agents?

Persistence turns a one-time trick into a lasting one. Three risks stand out.

  1. Indirect prompt injection: a document the agent reads can instruct it to save a malicious "rule" that fires in later sessions.
  2. Data leakage: memories can contain PII or secrets that show up for the wrong user if namespaces are weak.
  3. Silent drift: wrong facts, once stored, keep influencing decisions without anyone noticing.

Mitigations: scope memory per user and tenant, record the source of every entry, never auto-store content that came from untrusted tool output without review, give users a way to view and delete memories, and log all writes.

Take quiz
Why is injection through memory worse than injection in one chat?
The malicious instruction persists across sessions
It makes the model larger
It only affects the logs
It cannot be detected by anyone
A solid mitigation is to:
Share one namespace across all tenants
Track source and let users review or delete memories
Store all tool output blindly
Hide memory writes from logs

40. How do you isolate agent memory across users in a multi-tenant system?

Isolation has to be enforced in code and storage, never by asking the model to behave.

  1. Namespace every record with tenant and user IDs, for example ("tenant_7", "user_42", "memories").
  2. Apply the filter inside the data layer so a query without a valid scope returns nothing.
  3. Take the user ID from your authenticated session, not from model output or user text.
  4. Use separate indexes or row-level security (for example Postgres RLS with pgvector) for stricter tenants.
  5. Add tests that try cross-user retrieval and expect zero results.
# LangGraph store: scoped namespace
store.put(("tenant_7", "user_42", "memories"), key, {"fact": "prefers metric units"})
hits = store.search(("tenant_7", "user_42", "memories"), query="units")

Take quiz
Where should the user ID for memory scoping come from?
Text the model generates
A guess based on the topic
The authenticated session
The embedding vector
Strong isolation should be enforced:
Only in the system prompt
Only by user etiquette
Nowhere, models handle it
In the data layer, not just by prompt instructions

41. How can you optimize memory retrieval latency and cost?

Retrieval sits on the critical path of every turn, so small wins add up.

  • Use approximate nearest neighbour indexes such as HNSW instead of brute-force search once the store grows.
  • Cache embeddings of frequent queries and skip retrieval when the message clearly needs no memory ("thanks!").
  • Keep top-k small and add a threshold; every extra memory costs input tokens on every call.
  • Store compact memories: short atomic facts embed and read cheaper than raw transcripts.
  • Move writes off the hot path with background extraction.
  • Keep memory text stable and placed consistently so prompt caching can hit.
Take quiz
Which index type speeds up large-scale similarity search?
HNSW (approximate nearest neighbour)
Brute-force scan only
Alphabetical B-tree on text
Bloom filter
Why keep top-k small?
It improves GPU memory
Each retrieved memory adds input tokens every call
It disables embeddings
It enforces HTTPS

42. How do you evaluate the quality of agent memory?

Evaluate the pieces separately, then end to end.

Layer What to measure Example
Extraction Did it store the right facts, without junk? Precision/recall vs labelled facts
Retrieval Is the needed memory in top-k? Recall@k, MRR
Answer Does the final reply use memory correctly? Accuracy on recall questions
Update Are conflicts resolved properly? Test with changed facts
Ops Latency and token cost per turn p95 latency, tokens/turn

Public benchmarks such as LoCoMo and LongMemEval test long-conversation recall, temporal reasoning, and knowledge updates. Still build a small test set from your own domain, since real users ask very different things.

Take quiz
Recall@k measures:
Model parameter count
GPU temperature
Whether the needed memory appears in the top-k results
Prompt length only
LoCoMo and LongMemEval are:
Vector database products
Embedding models
Prompt caching features
Benchmarks for long-conversation memory

43. How do multiple agents share memory safely?

Shared memory is useful for hand-offs, but it multiplies the risk of conflicts and leaks. The usual pattern is private plus shared layers.

  1. Give each agent a private scratchpad for its own reasoning and tool noise.
  2. Provide a shared store, such as a blackboard or common graph state, for facts and results that others need.
  3. Define who may write what; for example only a coordinator writes final decisions.
  4. Tag entries with the writing agent, time, and confidence so readers can judge them.
  5. Use versioning or optimistic locking to avoid two agents overwriting each other.

Without these rules, one agent's bad guess becomes every agent's "fact."

Take quiz
A safe multi-agent pattern is:
Private scratchpads plus a controlled shared store
One shared prompt with no limits
Deleting memory after each agent
Letting any agent edit any entry silently
Tagging entries with writer and confidence helps readers to:
Compress embeddings
Judge how far to trust each entry
Increase the context window
Skip retrieval

44. What happens when an agent's context window overflows?

It depends on the framework, and the behavior is often worse than people expect.

  • Some APIs return an error when input plus requested output exceed the limit.
  • Some frameworks silently truncate the oldest messages, which may delete the original task or system instructions.
  • Agents with compaction or MemGPT-style paging summarise or evict old content to external storage.

Silent truncation is the dangerous case: the agent keeps running but has lost the goal or earlier decisions, so it drifts. Protect by pinning the system prompt and task, trimming bulky tool outputs early, and monitoring token counts so compaction runs before the hard limit.

Take quiz
The most dangerous overflow behavior is:
A clear error message
Automatic model retraining
Silent truncation of the oldest content
Doubling the window
A good protection against overflow drift is to:
Disable token counting
Remove the system prompt
Send duplicate messages
Pin the system prompt and task, and compact early

45. Explain reflection in agent memory?

Reflection is a step where the agent reads its recent memories and writes higher-level conclusions back into memory. In Generative Agents, it is triggered when the summed importance of recent events passes a threshold.

The model is asked something like: what are the three most important insights from these events? The answers, for example "Maria prefers morning meetings," are stored as new memories that can themselves be retrieved and reflected on.

flowchart LR
  A["Raw observations"] --> B["Importance sum passes threshold"]
  B --> C["LLM asked for key insights"]
  C --> D["Insights stored as new memories"]
  D --> E["Retrieved later for planning"]

This turns a long list of episodes into compact, reusable knowledge and cuts retrieval noise.

Take quiz
Reflection in Generative Agents is triggered when:
Recent events' importance sum crosses a threshold
The user logs out
The GPU restarts
A fixed number of tokens is sent
The output of reflection is:
A deleted database
Higher-level insights saved as new memories
A new embedding model
A tool schema

46. Why use hybrid search for agent memory?

Pure vector search is great at meaning but weak on exact tokens: order IDs, error codes, names, and rare terms. Keyword search (BM25) has the opposite strengths.

Hybrid search runs both and merges the lists, often with reciprocal rank fusion (RRF), then optionally reranks. A memory like "ticket INC-48213 was escalated" will be found by the ID through BM25 even if the embedding is vague.
Method Good at Weak at
Vector Paraphrases, concepts Exact IDs, rare words
BM25 keyword Exact terms, codes Synonyms, paraphrase
Hybrid Both Slightly more infrastructure

Take quiz
Which memory query benefits most from keyword search?
Something like the last trip idea
Summarise my mood
Find ticket INC-48213
Explain gravity
Reciprocal rank fusion is used to:
Compress embeddings
Encrypt memories
Train a tokenizer
Merge ranked lists from different retrievers

47. What is the difference between hot-path and background memory writes?

Hot-path writes happen during the conversation: the agent calls a save tool and the memory is available immediately. Background writes happen after or beside the conversation: a separate job extracts and consolidates memories.
Aspect Hot path Background
Latency to user Adds delay to the reply None
Freshness Available at once Available after the job runs
Quality Agent decides with limited view Sees whole conversation, can dedupe
Transparency User can see 'saved a memory' Invisible unless surfaced
Cost Extra tool-call tokens in-turn Separate LLM calls, can be batched

Many systems mix them: hot-path for explicit requests like "remember this," background for everything else.

Take quiz
Which write mode adds no delay to the user's reply?
Background
Hot path
Neither
Both always
An explicit 'remember this' request is best handled by:
Waiting a week
A hot-path write
Ignoring it
A model retrain

48. How do you handle PII and deletion requests in agent memory?

Plan for privacy at design time, because deleting data from a pile of embeddings is painful later.

  1. Minimise: store only what is useful; redact card numbers, passwords, and national IDs before writing.
  2. Tag and index by user so you can find everything about a person quickly.
  3. Support delete and export: remove the source text, its embeddings, graph edges, and any summaries derived from it. Do not forget backups and logs.
  4. Apply retention limits with TTLs.
  5. Show users what is remembered and let them edit it.

Summaries are a trap: a deleted fact can survive inside a summary or reflection derived from it, so track provenance of derived memories.

Take quiz
When deleting a user's data, you must also remove:
Only the original chat text
Only the model weights
Embeddings, graph edges and derived summaries
Nothing else
Why track provenance of derived memories?
To speed up embeddings
To lower token prices
To avoid using TTL
A deleted fact may live on inside a summary

49. What is the difference between context compaction and long-term memory?

Context compaction shrinks the current conversation so it keeps fitting in the window, for example by summarising older turns or clearing old tool results. It is about the same session. Long-term memory stores selected information outside the window so it survives across sessions and can be recalled later on demand.
Aspect Compaction Long-term memory
Goal Stay within context limit Persist knowledge
Scope One long-running task Across sessions
Form Summary inside the prompt External store, retrieved selectively
Loss Lossy, hard to undo Original kept, retrieval may miss

They complement each other: compaction keeps a long task alive, and the memory tool or store keeps what matters after the task ends.

Take quiz
Compaction mainly aims to:
Keep a long session within the context limit
Share data between users
Train the model
Encrypt facts
Which survives after the session ends?
The compacted in-prompt summary alone
Information saved to long-term memory
The raw context window
The temperature setting

50. Which is better for agent memory: file-based or vector-based, and why?

Neither wins everywhere. The right pick depends on volume, structure, and how the agent accesses memory.

Factor File-based (markdown, JSON) Vector-based
Best size Small to medium, tens to hundreds of notes Thousands to millions of items
Retrieval Agent reads index and opens files, exact and predictable Similarity search, fuzzy
Transparency Human-readable and editable, easy to diff Opaque embeddings
Setup Almost none Embedding model plus DB
Weakness Does not scale; agent must navigate Can return near-misses, harder to debug

Claude's memory tool and many coding agents use files because they are simple to inspect and version. Large customer-facing systems with huge histories generally need a vector or hybrid index. A common path is to start with files and add vector search when navigation becomes the bottleneck.

Take quiz
Which factor favors file-based memory?
Millions of items
Fuzzy semantic matching at scale
Human-readable, easy to audit and edit
No need for any storage
When does vector-based memory become the better choice?
When there are three notes
When humans must edit by hand only
When no retrieval is needed
When memory grows to thousands or more items
«
»

Comments & Discussions