Sub topic 6
Long-term memory: persisting beyond one session
This chapter assumes you know basic Python, have called a chat-style LLM API, and understand an agent as an LLM running in a loop with tools. A basic idea of vectors and similarity helps for the code.
Why the buffer is not enough
Short-term memory is the conversation buffer. It lives in the context window and disappears when the session ends. Even within a session, trimming drops the oldest turns. If a user says "My name is Priya" on Monday, a buffer-only agent cannot know it on Tuesday.
Long-term memory is information stored outside the model and brought back into the prompt when it is relevant. The model itself does not change. Your code saves facts and experiences, then retrieves some of them on later calls.
| Property | Short-term memory | Long-term memory |
|---|---|---|
| Lives in | The prompt (context window) | An external store |
| Lifetime | One session, or less if trimmed | Across sessions |
| Size limit | The token budget | The storage capacity |
| Access | Always included | Retrieved on demand |
The working model
Long-term memory has three operations:
- Write. Decide that something is worth keeping and save it with metadata such as the owner and a type.
- Search. Given the current input, find the few stored memories most relevant to it.
- Inject. Put those memories into the prompt so the model can use them.
Retrieval is selective because the context window is limited. You cannot paste every memory into every prompt, so you rank memories and include only the top few.
A minimal store
This class saves each memory with its embedding, owner, and type. An embedding is a list of numbers that represents the meaning of a text, so similar texts get similar vectors. The search method ranks by cosine similarity and returns results for one user only.
import math
import time
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
class MemoryStore:
def __init__(self, embed):
self.embed = embed # function: str -> list[float]
self.items = []
def write(self, user_id, text, kind="semantic"):
self.items.append({
"user_id": user_id,
"text": text,
"kind": kind,
"vec": self.embed(text),
"created": time.time(),
})
def search(self, user_id, query, k=3):
q = self.embed(query)
own = [m for m in self.items if m["user_id"] == user_id]
own.sort(key=lambda m: cosine(q, m["vec"]), reverse=True)
return own[:k]The embed function is passed in, so you can use any embedding model. The filter on user_id matters: without it, one user's memories could appear in another user's prompt.
This store keeps items in a Python list, so they vanish when the process exits. For real persistence, write the items to a database or a vector store. The interface stays the same.
Common errors
- Saving everything. Storing every message fills the store with noise and makes retrieval worse. Save only facts, preferences, and outcomes worth reusing.
- Skipping the owner filter. Searching all items leaks data between users.
- Injecting too many memories. Each retrieved memory uses tokens. Keep
ksmall. - Treating memories as always true. A stored fact can go stale, such as an old address. Stores need updating and forgetting, which later chapters cover.
Exercise
A user tells the agent their favorite language is Python in one session. In a new session a week later, the agent must still know it. Which three operations must your code perform, and why can't you simply include every stored memory in every prompt?
Show answer
The code must write the fact to an external store (with the user ID), search the store using the new input, and inject the top results into the prompt. Including every memory would exceed the token budget and bury relevant facts among irrelevant ones, so retrieval selects only the few most relevant memories.