Skip to content

All lessons

Area 03 // AI AgentsLesson 51 / 14014 min read

Short-term and long-term memory

Short-term memory is what an agent keeps in its context window during one conversation or task, and long-term memory is information saved outside the model (facts, preferences, past results) and looked up again in later sessions.

Think of it like this

Analogy

Think of a doctor. During your appointment they keep everything you've said in their head: that's short-term memory. Between appointments, they rely on your medical file: allergies, past treatments, notes from last time. That's long-term memory. A good doctor reads the relevant part of the file before you walk in, not the whole thing.

The problem it solves

Models remember nothing between requests (context windows). Within one long task, the conversation and tool results pile up until they no longer fit. Across sessions, everything is forgotten: users have to repeat their preferences, and agents redo work they already did last week.

Users expect assistants to remember. Doing it well means deciding what to keep in context now, what to save for later, and how to find it again.

How it works: short-term memory

  1. Short-term memory is the context your loop resends each turn: system prompt, recent messages, tool results, the current plan.
  2. It has a budget: the context window, and your cost and latency limits.
  3. Keep the most useful parts: the latest turns verbatim; important facts pinned (the user's goal, constraints).
  4. Shrink the rest: drop old tool results, summarise older turns (compaction), or move them to long-term memory.
  5. Per-session state (a shopping cart, a draft document) is better kept as structured data than as chat text.

How it works: long-term memory

  1. Long-term memory lives outside the model: a database, key-value store, vector store or files.
  2. Decide what to save:
    • Semantic (facts and preferences): "vegetarian", "prefers metric units", "works in finance".
    • Episodic (events): "On 3 Oct we fixed the login bug by resetting SSO."
    • Procedural (learned how-tos): "For this repo, run make test, not pytest."
  3. Save it: through a memory tool the agent calls ("remember that…"), a background job that extracts facts after each session, or explicit user settings.
  4. Retrieve it: at the start of a session, or when relevant to the current request, by key (user ID) or by similarity search (like RAG).
  5. Inject only what's relevant into the context, labelled as memory.
  6. Govern it: users can view and delete memories; apply retention limits; never store secrets; keep memories per user (and per tenant) with access control.
  7. Handle conflicts and staleness: newer facts replace older ones ("moved to Berlin" replaces "lives in London").
Short-term memory is the context; long-term memory is a store the agent reads and writes.

See it in code

Needs
Nothing: plain Python 3.

A sliding window for short-term memory and a simple per-user fact store for long-term memory.

memory.py
from collections import deque
 
# SHORT-TERM MEMORY: the recent conversation, trimmed to a budget.
class ShortTerm:
    def __init__(self, max_messages=4):
        self.messages = deque(maxlen=max_messages)   # oldest messages fall off automatically
    def add(self, role, text):
        self.messages.append({"role": role, "content": text})
 
# LONG-TERM MEMORY: facts saved across sessions, looked up when relevant.
class LongTerm:
    def __init__(self):
        self.facts = {}                              # a real app: a database or vector store
    def remember(self, user, key, value):
        self.facts.setdefault(user, {})[key] = value
    def recall(self, user, question):
        return {k: v for k, v in self.facts.get(user, {}).items() if k in question.lower()}
 
short, long_term = ShortTerm(), LongTerm()
for i, text in enumerate(["Hi", "I'm vegetarian", "Book a table", "For 4 people", "At 7pm"]):
    short.add("user", text)
long_term.remember("u42", "diet", "vegetarian")      # saved by a memory tool or a background job
 
print("short-term window:", [m["content"] for m in short.messages])
print("long-term recall :", long_term.recall("u42", "Suggest a diet-friendly restaurant"))
Output
short-term window: ["I'm vegetarian", 'Book a table', 'For 4 people', 'At 7pm']
long-term recall : {'diet': 'vegetarian'}

Notice that "Hi" has already fallen out of the window; if "I'm vegetarian" falls out too, only long-term memory keeps it. Real recall uses a database query by user, plus similarity search for free-text memories. Some APIs also offer a built-in memory tool the model can call (Anthropic's memory_20250818, as of November 2026), with your code deciding where memories are stored.

A real example

Example

A personal travel assistant

A travel app's assistant remembers, per user: home airport, seat preference, dietary needs, loyalty programmes, and a short history of past trips ("Lisbon, June 2026, loved the boutique hotel in Alfama"). A background job extracts these after each conversation; users see them under "What the assistant remembers" and can delete any item.

When a user asks "find me something like last summer's trip", the assistant retrieves the Lisbon memory and preferences, then searches. Within the conversation, it keeps the last 12 turns verbatim and a running summary of earlier ones. Conversion rates rose because users stopped re-typing their preferences.

The easy way

Start here

Short-term: keep the last N messages plus a running summary. Long-term: start with a small table of user preferences (key, value, updated_at), read it at the start of each session, and let users edit it. Add similarity-searched free-text memories only when you need them.

When you grow: the production setup

Production memory systems separate memory types, extract and deduplicate memories with LLM calls, timestamp and expire them, resolve conflicts, store embeddings for search, scope everything by user and tenant, log memory reads and writes, offer user controls and data export/deletion, and evaluate whether memory improves outcomes (and doesn't leak across users).

Trade-offs

What you gain

  • Users don't repeat themselves; experiences feel personal.
  • Long tasks stay within context limits.
  • Agents can reuse past results and lessons.

What it costs you

  • Wrong or outdated memories can mislead the agent.
  • Privacy, consent and deletion obligations.
  • More storage, retrieval and extraction logic to maintain.

When not to use it

  • Anonymous or one-off interactions where there's nothing to remember.
  • Sensitive domains where storing user details isn't allowed or wanted.

Common mistakes

  • Assuming the model remembers previous sessions by itself.
  • Stuffing every past message back into the context.
  • Storing sensitive data (passwords, health details) without consent or protection.
  • Never expiring or correcting outdated memories.
  • Memories not scoped by user, leaking between accounts.

Interview questions

Try answering out loud first, then open the model answer.

How would you add memory to a chat assistant?

Model answer

Short-term: maintain the conversation within a token budget, keeping recent turns verbatim and summarising older ones, plus structured session state. Long-term: extract salient facts and preferences (via a memory tool or post-session job), store them per user with timestamps and embeddings, retrieve relevant ones at session start or per query, inject them clearly labelled, and give users visibility and deletion controls with appropriate privacy safeguards.

What types of long-term memory might an agent need?

Model answer

Semantic memory (stable facts and preferences about the user or domain), episodic memory (records of past interactions and outcomes, useful for "like last time" and for learning from mistakes), and procedural memory (learned instructions or skills, like how a particular codebase is built and tested). Each has different storage, retrieval and update strategies.

What risks does long-term memory introduce?

Model answer

Privacy and compliance (sensitive data, consent, right to deletion), cross-user leakage from bad scoping, stale or wrong memories degrading answers, memory poisoning where injected content gets saved and influences future sessions, and growing cost. Mitigate with scoping, validation of what gets saved, expiry, user controls, audit logs and evals.

Quiz

Pick an answer to see whether it’s right and why.

  1. 01Where does an agent's short-term memory live?
  2. 02A user said "I'm vegetarian" last month. How can the assistant remember it today?
  3. 03What happens when short-term memory exceeds the context budget?
  4. 04What is a memory tool?
  5. 05Which should NOT be stored in long-term memory by default?

0 of 5 answered

Key terms

Short-term memory
What an agent keeps in its context window during one conversation or task, trimmed or summarised to fit.
Long-term memory
Information an agent saves outside the model (facts, preferences, past events) and retrieves in later sessions.
Context window
The maximum number of tokens a model can consider in one request, counting both the input and the generated output.
Memory tool
A tool an agent can call to save or look up memories itself, with the app deciding where they are stored.

Before and after

Progress is saved in this browser only.