How does memory work in AI agents?

Learning path, stage 4 of 5: Agents, tools and MCP · question 5 of 10

An LLM has no memory between calls, so agents build it. Short-term memory is the context window: the current conversation and tool results. Long-term memory is stored outside the model (files, databases, vector stores) and brought back into context when it's relevant. The hard part is deciding what to write, when to recall it, and what to forget.

Types of memory

  • Working / short-term: the message history. Limited by the context window, so you compact or summarise it.
  • Episodic: records of past interactions ("last week the user preferred TypeScript").
  • Semantic: facts and knowledge, often in a vector store for retrieval.
  • Procedural: learned instructions or skills (saved prompts, playbooks).

Patterns

  • Summarise and compact old turns once a token threshold is reached.
  • A memory tool: the agent explicitly reads and writes notes (files), like a scratchpad that persists between sessions.
  • Retrieval by relevance + recency + importance, as in the Generative Agents paper.
  • OS-style paging between main context and external storage (MemGPT).

Risks

Stale or wrong memories spread across sessions. Memory can store injected instructions. Privacy and deletion obligations apply. Let users see and delete what's stored.

Sources

Code example

tsx
1// Long-term memory scored by relevance + recency + importance (Generative Agents style).
2interface Memory { text: string; vector: number[]; createdAt: number; importance: number /* 1-10 */ }
3
4declare function embed(text: string): Promise<number[]>;
5const cosine = (a: number[], b: number[]) => {
6 let d = 0, na = 0, nb = 0;
7 for (let i = 0; i < a.length; i++) { d += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
8 return d / Math.sqrt(na * nb);
9};
10
11export async function recall(store: Memory[], query: string, k = 5) {
12 const q = await embed(query);
13 const now = Date.now();
14 return store
15 .map((m) => {
16 const hours = (now - m.createdAt) / 3.6e6;
17 const recency = Math.pow(0.995, hours); // exponential decay
18 const score = cosine(q, m.vector) + recency + m.importance / 10;
19 return { m, score };
20 })
21 .sort((a, b) => b.score - a.score)
22 .slice(0, k)
23 .map((x) => x.m.text); // inject these into the system prompt or the next turn
24}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @modelcontextprotocol/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app