Sub topic 9
Embeddings and similarity search
This chapter assumes you can read basic Python, know what a vector is (a list of numbers), and have seen the MemoryStore idea from the long-term memory chapters. It covers how a memory store decides which saved memories are relevant to the current input.
Why keyword matching is not enough
A long-term store may hold hundreds of memories, and only a few belong in the prompt. The agent needs a way to ask: "Which saved memories relate to what the user just said?"
Keyword matching is the obvious first answer, and it fails often. Suppose the store holds "User is vegetarian" and the user asks "What should I cook for dinner?". The two texts share no words, but the first fact matters a great deal for the answer.
An embedding is a list of numbers (a vector) produced by a trained model. The model is trained so that texts with similar meaning get vectors that point in similar directions. Retrieval then becomes geometry: embed the query, embed the memories, and rank memories by how close their vectors are to the query vector.
The pipeline
Both sides must use the same embedding model. Vectors from two different models live in unrelated spaces, so comparing them gives meaningless scores.
Measuring closeness
Three measures are common.
| Measure | What it computes | Higher score means | Notes |
|---|---|---|---|
| Cosine similarity | Angle between vectors | More similar | Ignores vector length. Range -1 to 1. |
| Dot product | Sum of element products | More similar | Equals cosine when vectors have length 1. |
| Euclidean distance | Straight-line distance | More distant (lower is closer) | Sensitive to vector length. |
Cosine similarity is the usual default for text. Its formula is the dot product divided by the product of the two vector lengths. Many embedding providers return vectors already scaled to length 1. For those, dot product and cosine give the same ranking, and the dot product is cheaper to compute.
What keyword overlap gets wrong
The next example uses a word-count vector, which is not a real embedding. It shows the failure that real embeddings fix.
import math
import re
VOCAB = ["vegetarian", "vegan", "meat", "dinner", "cook",
"python", "code", "dog", "walk"]
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
def word_count_vector(text):
"""Count how often each vocabulary word appears. Not a real embedding."""
words = re.findall(r"[a-z]+", text.lower())
return [float(words.count(w)) for w in VOCAB]
memories = [
"User is vegetarian",
"User likes dinner at 7pm",
]
query = "What should I cook for dinner?"
q = word_count_vector(query)
for text in memories:
print(round(cosine(q, word_count_vector(text)), 2), text)The output is:
0.71 User likes dinner at 7pm
0.0 User is vegetarianBoth the query and the dinner-time memory contain "dinner", so that memory wins. The vegetarian memory shares no words with the query, so it scores zero. A real embedding model maps "vegetarian" and "cook for dinner" into nearby regions, because the two ideas often appear together in training text.
Real embeddings
This version uses the sentence-transformers library. Install it with pip install sentence-transformers numpy. The first run downloads a small model.
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
memories = [
"User is vegetarian",
"User likes dinner at 7pm",
"User is learning Rust",
]
# normalize_embeddings=True gives unit-length vectors, so dot product == cosine
matrix = model.encode(memories, normalize_embeddings=True) # shape (3, 384)
def search(query, k=2, min_score=0.2):
q = model.encode([query], normalize_embeddings=True)[0]
scores = matrix @ q # one score per memory
order = np.argsort(scores)[::-1][:k] # best first
return [(float(scores[i]), memories[i]) for i in order
if scores[i] >= min_score]
for score, text in search("What should I cook for dinner?"):
print(round(score, 2), text)Exact scores depend on the model version, so do not hard-code them in tests. The vegetarian memory should now rank well above the Rust memory. The matrix @ q line scores every memory in one operation. This approach is called brute-force search, and it is fast enough for thousands of memories.
Choices that affect quality
The similarity threshold
Top-k always returns k results, even when nothing is relevant. If the user says "Hello", the k nearest memories are still the k least-unrelated ones, and injecting them adds noise or confuses the model. A minimum score, like min_score above, lets the search return fewer than k results, or none.
There is no universal threshold. Scores depend on the model, so pick a value by looking at scores for known relevant and irrelevant pairs from your own data.
What text you embed
The vector represents the text you give it. A memory saved as "He said yes" has no usable meaning on its own. Write memories as short, self-contained statements, such as "Priya approved the Q3 budget on 12 May". This is a write-time decision, and it limits retrieval quality later.
Queries and memories also differ in form. A query is often a question or a fragment, and a memory is a statement. Embedding models handle this reasonably well, but some models expect a prefix or a separate query mode. Check the model's documentation.
Keeping the model fixed
Store the model name alongside each vector. If you switch models, every stored vector must be re-embedded from its original text, so keep the text. A stored vector without its source text cannot be migrated.
Scale
Brute-force search compares the query with every vector, so cost grows linearly with store size. Beyond roughly hundreds of thousands of vectors, stores use approximate nearest neighbor (ANN) indexes. These return results that are nearly the best, in exchange for much faster lookups. Vector databases provide this.
Per-user filtering
Search only the requesting user's memories. In the MemoryStore code, search filters by user_id before ranking. Similarity search has no sense of ownership, so skipping the filter can return another user's closest memory.
Common errors
- Mixing models. Memories embedded with one model and queries with another produce scores that look valid but mean nothing.
- Comparing unnormalized vectors with a dot product. Longer vectors score higher regardless of meaning. Normalize, or use cosine.
- Treating similarity as truth. A high score means the texts are related, not that the memory is correct or current. "User lives in Paris" and "User moved to Berlin" can both score high for a question about where the user lives.
- Embedding on every search. Embed each memory once, at write time, and store the vector. Only the query needs a fresh embedding.
- Ignoring zero vectors. The
cosinefunction returns 0.0 when a vector has zero length, which avoids a division by zero.
Exercises
Exercise
Why can top-k retrieval without a score threshold harm the agent's answers, and how do you fix it?
Show answer
Top-k always returns k memories, even when none relate to the input. The least-unrelated memories then get added to the prompt, adding noise and possibly leading the model to use irrelevant facts. Add a minimum similarity score so the search can return fewer than k results, or none. Choose the threshold by checking scores on known relevant and irrelevant examples from your own data.
Exercise
You change your embedding model from model A to model B. You kept the memory text and the old vectors. What must you do, and why?
Show answer
Re-embed every memory's text with model B and replace the stored vectors. Vectors from different models are in unrelated spaces, so comparing a model B query vector with model A vectors gives meaningless scores. The old vectors cannot be converted, which is why the original text must be kept.