Types of memory for AI systems

A language model has no memory between calls. Everything it appears to remember is something the application stored and put back in the prompt. This guide explains the memory types, how to manage a limited context window, and what you should never store.

Memory in 60 seconds

  • The model remembers nothing. Memory is stored text or data that your application selects and places in the prompt.
  • Two big groups: short-term memory lives in the context window for one task or session; long-term memory lives in a store and is retrieved when relevant.
  • Types of long-term memory: semantic (facts), episodic (past events), and procedural (how to do things).
  • Four operations: write, retrieve, update, and forget. Forgetting is as important as writing.
  • The context window is a budget. Keep it small and relevant: more text is not always better, and long contexts can lose details in the middle.

What memory means for a model

When you tell a chat assistant your name and it uses it five messages later, the model did not learn anything. The application kept the earlier messages and sent them again. When an assistant remembers your preferences next week, the application saved them somewhere and fetched them. Memory in an AI system is always an engineering feature built around a stateless model, and so it has the usual engineering questions: where is it stored, who can read it, how long does it live, and how does it stay correct?

What the model sees right now, and what is stored for later.

A guide to each type

Every type on this page has its own in-depth guide with a diagram, a worked example, code, design decisions, metrics, and notes for your role.

Part 1: short-term memory

1. Working memory (the context window)

Working memory is everything in the current prompt: the instructions, the conversation so far, retrieved documents, tool results, and the scratch work of an agent. It is the only thing the model can actually use. It is limited in size, it costs money in proportion to its length, and it is read again on every call. Treat it as a small desk: you decide what is on it.

Bigger is not automatically better. Models tend to use information at the start and end of a long prompt more reliably than information buried in the middle, and irrelevant text can distract from the relevant part. A common finding in practice is that quality can fall as the prompt fills with loosely related material, a problem often called context rot. The remedy is to curate: put in what the next step needs and leave out what it does not.

Read the full guide to the working memory: how it works, a worked example, code, design decisions, and how to measure it.

2. Session (short-term) memory

Session memory holds the state of the current conversation or task across turns: what the user asked, what was decided, what is still open. It lives for the session and is usually kept in a fast store keyed by session ID. Each turn, the application reads it, builds the prompt, and writes the update. When the session grows past the context budget, the application has to shorten it, and the techniques for that are in the next section.

Read the full guide to the session memory: how it works, a worked example, code, design decisions, and how to measure it.

Managing a limited context window

When a conversation or an agent run grows past the budget, something has to give. There are four standard techniques, and real systems combine them.

  • Truncation: drop the oldest messages. Simple and fast, but it forgets early instructions and facts unless they are pinned.
  • Sliding window: keep only the most recent N messages or tokens, usually with the system prompt always kept at the top.
  • Summarisation: replace old messages with a short summary of decisions, facts, and open questions. It keeps meaning but may drop details, so keep exact values (names, numbers, identifiers) as structured notes.
  • Compaction: a stronger form of summarisation for long agent runs. The agent's history is rewritten into a compact working state, such as a task list, key findings, and file or document references, and the raw history is archived.
Compaction: keep recent turns, summarise the rest (illustrative) (python)
# Illustrative: shrink a long history while keeping what matters.
# count_tokens() and call_model() are placeholders.

def compact(messages, budget_tokens, keep_last=6):
    if count_tokens(messages) <= budget_tokens:
        return messages
    old, recent = messages[:-keep_last], messages[-keep_last:]
    summary = call_model(
        'Summarise the decisions, confirmed facts, exact values and open questions '
        'from this conversation. Keep names, numbers and identifiers exactly as written.\n\n'
        + render(old)
    )
    note = {'role': 'system', 'content': 'Summary of the earlier conversation: ' + summary}
    return [note] + recent

Part 2: long-term memory

Long-term memory survives the session. The application writes selected items to a store, and later retrieves the relevant ones into the context window. Cognitive science offers a useful vocabulary here, and AI systems borrow it. The three kinds below differ in what they store and how they are used.

3. Semantic memory (facts and preferences)

Semantic memory stores facts that stay true across sessions: the user prefers metric units, their team uses Python, their company's fiscal year starts in April. Each entry is short, standalone, and easy to correct. This is the most common long-term memory in assistants. It works best when entries are written as clean statements, not raw quotes, and carry a source and a date, so a wrong fact can be traced and removed.

Read the full guide to the semantic memory: how it works, a worked example, code, design decisions, and how to measure it.

4. Episodic memory (past events)

Episodic memory stores what happened: a previous task, how it went, what was tried. An agent that fixed a deployment error last month can retrieve that episode when a similar error appears. Entries describe a situation, an action, and an outcome. They are retrieved by similarity to the current situation. Episodes are most valuable when they include the outcome, because that tells the agent whether to repeat the approach or avoid it.

Read the full guide to the episodic memory: how it works, a worked example, code, design decisions, and how to measure it.

5. Procedural memory (how to do things)

Procedural memory stores skills and rules: the steps for a refund, the team's code review checklist, the preferred report format. In practice these are instructions, templates, and worked examples that the application loads when a matching task appears. Some systems let agents improve their own procedures from feedback. That is powerful and risky, so route changes through review: a bad rule saved to procedural memory affects every later run.

Read the full guide to the procedural memory: how it works, a worked example, code, design decisions, and how to measure it.

6. Tiered (hierarchical) memory

Tiered memory arranges these stores by speed and size, much as a computer does with cache, memory, and disk. A small, always-visible core holds the most important facts. A larger store holds recent items that are retrieved on demand. An archive holds everything else and is searched only when needed. Items move between tiers: frequently used items are promoted, and old ones are summarised and archived. The design keeps the context window small while allowing a large total memory.

Read the full guide to the tiered memory: how it works, a worked example, code, design decisions, and how to measure it.

7. Shared (team) memory

Shared memory is visible to several users or agents: a team's decisions, a project's glossary, the state that several agents in one run read and write. It brings coordination benefits and sharp risks. Each entry needs an owner, a scope (who may read it), and a rule for conflicting updates. Private user memory must never leak into shared memory, and the separation should be enforced by the store's access rules, not by the prompt.

Read the full guide to the shared memory: how it works, a worked example, code, design decisions, and how to measure it.

The four operations

Any memory system, whatever its types, performs four operations. Each one needs a design decision.

  • Write: decide what is worth saving, and when. Writing everything creates noise; writing nothing wastes the feature. A common approach is to extract candidate facts after each session and keep only those that are specific, stable, and useful later.
  • Retrieve: find the right memories for the current turn, usually by similarity search over embeddings, combined with filters such as user, type, and recency.
  • Update: when a new fact contradicts an old one, replace or version it. 'Lives in Berlin' should not coexist with 'moved to Lisbon'.
  • Forget: expire old items, delete on request, and remove anything that should not have been stored.
A small long-term memory store with write, retrieve, and forget (illustrative) (python)
# Illustrative: a user-scoped memory store. vector_index and embed() are placeholders.
from datetime import datetime, timedelta

class Memory:
    def write(self, user_id, text, kind, source):
        record = {'user': user_id, 'text': text, 'kind': kind,  # semantic, episodic, procedural
                  'source': source, 'created': datetime.utcnow(), 'vector': embed(text)}
        existing = vector_index.nearest(record['vector'], filter={'user': user_id, 'kind': kind}, top_k=1)
        if existing and existing.score > 0.92:
            vector_index.update(existing.id, record)  # replace near-duplicates instead of piling up
        else:
            vector_index.add(record)

    def retrieve(self, user_id, query, top_k=5):
        hits = vector_index.search(embed(query), filter={'user': user_id}, top_k=top_k)
        return [h.text for h in hits if h.created > datetime.utcnow() - timedelta(days=365)]

    def forget(self, user_id, memory_id=None):
        if memory_id:
            vector_index.delete(memory_id, filter={'user': user_id})
        else:
            vector_index.delete_where({'user': user_id})  # a full erase request

What to store, and what not to

Memory makes an assistant useful, and it also makes the application a keeper of personal data. Decide the policy before building the store.

Store thisDo not store this
Stable preferences the user stated (units, tone, language)Passwords, API keys, payment card numbers, or other secrets
Decisions and their reasons, with a dateHealth, legal, or financial details unless the product needs them and the user has agreed
Task outcomes and what was learnedRaw conversations kept indefinitely 'just in case'
Project facts the user or team has confirmedGuesses the model made about the user, stored as if they were facts
Source and timestamp for every entryAnything the user asked you to forget
  • Show users what is remembered, and let them edit or delete it.
  • Set retention limits for each memory kind, and apply them automatically.
  • Scope by user and tenant inside the store's access rules.
  • Keep an audit log of writes and reads of sensitive memory.

The types compared

MemoryLives whereHoldsLifetimeMain risk
WorkingThe promptEverything the model reads nowOne callOverfilling; context rot
SessionA fast store keyed by sessionConversation or task stateOne sessionGrowing past the budget
SemanticA searchable storeFacts and preferencesLong, until updatedWrong or outdated facts
EpisodicA searchable storePast events and outcomesLong, with decayRepeating a past mistake
ProceduralTemplates and rulesHow to do tasksUntil revisedA bad rule affecting every run
TieredCore, recent, and archiveAll of the above, by priorityPer tierWrong promotion between tiers
SharedA scoped team storeCommon decisions and statePer policyLeaks and conflicting updates

How to choose

  • Start with session memory and a small sliding window. Most assistants need nothing more for a first release.
  • Add summarisation or compaction when conversations or agent runs routinely exceed the budget.
  • Add semantic memory when users repeat the same preferences every session.
  • Add episodic memory when an agent does recurring tasks and past outcomes would help.
  • Add procedural memory when instructions are long, change with the task, and can be loaded on demand.
  • Add shared memory only with explicit ownership, scope, and conflict rules.

What this means for your role

Common mistakes

Further reading

Good memory is selective. Save little, save it clearly, retrieve only what the next step needs, and let the user see and change it.

Search topics

↑↓ to move · Enter to open · Esc to close