Sub topic 3
Retrieving and Ranking Relevant Memories
Assume you know basic Python, chat-style LLM APIs, and vector similarity. This chapter focuses on reading stored memories and adding useful results to an agent prompt.
Retrieving and Ranking Memories
A memory store usually contains text, an owner, a type, and an embedding. An embedding is a vector that represents the meaning of text. Retrieval converts the current user input into a vector, compares it with stored vectors, and returns the highest-scoring matches.
Cosine similarity is a common score. It measures how closely two vectors point in the same direction. Higher scores usually indicate more relevant memories.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
size_a = math.sqrt(sum(x * x for x in a))
size_b = math.sqrt(sum(x * x for x in b))
return dot / (size_a * size_b) if size_a and size_b else 0.0
def retrieve(items, user_id, query_vector, k=3):
owned = [item for item in items if item["user_id"] == user_id]
ranked = sorted(
owned,
key=lambda item: cosine(query_vector, item["vector"]),
reverse=True,
)
return ranked[:k]
items = [
{"user_id": "u1", "text": "Prefers Python examples",
"vector": [1.0, 0.0]},
{"user_id": "u1", "text": "Uses PostgreSQL",
"vector": [0.8, 0.2]},
{"user_id": "u2", "text": "Prefers Java examples",
"vector": [0.0, 1.0]},
]
print(retrieve(items, "u1", [0.9, 0.1], k=2))Similarity alone can produce poor results. Add filters for memory type, age, confidence, or required keywords. A recent explicit preference may deserve a higher score than an old inference.
Putting Memory into the Agent Loop
The agent retrieves memories before each LLM call. It places selected memories in a clearly labeled system-message section, then adds the current conversation. The complete prompt must still fit the context budget.
Scoping Memory by User and Session
Always filter by an authenticated user_id before ranking. A session_id can restrict short-term conversation history while long-term facts remain available across sessions. Never trust an identifier supplied only in prompt text.
Updating, Deduplicating, and Forgetting
Update a memory when the user clearly corrects it. Deduplicate equivalent records before retrieval. Add expiration dates to temporary facts, and support explicit deletion. Keeping stale memories can be worse than having no memory.
Privacy and Safety
Store only information that improves the service. Encrypt sensitive data, restrict access by tenant and user, log access without logging secret content, and provide inspection and deletion controls. Do not store passwords, access tokens, or unnecessary sensitive attributes.
Testing Whether Memory Helps
Compare two versions of the agent: one with memory and one without it. Use the same test conversations and measure correct personalization, retrieval precision, stale-memory errors, privacy violations, and token cost.
Exercise
A retrieved preference conflicts with the user's current request. Which should the agent follow?
Show answer
The current request should win. Treat stored memory as a fallible hint, not as an instruction.