Sub topic 6
Long-term memory: persisting beyond one session
This chapter assumes you know basic Python, have called a chat-style LLM API, understand an agent as an LLM running in a loop with tools, and have a basic idea of vectors and cosine similarity. Earlier chapters covered the context window and the short-term conversation buffer. Here you build the piece that survives after a session ends.
Why a buffer is not enough
Short-term memory is the list of messages you send to the model on each call. It has three limits:
- Size. The list must fit the token budget, so old turns get trimmed or summarized.
- Lifetime. The list usually lives in a variable or a session object. When the process ends or the user opens a new chat, it is gone.
- Scope. The buffer holds one conversation. It cannot tell the agent what happened last week or what another session learned.
Long-term memory is information stored outside the model and outside the prompt, so it persists across sessions. The agent writes to it during or after a conversation and reads from it later. Nothing is "remembered" by the model itself. Your code retrieves a few relevant items and places them in the prompt, where they become part of the context window like any other text.
This leads to the central rule of the chapter: long-term memory is a storage and retrieval problem, not a model feature. Every quality problem you meet later (wrong recall, stale facts, leaked data) is a problem in how you store, find, or inject records.
Short-term versus long-term
| Property | Short-term memory | Long-term memory |
|---|---|---|
| Where it lives | In the prompt (context window) | In an external store |
| Lifetime | One session or less | Across sessions |
| Capacity | Limited by the token budget | Limited by storage, not tokens |
| Access | Always included, in order | Retrieved on demand by relevance |
| Typical content | Recent turns, tool results | Facts, preferences, past outcomes |
| Main failure | Important turns trimmed away | Wrong or missing records retrieved |
Use short-term memory for what the model needs to follow the current exchange. Use long-term memory for what should still be true tomorrow: the user's name, their preferred language, a decision made last week, or a fix that worked.
A quick test: if you would be annoyed to repeat it in a new chat, it belongs in long-term memory. If it only matters for the next few turns, leave it in the buffer.
The memory cycle
Every long-term memory system performs three operations. The agent decides when to run each one.
- Write. Turn something worth keeping into a record and save it.
- Retrieve. Given the current input, find the few records most likely to help.
- Inject. Place those records in the prompt, then trim the whole prompt to the budget.
The loop closes at the store. What one turn writes, a later turn, possibly in another session, can retrieve.
What a memory record contains
A string of text is not enough. A useful record carries metadata that you will need for filtering, ranking, and cleanup:
- text: the memory in plain language, such as "Prefers answers in metric units."
- user_id: who the memory belongs to. Without it you cannot keep users apart.
- kind: episodic, semantic, or procedural (a later chapter covers these).
- vec: an embedding of the text, used for similarity search.
- created: a timestamp, so you can rank by recency or expire old items.
The sample code below keeps exactly these fields.
A minimal store
This store keeps records in a Python list, embeds each one on write, and returns the top-k most similar records for a single user. It is deliberately small, so you can see every step.
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]Points to notice:
embedis passed in. In production it calls an embedding model. The store does not care which one, as long as the same function embeds both memories and queries.searchfilters byuser_idbefore ranking. The filter is what stops one user's memories from appearing for another.cosinereturns 0.0 for zero vectors instead of dividing by zero.searchalways returns up tokitems, even if none is relevant. The next sections explain why that matters.
Using the store inside a turn
The next function retrieves memories for the current input, adds them to the system message, and trims everything to the budget. It relies on trim_messages from the short-term chapter, which keeps system messages and drops the oldest turns first.
def trim_messages(messages, max_tokens, count_tokens):
"""Keep system messages plus the most recent messages that fit the budget."""
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
budget = max_tokens - sum(count_tokens(m["content"]) for m in system)
kept = []
for m in reversed(rest):
cost = count_tokens(m["content"])
if cost > budget:
break
kept.append(m)
budget -= cost
return system + list(reversed(kept))
def build_prompt(system_prompt, history, store, user_id, user_input,
max_tokens, count_tokens, k=3):
recalled = store.search(user_id, user_input, k=k)
memory_block = "\n".join("- " + m["text"] for m in recalled)
system = system_prompt
if memory_block:
system += "\n\nKnown facts about the user:\n" + memory_block
messages = [{"role": "system", "content": system}]
messages += history + [{"role": "user", "content": user_input}]
return trim_messages(messages, max_tokens, count_tokens)Recalled memories sit in the system message, so trimming never removes them. That is convenient, but it has a cost: every memory you inject reduces the room left for conversation history. If you retrieve too many, the buffer shrinks. Choose k with the token budget in mind.
Running it across two sessions
To try the store without an embedding API, use a toy embedding based on word counts. It is crude, but it makes the behavior visible. Add this after the code above.
VOCAB = ["name", "priya", "metric", "units", "python", "vegetarian", "food"]
def toy_embed(text):
words = text.lower().replace("?", "").replace(".", "").split()
return [float(words.count(w)) for w in VOCAB]
count = lambda text: len(text.split())
store = MemoryStore(toy_embed)
# Session 1: the agent saves facts it learned.
store.write("u1", "User name is Priya")
store.write("u1", "User prefers metric units")
store.write("u2", "User is vegetarian and likes food from India")
# Session 2: a new conversation with an empty history.
prompt = build_prompt(
system_prompt="You are a helpful assistant.",
history=[],
store=store,
user_id="u1",
user_input="Which units do I prefer, what is my name?",
max_tokens=60,
count_tokens=count,
k=2,
)
for message in prompt:
print(message["role"], "->", message["content"])The second session starts with no history, yet the system message lists both facts about u1. The vegetarian memory belongs to u2 and does not appear.
Edge cases and common errors
- Top-k returns noise.
searchreturns the k best matches, even when all of them are poor. A question about the weather would still pull in three unrelated memories. Add a minimum similarity threshold, and return fewer items, or none, when nothing passes. - Mismatched embedders. If you change the embedding model, old vectors and new query vectors live in different spaces and similarity becomes meaningless. Store the model name with each record, and re-embed everything when you switch.
- Duplicates. Writing "User name is Priya" every session fills the store with copies that crowd out other results. Check for a near-identical record before writing.
- Stale facts. "Lives in Berlin" may stop being true. Without updating or expiry, the agent will state old facts with confidence. Timestamps give you the means to detect this.
- Memory treated as instructions. Retrieved text goes into the prompt, so a stored sentence like "ignore previous rules" could steer the model. Label the block as facts about the user, and avoid storing raw untrusted text.
- Missing scope. Searching without a
user_idfilter is a data leak. Make the filter part of the only search path, as the code above does, instead of relying on callers to remember it. - Lost on restart. A Python list vanishes when the process exits. It demonstrates the interface, but it is not persistence. Real systems back the same interface with a database, a file, or a vector store, which the next chapters cover.
When to write, in brief
Writing every message is rarely a good idea. It stores filler, raises cost, and makes retrieval noisier. A common approach is to run a small extraction step after a turn or session. The step asks the model to list durable facts, preferences, or outcomes, and only those become records. A later chapter in this tutorial covers that decision in detail. For now, remember that what you write decides what you can ever retrieve.
Key points
- LLM calls are stateless. Long-term memory is external storage that your code searches and injects into the prompt.
- A record needs text, an owner, a kind, an embedding, and a timestamp.
- Retrieval returns top-k by similarity, so add a threshold to avoid injecting noise.
- Filter by user inside the store itself.
- Injected memories use up the same token budget as conversation history.
Exercise
A user tells the agent in session 1 that they are allergic to peanuts. In session 3, the agent suggests a peanut sauce. The fact was saved correctly with the right user_id. Name two retrieval-side causes that could explain the miss, and one fix for each.
Show answer
First, the search may have ranked the allergy memory below the top k results because the query ("suggest a sauce for dinner") is not similar to the stored text, so a larger k, a rewritten query, or a rule that always injects safety-related facts would fix it. Second, the embedding model may have changed since the memory was written, so old and new vectors are not comparable. The fix is to store the embedding model name with each record and re-embed old records after a switch. (A third valid cause is that injected memories were dropped because the prompt exceeded the token budget, fixed by reserving space for the memory block.)
Exercise
In MemoryStore.search, what would go wrong if you sorted all items by similarity first and filtered by user_id afterwards, taking only the top k before filtering?
Show answer
Other users' records could fill the top k slots. After filtering, the current user might get fewer than k results, or none, even though they have relevant memories. It also means the similarity work runs over other users' data, which is wasteful and widens the chance of a leak if the filter is ever skipped. Filtering first and then ranking avoids both problems.
Exercise
Modify search to accept a min_score argument (default 0.2) and return only memories whose cosine similarity to the query is at least that value. Write the new method body.
Show answer
def search(self, userid, query, k=3, minscore=0.2): q = self.embed(query) own = [m for m in self.items if m["userid"] == userid] scored = [(cosine(q, m["vec"]), m) for m in own] scored = [(s, m) for s, m in scored if s >= minscore] scored.sort(key=lambda pair: pair[0], reverse=True) return [m for , m in scored[:k]]