Sub topic 2
Long-term memory: persisting beyond one session
Assume you know basic Python, can call a chat-style LLM API, and understand vectors and similarity. An LLM call is stateless: after it returns, it does not remember the call. Long-term memory is data that your application stores outside the model and retrieves in a later session.
What long-term memory stores
A memory usually contains text, a type, an owner, a creation time, and sometimes an embedding. An embedding is a vector that represents the meaning of text.
| Memory type | What it records | Example |
|---|---|---|
| Episodic | A specific event | “Priya asked for help deploying version 2.” |
| Semantic | A stable fact | “Priya uses Python.” |
| Procedural | A preferred method | “Show Priya examples before theory.” |
Storage and retrieval
Use a key-value store for exact lookup, such as a user’s preferred language. Use a document store for richer records and metadata. Use a vector store when the query and memory may use different words but share meaning.
An embedding model converts both a stored memory and a query into vectors. Similarity search ranks stored vectors, often with cosine similarity. The agent then places the highest-ranked, properly scoped memories into its prompt.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(x * x for x in b))
return dot / (na * nb) if na and nb else 0.0
class MemoryStore:
def __init__(self, embed):
self.embed, self.items = embed, []
def write(self, user_id, text, kind="semantic"):
self.items.append({
"user_id": user_id, "text": text, "kind": kind,
"vector": self.embed(text)
})
def search(self, user_id, query, limit=3):
q = self.embed(query)
matches = [m for m in self.items if m["user_id"] == user_id]
return sorted(matches,
key=lambda m: cosine(q, m["vector"]),
reverse=True)[:limit]Deciding what to remember
Write information when it is likely to help across sessions, is explicit, and has a clear owner. Prefer stable preferences, recurring goals, and confirmed facts. Avoid saving every conversational detail. Do not store secrets or sensitive data unless there is a clear need, consent, and suitable protection.
Exercise
Which storage approach fits a memory such as “The user prefers concise answers”?
Show answer
Store it as a structured or document record, optionally with an embedding for semantic retrieval.