Sub topic 2
Measuring Similarity and Finding Nearest Neighbors
Assume you know basic Python, vector dot products, API responses, and how embeddings represent text. This chapter focuses on choosing and ordering passages after documents have been embedded.
Measuring similarity
An embedding is a numeric vector representing a passage. Similar passages usually have vectors pointing in similar directions. Cosine similarity measures that alignment:
\[ \text{cosine}(a,b)=\frac{a\cdot b}{\|a\|\|b\|} \]
A value near 1 means strong similarity. A value near 0 means little similarity. The value is less useful when either vector has zero length.
Finding nearest neighbors
Given a query vector, exact search compares it with every stored vector and sorts the results. This is simple and accurate, but its work grows with the number of passages.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
length_a = math.sqrt(sum(x * x for x in a))
length_b = math.sqrt(sum(y * y for y in b))
return dot / (length_a * length_b) if length_a and length_b else 0.0
def top_k(query, passages, k=3):
scored = [(cosine(query, vector), text)
for text, vector in passages]
scored.sort(reverse=True)
return scored[:k]Approximate nearest-neighbor indexes
An approximate nearest-neighbor (ANN) index avoids checking every vector. It explores a smaller set of likely candidates, so searches are faster and use less compute. The trade-off is recall: the index might miss a truly relevant passage.
Index settings often control this balance. Searching more candidates improves recall but increases latency. Measure both before choosing a setting.
Retrieving top-k passages
Top-k retrieval returns the best k passages for the query. A small k reduces prompt size and latency. A large k may improve coverage but can add irrelevant text and confuse generation. Tune k using a validation set rather than guessing.
Combining keyword and vector search
Vector search captures meaning. Keyword search is often better for exact names, identifiers, error codes, and product terms. Hybrid search combines their rankings. Reciprocal rank fusion adds a score based on each document’s position, so the raw scores do not need to match.
Reranking retrieved passages
A reranker examines the query and a small candidate set together, often with a more expensive model. It can reorder initially retrieved passages before they enter the prompt. This improves precision, but adds latency and cost. Use it when the first-stage search finds relevant candidates but places them in the wrong order.
Exercise
Why might an ANN index return a less relevant passage than exact search?
Show answer
It searches only selected candidates to reduce latency, so it can miss the true nearest neighbor.