AI / AI agent memory Interview questions
Last updated
1. What is AI agent memory?
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
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
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.
- Keep task state across the steps of a single run.
- Carry user facts and preferences across sessions.
- Store lessons and past results so the agent does not repeat failed attempts.
- Hold knowledge that is too large to fit in the context window.
Take quiz
Making the tokenizer faster
Reducing the model's parameter count
Losing state between steps and sessions
Encrypting API keys
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?
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
The context window of the current session
A permanent external knowledge graph
The model's training data
The user's browser cookies only
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?
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
Is erased after each model call
Is stored only in the system prompt
Persists outside the context window across sessions
Cannot be searched
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?
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
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
A model fine-tuning job
Working memory for the run
A rate limiter
A tokenizer
6. What is episodic memory in AI agents?
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
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
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?
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
Semantic memory
Procedural memory
Working memory only
A checkpoint
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?
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
Raw user chat logs
A list of past dates
Instructions, skills and learned workflows
GPU temperature logs
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
Input and output tokens combined in a request
Only the user's message
Only the system prompt
Only stored files
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
Episodic
Semantic
Procedural
Sensory
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
Similarity between embeddings
Alphabetical order only
Random sampling
Exact primary-key joins only
GPU model
User ID and timestamp
Browser theme
Model temperature
12. What are embeddings in agent memory?
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
The user's screen size
The log file name
The embedding model
The HTTP method
At random positions
In separate databases
Only in the same language
Close together in vector space
13. What is conversation buffer memory?
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
The last N messages
Only the first message
Only tool errors
Summaries only
It cannot store text
Token cost grows every turn
It requires a graph database
It deletes the latest message
14. What is summary memory?
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
Speed for hardware cost
Security for accuracy
Exact detail for lower token usage
Storage for GPU memory
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 thread ID
The model name
The embedding dimension
The API key
Resuming a paused run
Memory shared across different threads
Replaying past steps
Per-thread state snapshots
16. What is entity memory?
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
Raw GPU metrics
Only the last user message
Facts about named people, products or accounts
Tokenizer merges
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?
(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
Edges between entity nodes
Rows of raw embeddings only
Cached HTTP responses
Prompt templates
Compressing images
Multi-hop relationship questions
Reducing tokenizer size
Streaming audio
18. Define memory retrieval in AI agents?
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
Which GPU runs the model
How the model is trained
Which stored items go into the prompt now
Which language the user speaks
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
One conversation's state and history
All users' long-term facts
The embedding model
The model's weights
Thread ID only
User ID or namespace
Timestamp only
Token count
20. Define memory consolidation in AI agents?
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
Deletes the model
Increases temperature
Merges and cleans raw logs into durable memories
Disables embeddings
Only during token generation
Only at model training time
Never
In the background between sessions
21. What is forgetting in AI agent memory?
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
TTL expiry
Doubling every entry
Re-embedding hourly
Raising the max tokens
Lower storage use
Stale and contradictory memories piling up
Perfect accuracy
Faster training
22. What is MemGPT?
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
Image compression
Blockchain consensus
Operating system memory management
Database sharding only
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
In storage your application controls
Inside Claude's weights
On Anthropic's public CDN
In the user's browser history
Direct SQL queries to the model
A /memories directory via tool calls
The tokenizer
24. What is memory poisoning in AI agents?
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
It speeds up the model
It deletes the GPU driver
Malicious content persists and affects later sessions
It only affects logging
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
Zep / Graphiti
LangGraph checkpointer
pgvector alone
Pinecone alone
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
Short-term memory in the current prompt
The system prompt text
Long-term memory
Tool schemas
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
The agent or a background extractor
Only the document ingestion team
The tokenizer
The load balancer
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
Only by a nightly batch job
By the user's browser
By the agent during the conversation
By the embedding model alone
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
Injects the top results into the prompt
Retrains the model
Deletes the query
Closes the session
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 --> [*]
- Extract the candidate from conversation or tool output.
- Validate it for duplicates, conflicts, and trust.
- Store it with embedding and metadata such as user, time, and source.
- Retrieve it when relevant, often raising its importance score.
- Update or expire it when newer facts arrive or its TTL passes.
Take quiz
Expiry
Retrieval by the user
Storing with embedding and metadata
Model retraining
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.
- Cost and latency: every turn re-sends and re-reads the whole prompt, so long histories get expensive and slow.
- Attention quality: models tend to use information in the middle of very long inputs less reliably, so recall degrades.
- Persistence: the window is wiped between sessions; it cannot remember last week.
- 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
Information is lost between separate sessions
Models can no longer read text
Embeddings stop working
Tool calls become illegal
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
Cost, speed, size
Length, tone, language
Recency, importance, relevance
Author, date, format
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
The LLM itself, via function calls
A fixed truncation rule only
The user manually
The database server
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
Summary memory alone
Dropping all history
Window plus separately extracted key facts
Increasing temperature
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
Who is the manager of the approver of this invoice?
Find text similar to this paragraph
Summarise this chat
Translate this sentence
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.
- On write, search for existing memories on the same subject.
- Ask an LLM (or rule) to decide: add, update, delete, or ignore.
- Keep timestamps and, if useful, mark the old fact as invalid rather than erasing it, which preserves history.
- At retrieval time, prefer the newest item when two disagree.
- 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
Append a duplicate and ignore the old one
Delete all memories
Update or supersede the old location fact
Do nothing
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.
- Was it written? Inspect the store. If missing, the extraction prompt or save-tool trigger is too strict.
- Was it written under the wrong key? Check user ID, namespace, or thread ID. A mismatch is the most common bug.
- 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.
- Was it in the prompt but ignored? Move it closer to the end, label it clearly, or shorten surrounding noise.
- Was it summarised away? Pull critical values into a structured fact list.
Take quiz
The retrieval query, top-k and threshold
The GPU fan speed
The user's browser
The model's license
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
Increasing the temperature
Removing metadata
A similarity threshold
Embedding with a random model
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.
- Indirect prompt injection: a document the agent reads can instruct it to save a malicious "rule" that fires in later sessions.
- Data leakage: memories can contain PII or secrets that show up for the wrong user if namespaces are weak.
- 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
The malicious instruction persists across sessions
It makes the model larger
It only affects the logs
It cannot be detected by anyone
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.
- Namespace every record with tenant and user IDs, for example
("tenant_7", "user_42", "memories"). - Apply the filter inside the data layer so a query without a valid scope returns nothing.
- Take the user ID from your authenticated session, not from model output or user text.
- Use separate indexes or row-level security (for example Postgres RLS with pgvector) for stricter tenants.
- 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
Text the model generates
A guess based on the topic
The authenticated session
The embedding vector
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
HNSW (approximate nearest neighbour)
Brute-force scan only
Alphabetical B-tree on text
Bloom filter
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
Model parameter count
GPU temperature
Whether the needed memory appears in the top-k results
Prompt length only
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.
- Give each agent a private scratchpad for its own reasoning and tool noise.
- Provide a shared store, such as a blackboard or common graph state, for facts and results that others need.
- Define who may write what; for example only a coordinator writes final decisions.
- Tag entries with the writing agent, time, and confidence so readers can judge them.
- 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
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
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
A clear error message
Automatic model retraining
Silent truncation of the oldest content
Doubling the window
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?
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
Recent events' importance sum crosses a threshold
The user logs out
The GPU restarts
A fixed number of tokens is sent
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
Something like the last trip idea
Summarise my mood
Find ticket INC-48213
Explain gravity
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?
| 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
Background
Hot path
Neither
Both always
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.
- Minimise: store only what is useful; redact card numbers, passwords, and national IDs before writing.
- Tag and index by user so you can find everything about a person quickly.
- Support delete and export: remove the source text, its embeddings, graph edges, and any summaries derived from it. Do not forget backups and logs.
- Apply retention limits with TTLs.
- 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
Only the original chat text
Only the model weights
Embeddings, graph edges and derived summaries
Nothing else
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?
| 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
Keep a long session within the context limit
Share data between users
Train the model
Encrypt facts
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.