What types of memory can an AI agent have, and where does each one live?
Advertisement
🧩 Scenario
Concept Walkthrough
Start from the truth: the model is stateless
Think of an LLM call like a pure function: same input, it knows nothing else. There is no session on the model side. If your chat feels like it "remembers", it is because your code (or the SDK) sent the earlier messages again. So agent memory is really a question of what you put back into the context, and where you stored it in the meantime.
1. Short-term memory: the current conversation
This is the message history of one thread: user messages, assistant replies, tool calls and tool results. It is like component state that lives as long as the conversation does. You store it per thread (a threadId) and send it back each turn.
The problem: it grows. Every turn adds input tokens, so cost and latency rise and you eventually hit the context window. Common fixes are keeping only the last N messages, dropping old tool results, or replacing older turns with a summary.
2. Working memory: the key facts you always keep in view
Working memory is a small, structured set of facts the agent should always have, such as "user's stack: Next.js, TypeScript" or "current goal: migrate to App Router". It sits in the system prompt every turn. Think of it as a tiny global store: small, always read, updated on purpose. Mastra offers this as a named feature (working memory).
3. Long-term memory: facts and history across sessions
This lives in a database and outlives any single thread. It is usually scoped to the user, not the thread. Two common ways to read it back:
- Direct lookup: load the user's saved preferences by
userId. Cheap and predictable. - Semantic recall: store past messages or notes as embeddings and retrieve the ones most similar to the current question. Useful when there is too much history to send, at the cost of an embedding model and a vector store.
LangChain's docs further split long-term memory into semantic (facts), episodic (past experiences) and procedural (how to behave, often the instructions themselves). You do not need these labels in an interview, but they help structure your answer.
Who writes memory?
Either your code writes it (for example after each conversation, extract preferences) or the agent writes it through a tool like rememberFact. A tool is flexible, but treat it like any user input: validate it, cap its size, scope it to the user, and let users see and delete it.
Key Code Explained
import { generateText, tool, isStepCount, type ModelMessage } from 'ai';
import { z } from 'zod';
// Your own data layer (Postgres, Redis, etc.)
import { db } from './db';
const MAX_HISTORY = 20; // tune from real conversations
export async function chatTurn(userId: string, threadId: string, userText: string) {
// Long-term memory: facts saved against the user, across all threads
const facts = await db.facts.listByUser(userId); // e.g. ['Uses Next.js with TypeScript']
// Short-term memory: this thread only, trimmed to fit the context window
const history: ModelMessage[] = await db.messages.lastByThread(threadId, MAX_HISTORY);
const result = await generateText({
model: 'anthropic/claude-sonnet-5.5', // example id
// Working memory: a few key facts, injected every turn
system: [
'You are a coding assistant.',
facts.length ? `Known facts about this user:\n- ${facts.join('\n- ')}` : '',
].join('\n\n'),
messages: [...history, { role: 'user', content: userText }],
tools: {
// Lets the agent write long-term memory, with limits you control
rememberFact: tool({
description: 'Save a durable fact about the user, such as their tech stack.',
inputSchema: z.object({ fact: z.string().max(200) }),
execute: async ({ fact }) => {
await db.facts.add(userId, fact); // scoped to this user only
return { saved: true };
},
}),
},
stopWhen: isStepCount(3),
});
// Persist the new turn so the next request can rebuild short-term memory
await db.messages.append(threadId, [
{ role: 'user', content: userText },
...result.response.messages,
]);
return result.text;
}
Notice that every kind of memory is just data you load before the call and save after it. The userId passed into execute comes from your auth session, never from the model, so one user's memory cannot leak into another's thread.
Tradeoffs
| Memory type | Scope | Stored in | Strength | Cost |
|---|---|---|---|---|
| Short-term (history) | One thread | Messages table | Full detail of the current chat | Grows with every turn |
| Working memory | Thread or user | Small record in the prompt | Always available, cheap | Must stay small and current |
| Long-term (lookup) | User | Database | Persists across chats | Needs write rules and privacy controls |
| Long-term (semantic recall) | User | Vector store | Finds relevant old context | Embedding cost, can retrieve wrong items |
What Interviewers Actually Check
- Whether you know the model is stateless and memory is rebuilt per request
- Whether you separate thread scope from user scope
- Whether you handle growing history before it hits the context window
- Whether you treat agent-written memory as untrusted input
- Whether you think about privacy: visibility and deletion
Follow-Up Questions
- How would you summarise old messages without losing important details?
- When would you use semantic recall instead of a direct lookup?
- How do you stop the agent from saving wrong or harmful "facts"?
- How would memory work if the same user chats from two tabs at once?
- How would you let a user export or delete everything the assistant remembers?
Common Candidate Mistakes
- Saying the model "learns" from conversations. It does not change between calls.
- Sending the entire history every time with no trimming plan.
- Storing memory by thread only, so nothing carries over to a new chat.
- Taking
userIdfrom tool input instead of the server session. - Forgetting that more memory in the prompt means more input tokens on every call.
Interview Readiness Checklist
Before you leave this question, make sure you can answer:
- Can you explain why an LLM call has no memory of its own?
- Can you describe short-term, working and long-term memory with examples?
- Can you trim history to stay within the context window?
- Can you scope memory correctly by thread and by user?
- Can you design a memory tool with validation and user controls?
Summary
LLM calls are stateless, so agent memory is your app choosing what to send back into the context. Short-term memory is the current thread's message history and needs trimming as it grows. Working memory is a small set of key facts injected every turn. Long-term memory lives in a database, is scoped to the user and comes back through direct lookup or semantic recall. Whoever writes memory, your code or the agent through a tool, validate it, scope it with the server-side user id, and let users see and delete it.
Does the model remember previous conversations by itself?
No. A model API call is stateless. Anything the model seems to remember was sent again in the request, either by your code or by a provider feature that stores state for you. Memory is an application feature, not a model feature.
What is the difference between a thread and a user in agent memory?
A thread is one conversation, so its message history is short-term memory. A user (Mastra calls it a resource) owns many threads, so facts saved against the user, such as their preferred language, can be reused in any of their conversations. Frameworks like Mastra and LangGraph model this split explicitly.
Should I store everything the user says as long-term memory?
No. Store only facts that will help later, let users see and delete them, and treat anything personal as data you are responsible for. Saving too much also hurts quality, because irrelevant memories get pulled into the prompt.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement