Lesson 4 of 5 · Memory
Long-Term Memory With Vector Stores
Give an AI agent memory across sessions: save facts with embeddings and metadata, recall them by similarity, filter by user and expose memory as tools.
- 8 min read
- Intermediate
- Reviewed
- Explain how a vector store gives an agent memory across sessions
- Save memories with embeddings and metadata such as the user and date
- Recall only relevant memories, for the right user, above a score threshold
- Choose between writing memories during the conversation or in the background
Memory that outlives the conversation
Short-term memory ends when the session ends. To remember Mei's allergy next month, the agent has to write it somewhere outside the model and look it up again later.
You could put every remembered fact into every prompt, but after a few months there might be hundreds. Instead, agents store memories in a vector store and, for each new message, fetch only the few that are relevant. It's the same retrieval idea as RAG (see the Embeddings and Vector Databases courses), applied to what the agent has learned about a user or task.
Save, recall, use
The loop has three steps:
- Save: turn a memory into an embedding and store it with metadata: who it belongs to, when it was saved, what kind of memory it is.
- Recall: when a new message arrives, embed it and search the store, only within this user's memories, keeping the top matches above a score threshold.
- Use: add the recalled memories to the prompt, clearly labelled.
The demo uses a tiny see-inside embedding with one dimension per topic, so you can follow every score. A real agent uses an embedding model, but the steps are identical:
import math, re
# ---- A tiny see-inside embedding: one dimension per topic (real agents use an embedding model) ----
TOPICS = {
"food": "food eat eating dinner lunch restaurant recipe allergic allergy peanuts vegetarian meat cook",
"place": "live lives city lyon move moved home address near",
"work": "job work works analyst manager team cv cover letter interview salary",
"family": "daughter son partner kids family birthday",
"sport": "run running marathon training gym bike cycling",
}
VOCAB = {t: set(w.split()) for t, w in TOPICS.items()}
def embed(text):
words = re.findall(r"[a-z]+", text.lower())
v = [sum(w in VOCAB[t] for w in words) for t in TOPICS]
n = math.sqrt(sum(x * x for x in v))
return [x / n for x in v] if n else v
def cosine(a, b):
return sum(x * y for x, y in zip(a, b))
class LongTermMemory:
def __init__(self):
self.items = [] # each memory: text, vector, user, when it was saved
def save(self, user, text, day):
self.items.append({"user": user, "text": text, "vec": embed(text), "day": day})
def recall(self, user, query, k=3, min_score=0.3):
q = embed(query)
scored = [(cosine(q, m["vec"]), m) for m in self.items if m["user"] == user] # only THIS user's memories
scored = [(s, m) for s, m in scored if s >= min_score] # drop weak matches
return sorted(scored, key=lambda x: -x[0])[:k]
memory = LongTermMemory()
# Facts saved during earlier conversations, weeks apart
memory.save("mei", "Mei is allergic to peanuts.", day=1)
memory.save("mei", "Mei is vegetarian and likes to cook at home.", day=3)
memory.save("mei", "Mei lives in Lyon.", day=3)
memory.save("mei", "Mei works as a data analyst and wants a manager job.", day=9)
memory.save("mei", "Mei is training for a marathon in April.", day=14)
memory.save("tom", "Tom is allergic to shellfish.", day=2) # a different user
for query in ["Can you suggest a restaurant near home for dinner on Friday?",
"Help me write a cover letter for a new job.",
"What's the capital of Australia?"]:
print("New session:", query)
hits = memory.recall("mei", query)
for score, m in hits:
print(f" {score:.2f} {m['text']}")
if not hits:
print(" (no relevant memories, so nothing is added to the prompt)")
# Recalled memories go into the prompt as context, clearly labelled
query = "Can you suggest a restaurant near home for dinner on Friday?"
notes = "\n".join(f"- {m['text']}" for _, m in memory.recall("mei", query))
print()
print(f"System: You are Mei's assistant. What you remember about her:\n{notes}")The restaurant question recalls the diet, the allergy and the city; the cover letter recalls the job; the general-knowledge question recalls nothing, so the prompt stays clean. Tom's shellfish allergy is never considered, because recall filters by user before comparing.
The same thing with a real vector store
Here's the same design with Chroma, which embeds the text for you with its default embedding model:
import chromadb, uuid
client = chromadb.PersistentClient(path="./agent_memory") # memories survive restarts
memories = client.get_or_create_collection("memories")
def remember(user_id, text):
memories.add(ids=[str(uuid.uuid4())], documents=[text],
metadatas=[{"user_id": user_id}])
def recall(user_id, query, k=3, max_distance=1.0):
res = memories.query(query_texts=[query], n_results=k,
where={"user_id": user_id}) # never mix users' memories
return [doc for doc, dist in zip(res["documents"][0], res["distances"][0])
if dist <= max_distance] # drop weak matches
remember("mei", "Mei is allergic to peanuts.")
remember("mei", "Mei lives in Lyon.")
print(recall("mei", "Suggest a restaurant for Friday"))The where filter limits the search to one user's memories. Chroma returns distances rather than similarities (smaller is closer). With its default settings and normalised embeddings, a distance of 1.0 corresponds to a cosine similarity of 0.5, so the cut-off above keeps reasonably close matches. Tune the threshold on your own data.
When does the agent write memories?
There are two common designs, and many systems use both:
| In the conversation | In the background | |
|---|---|---|
| How | The agent has a save_memory tool and decides when to call it | After the session, a separate job reads the transcript and extracts memories |
| Good for | Things the user explicitly asks to remember | Catching facts nobody flagged |
| Downsides | Adds steps and delay to replies; the agent may forget to save | Memories aren't available until the job runs |
Giving the agent memory tools (save_memory, search_memory) also lets it search on purpose, for example “search memories for the user's travel preferences” before booking a trip, instead of relying only on automatic recall.
Common mistakes
Write the recall step of a long-term memory: keep only this user's memories that pass the score threshold, and return the best k.
# Similarity scores already computed for the query "plan my weekend run"
scored = [
("mei", "Mei is training for a marathon.", 0.92),
("tom", "Tom runs every Sunday.", 0.88),
("mei", "Mei's knee hurts after long runs.", 0.74),
("mei", "Mei lives in Lyon.", 0.41),
("mei", "Mei likes cycling.", 0.55),
]
user, k, min_score = "mei", 2, 0.5
# Recall the top k memories for this user only, with score >= min_score,
# best first, and print each text on its own line.
Where should the filter that limits recall to the current user be applied?
Summary
- Long-term memory lives outside the model, usually in a vector store, so it survives across sessions.
- The loop is save (embedding plus metadata), recall (similar memories for this user, above a threshold) and use (labelled in the prompt).
- Always filter by user inside the search, and store metadata such as time, type and source.
- Write memories during the conversation with a tool, in the background after it, or both.
Next: deciding what to remember, and what to forget.
Finished reading? Tick it off to track your progress.