Sub topic 9
Embeddings and Similarity Search
This chapter assumes you know basic Python, have seen vectors (lists of numbers), and have built the MemoryStore outline from the previous chapters. Here you will see how that store decides which memories are "similar" to a query.
Why keyword matching is not enough
A user once said, "I'm allergic to peanuts." Later they ask, "Can you suggest a snack?" The two sentences share no important words, yet the first matters a lot to the second. Keyword search would miss it. Embeddings solve this.
An embedding is a list of numbers (a vector) that represents the meaning of a piece of text. An embedding model produces it. Texts with similar meaning get vectors that point in similar directions.
Comparing vectors with cosine similarity
Cosine similarity measures the angle between two vectors. It ranges from -1 to 1. A value near 1 means the vectors point the same way, so the meanings are close. A value near 0 means they are unrelated.
The cosine function in the memory store computes it:
import math
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
print(cosine([1, 0], [1, 0])) # 1.0, same direction
print(cosine([1, 0], [0, 1])) # 0.0, unrelated
print(cosine([1, 1], [2, 2])) # about 1.0, length is ignoredThe last line shows why cosine is popular. It ignores vector length and compares direction only.
The search flow
Search has four steps. The store embeds the query with the same model used at write time. It filters to the current user's memories. It scores each memory against the query. It returns the top k.
A runnable example
Real embedding models return hundreds of numbers. This toy version uses a tiny hand-made embedding so you can run the code without an API. The dimensions are food, animals, and travel.
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
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]
def toy_embed(text):
words = text.lower().split()
food = sum(w in {"peanuts", "snack", "allergic", "pizza"} for w in words)
animals = sum(w in {"dog", "cat", "walk"} for w in words)
travel = sum(w in {"paris", "flight", "trip"} for w in words)
return [food, animals, travel]
store = MemoryStore(toy_embed)
store.write("priya", "allergic to peanuts")
store.write("priya", "has a dog")
store.write("priya", "flight to paris")
for m in store.search("priya", "suggest a snack", k=1):
print(m["text"])The query "suggest a snack" matches "allergic to peanuts" because both land in the food dimension.
Common errors
- Mixing models. Vectors from different embedding models are not comparable. Use one model for writing and searching, and re-embed everything if you change it.
- Always returning k results. Top-k returns something even when nothing is relevant. Add a minimum score threshold.
- Slow scans. The loop above compares against every memory. Past a few thousand items, use a vector index (approximate nearest neighbor search).
- Skipping the user filter. Without it, one user's memories can appear in another user's prompt.
Exercise
A query returns k=3 memories, but the best cosine score is 0.05. What should the agent do, and why?
Show answer
Add a minimum score threshold and drop results below it, so the prompt gets no memories instead of irrelevant ones. Top-k always returns k items, even when none are relevant, and unrelated memories add noise and can mislead the model.