Sub topic 1
Recap: embeddings and vector search
Prerequisites
This chapter assumes you know basic Python and what an LLM prompt and completion are. You should also have a high-level idea of a retrieve-then-generate pipeline. Nothing here is new material. It fixes the vocabulary that later chapters use when the model starts calling retrieval as a tool.
What an embedding is
An embedding is a list of numbers (a vector) that represents a piece of text. An embedding model produces it. Texts with similar meaning get vectors that point in similar directions, even when they share few words. "How do I reset my password?" and "I forgot my login credentials" end up close together.
You embed each document chunk once, ahead of time, and store the vectors in an index. At query time you embed the question with the same model and look for the nearest chunk vectors.
Measuring closeness
The most common measure is cosine similarity. It compares the angle between two vectors and ignores their length. A score near 1 means the vectors point the same way. A score near 0 means the texts are unrelated.
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)
def top_k(query_vector, index, k=3):
# index: list of {"id": str, "text": str, "vector": list[float]}
scored = [(cosine(query_vector, item["vector"]), item) for item in index]
scored.sort(key=lambda pair: pair[0], reverse=True)
return [item for _, item in scored[:k]]
index = [
{"id": "a", "text": "Reset a password", "vector": [0.9, 0.1, 0.0]},
{"id": "b", "text": "Billing limits", "vector": [0.0, 0.2, 0.9]},
{"id": "c", "text": "Recover an account", "vector": [0.8, 0.3, 0.1]},
]
for item in top_k([0.85, 0.2, 0.05], index, k=2):
print(item["id"], item["text"])The vectors here have three numbers so you can read them. Real embedding models produce hundreds or thousands of dimensions.
Vector search in practice
The code above compares the query with every vector. That is exact, but it slows down as the index grows. Production systems use approximate nearest neighbor (ANN) indexes, which trade a small loss in recall for much faster lookups.
What to remember
- Similarity is not correctness. The nearest chunk may be on topic and still not contain the answer.
- The query and the chunks must use the same embedding model.
- Search returns the k best matches even when none is good. A top-k result never says "nothing found" by itself.
- Chunk size matters. Chunks that are too large blur several topics into one vector. Chunks that are too small lose context.
Exercise
A user asks a question about a topic your documents never cover. Vector search still returns k chunks. Why, and what does that imply for a pipeline that passes them straight to the model?
Show answer
Nearest-neighbor search ranks all chunks and returns the k closest, whatever their absolute similarity. It has no built-in "no match" result. A pipeline that passes the chunks to the model unchecked gives the model irrelevant context, which can lead to a confident but unsupported answer. You need a similarity threshold, a grading step, or an instruction to say when the context lacks the answer.