Module 2 · Lesson 2 · 14 min read

Short-term and long-term memory

Short-term and Long-term Memory

Introduction

An agent needs two kinds of memory: one for what is happening now inside the context window, and another that lasts across sessions. In this lesson we learn the properties of each kind, strategies for managing short-term memory, and how information moves between the two.

Learning objectives

  • Compare short-term and long-term memory in terms of location, size and persistence
  • Apply the sliding window, summarization and selection strategies
  • Explain the MemGPT analogy of managing memory like an operating system
  • Build a dual memory in Python that moves important facts to permanent storage

A division inspired by psychology

Agent designers borrow from cognitive psychology the division of memory into short-term and long-term. The analogy is not scientifically exact, but it is useful in engineering because it separates what the agent needs now from what it needs over time. The CoALA framework uses the term working memory for the information active in the current decision, and contrasts it with long-term memory of different kinds.

RetrievalShort-term memoryShort-Term: the current context windowConversation memoryLong-term memoryLong-Term: outside the modelEpisodicEpisodic: eventsSemanticSemantic: factsStore and retrievalVector DB / keyword search
Short-term memory lives inside the context window, while long-term memory is stored outside the model and retrieved when needed.

Short-term memory

It is what is in the context window during the current task: the latest conversation messages, the current plan, and tool results from earlier cycles. Its properties:

  • Fast to access: the model sees it directly without any retrieval.
  • Limited in size: constrained by the context window and by your budget.
  • Temporary: it disappears when the session ends unless it is moved somewhere permanent.

The best-known strategies for managing it:

  1. Sliding window: keeping only the last N messages.
  2. Summarization: replacing old messages with a short summary.
  3. Selection: always keeping the important messages (such as the original goal) and deleting the less important ones.

Long-term memory

It is what is saved outside the model and lasts between sessions: in a database, a file or a vector store. Its properties:

  • Permanent: it remains after the session ends.
  • Relatively large: it is not constrained by the context window.
  • Needs retrieval: the agent must search it and choose what to put in the context.

The bridge between the two kinds

The most important engineering question: when does information move from short-term to long-term? And when does it come back? A common flow:

  1. During the session, the agent extracts "facts worth saving" (a preference, a decision, a permitted piece of personal information).
  2. It writes them to long-term memory with the time saved and their source.
  3. At the start of each session or before each decision, it retrieves what relates to the current request and puts it in the context.

The MemGPT paper (Packer and colleagues, 2023) offers a useful analogy: it treats the context window as limited main memory and external storage as a disk, and lets the agent itself move information between them through function calls, the way an operating system manages memory.

A practical example: the graduation project assistant

A student works with an agent on her graduation project over several weeks. In a long session dozens of messages pile up. The agent:

  • Keeps the last 4 messages in full in short-term memory.
  • Saves important decisions ("we chose a PostgreSQL database", "the deadline is 15 May") in long-term memory.
  • The following week, it retrieves these decisions automatically when she asks about the next step.
python
from collections import deque
from datetime import date

class AgentMemory:
    def __init__(self, window=4):
        self.short = deque(maxlen=window)   # sliding window: the last N messages
        self.long = []                      # simplified permanent storage

    def add_message(self, role, text):
        self.short.append({"role": role, "text": text})
        # A simple rule to extract what is worth saving
        for marker in ("decided", "deadline", "prefer"):
            if marker in text:
                self.long.append({"fact": text, "saved": date.today().isoformat()})

    def recall(self, query):
        words = set(query.split())
        return [m["fact"] for m in self.long if words & set(m["fact"].split())]

    def context(self, query):
        recalled = self.recall(query)
        return {"long_term": recalled, "short_term": list(self.short)}

mem = AgentMemory(window=4)
mem.add_message("user", "We decided to use PostgreSQL for the database")
mem.add_message("user", "The deadline is 15 May")
for i in range(5):
    mem.add_message("user", f"Side question number {i}")

ctx = mem.context("What is the next step for the database before the deadline")
print("Short:", [m["text"] for m in ctx["short_term"]])
print("Long:", ctx["long_term"])

Notice that the first two messages left the sliding window after the side questions, but the two decisions survived because they were moved to long-term memory, and then they returned to the context through retrieval.

Summary

Short-term memory is the content of the context window during the task; it is fast but limited and temporary, and it is managed with a sliding window, summarization or selection. Long-term memory is saved outside the model and lasts between sessions, but it needs good retrieval to be useful. The bridge between them is extracting the important facts, saving them and then retrieving them when needed. MemGPT offers the operating system analogy for this management.

Terms

TermEnglishDefinition
Short-term memoryShort-term MemoryThe information in the context window during the current task
Long-term memoryLong-term MemoryInformation saved outside the model that lasts between sessions
Working memoryWorking MemoryThe active information used in the current decision, according to CoALA
Sliding windowSliding WindowKeeping only the last set number of messages
RetrievalRetrievalSearching long-term memory and choosing what goes into the context

Review questions

  1. What three properties distinguish short-term memory?
  2. Why is the quality of retrieval more important than the size of the storage?
  3. In the graduation project example, how did the database decision survive despite leaving the sliding window?
  4. What analogy does MemGPT offer, and what does it add to our understanding of memory?

References