Sub topic 9
Retrieving the top-k passages
This chapter assumes you can read basic Python, know what an embedding vector is, and understand cosine similarity as a normalized dot product. Retrieval is the step that turns a user question into a short list of passages for the prompt.
What retrieval does
At query time, the system embeds the question with the same model used for the chunks. It scores the question vector against the stored chunk vectors and keeps the k highest-scoring chunks. These are the top-k passages.
Exact top-k search
For a small collection, you can score every vector. This is exact search, and it is the baseline that approximate indexes try to match.
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(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
def top_k(query_vec, index, k=3):
# index is a list of (text, vector) pairs
scored = [(cosine(query_vec, vec), text) for text, vec in index]
scored.sort(key=lambda pair: pair[0], reverse=True)
return scored[:k]The cost is one similarity computation per stored chunk, so it grows linearly with the collection. Past a certain size, an approximate index replaces the full scan and returns nearly the same results faster.
Choosing k
The value of k trades recall against noise.
| Choice | Effect |
|---|---|
| k too small | The needed passage may be missing, and the model cannot answer. |
| k too large | Irrelevant text fills the prompt, which raises cost and can distract the model. |
A common starting point is 3 to 5 passages. If a reranker follows (a later chapter), retrieve more, such as 20 to 50, and let the reranker cut the list down.
Metadata filtering
Each chunk can carry metadata such as source, date, language, or the team that owns it. A filter restricts the search to chunks whose metadata matches, before or during scoring. For example, you might search only documents from the current product version.
def top_k_filtered(query_vec, index, k=3, **required):
# index is a list of (text, vector, metadata) triples
allowed = [
(text, vec)
for text, vec, meta in index
if all(meta.get(key) == value for key, value in required.items())
]
return top_k(query_vec, allowed, k)Calling top_k_filtered(q, index, k=3, version="2.0") ranks only chunks tagged with version 2.0. Filtering before ranking guarantees you get k results that match. If you filter after taking the top k, you may end up with fewer than k, or none.
Common errors
- Mismatched embedding models. The query and the chunks must come from the same model. Vectors from different models are not comparable.
- No score threshold. Top-k always returns k results, even when none are relevant. Consider a minimum similarity so the system can say it found nothing.
- Duplicates. Overlapping chunks can fill the top k with near-identical text. Remove duplicates or merge neighbors.
- Post-filtering. As noted above, filter first, then rank.
Exercise
A query returns 5 chunks, but 3 of them are near-duplicates from overlapping windows of the same section. Name two ways to fix this.
Show answer
Retrieve more than 5 candidates and remove near-duplicate chunks before keeping 5, or merge adjacent chunks from the same section into one passage. Reducing chunk overlap also lowers the number of duplicates.
Exercise
Why is filtering by metadata after taking the top k riskier than filtering before?
Show answer
The top k may contain few or no chunks that pass the filter, so you can end up with fewer than k results or none. Filtering first ranks only eligible chunks, so all k results match.