Sub topic 1
Recap: embeddings and vector search
Agentic RAG builds on a small set of retrieval ideas. This chapter refreshes them, with attention to the behaviors that matter once a model starts choosing its own searches. Later chapters assume you know this material.
Prerequisites
This chapter assumes you have:
- Basic Python: functions, lists, dictionaries and comprehensions.
- A working idea of what an LLM prompt and completion are.
- A high-level picture of a retrieve-then-generate pipeline, where text is fetched and pasted into a prompt.
You do not need linear algebra beyond "a vector is a list of numbers".
What an embedding is
An embedding is a list of numbers (a vector) that represents a piece of text. An embedding model produces it. The model is trained so that texts with similar meaning get vectors that point in similar directions.
Real embedding models produce vectors with hundreds or thousands of dimensions. The individual numbers have no human-readable meaning. Only the relationships between vectors carry information.
Three properties of embeddings matter for the rest of this tutorial:
- They are fixed per model. Vectors from different models are not comparable. If you change the embedding model, you must re-embed every document.
- They capture topic, not truth. A passage that mentions a topic lands near a question about that topic, whether or not the passage answers the question.
- They compress. A long passage becomes one vector, so fine details such as exact version numbers, negations and identifiers can get blurred.
Measuring similarity
Search compares the query vector with stored document vectors. The most common measure is cosine similarity, which is the cosine of the angle between two vectors. It ranges from -1 to 1. A higher value means the vectors point in more similar directions, and the length of the vectors is ignored.
Two other measures appear often:
| Measure | What it compares | Notes |
|---|---|---|
| Cosine similarity | Direction only | Common default for text embeddings |
| Dot product | Direction and length | Equals cosine if vectors are normalized to length 1 |
| Euclidean distance | Straight-line gap | Lower is closer, so the sort order is reversed |
Check which measure your embedding model was trained for and use that one. For normalized vectors, all three give the same ranking.
The indexing and query flow
Vector search has two phases. Indexing happens once, offline, and again whenever documents change. Querying happens on every search.
The query must be embedded with the same model that embedded the chunks. This is a common source of silent bugs after a model upgrade.
Chunking
Documents are split into chunks before embedding, because one vector for a whole manual would be too vague to match a specific question. Chunks are often a few hundred tokens, sometimes overlapping so a sentence cut at a boundary still appears whole in one chunk.
Chunk size is a trade-off:
- Small chunks match precisely but may lack the surrounding context needed to answer.
- Large chunks keep context but dilute the vector, and they use more of the prompt when retrieved.
Whatever you choose, give each chunk a stable id. Later chapters rely on ids so the model can cite exactly which passage supports a claim.
Search in code
The following program implements the core of vector search with no libraries. The three-dimensional vectors are made up by hand so the result is easy to check. Read the dimensions as roughly "billing", "security" and "setup".
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)
index = {
"refund-policy": [0.9, 0.1, 0.1],
"password-reset": [0.1, 0.9, 0.2],
"install-guide": [0.1, 0.2, 0.9],
}
def search(query_vector, k=2):
scored = [(chunk_id, cosine(query_vector, vec)) for chunk_id, vec in index.items()]
scored.sort(key=lambda pair: pair[1], reverse=True)
return scored[:k]
# Pretend this is the embedding of "how do I get my money back"
query_vector = [0.8, 0.2, 0.1]
for chunk_id, score in search(query_vector):
print(f"{chunk_id}: {score:.2f}")Running it prints:
refund-policy: 0.99
password-reset: 0.36The query contains none of the words "refund" or "policy", yet the refund chunk wins. That is the strength of embeddings: they match meaning, not exact words.
Exact and approximate search
The code above compares the query with every stored vector. This is exact search, also called brute force. Its cost grows linearly with the number of chunks. It is fine for thousands of chunks and often acceptable for hundreds of thousands.
For larger collections, vector databases use approximate nearest-neighbor (ANN) indexes. Common families include graph-based indexes such as HNSW and clustering-based indexes such as IVF. They skip most of the collection and return neighbors that are very likely, but not guaranteed, to be the true closest ones. The measure of this is recall: the fraction of the true top-k that the index actually returns.
Two practical consequences follow:
- ANN settings trade speed against recall. A search that misses a relevant chunk because of ANN settings looks identical to a search where the chunk does not exist.
- Results may differ slightly between runs or after the index is rebuilt.
Behaviors that matter for agents
Classic RAG hides several properties of vector search because a fixed pipeline never inspects them. An agent that searches repeatedly will run into each one.
- Scores are not calibrated. A cosine score of 0.8 means different things for different models and different queries. A fixed threshold can work for one query and fail for another, so treat scores as a ranking, not as a probability of relevance.
- Query wording changes results. A vague, pronoun-heavy query such as "what about the second one?" has no meaning on its own. Embedding it produces a vector near nothing useful. Queries need to be self-contained.
- Exact strings are weak spots. Error codes, product names, ticket numbers and version strings often match poorly. Many systems add keyword search (such as BM25) next to vector search and merge the two ranked lists. This is called hybrid search.
- Multi-part questions blur. A question about two separate topics yields a vector between the two, which may match neither well.
- Negation and qualifiers are fragile. "Which plans do not include SSO?" often retrieves passages about plans that do include SSO.
- Retrieval returns text, not answers. The chunk is evidence. A model still has to read it and decide whether it answers the question.
These are the failure modes that the next chapters address, first by looking at how classic RAG uses retrieval and then by moving the decision of what to search for from the pipeline to the model.
Key points to carry forward
- An embedding maps text to a vector, and nearby vectors mean similar topics.
- Search ranks stored chunks by similarity to the query vector and returns the top k.
- Chunks need stable ids, and the same embedding model must be used for indexing and querying.
- Search always returns something, so "found" does not mean "relevant".
- The query text determines the result, which is why who writes the query becomes an important design question.
Exercise
A user asks a support bot, "Does the Pro plan include audit logs?" Your vector search returns the top 3 chunks, and the best one has a cosine score of 0.62. Give two reasons you cannot conclude from the score alone that the chunk answers the question, and name one change that would help with an exact term such as "SSO-4012".
Show answer
First, scores are not calibrated: 0.62 may be high for one embedding model and low for another, so it is only meaningful as a ranking among the results. Second, embeddings capture topic similarity, not whether a passage answers the question. The chunk might discuss the Pro plan or audit logs without stating whether the Pro plan includes them, and top-k search returns the best available chunks even when none is relevant. For exact terms such as "SSO-4012", add keyword search (for example BM25) alongside vector search and merge the results, which is hybrid search.
Exercise
You switch to a new embedding model but only re-embed the new documents, leaving the old chunk vectors in the index. What goes wrong, and what is the fix?
Show answer
Vectors from different models live in different spaces, so similarity between a new-model query vector and old-model chunk vectors is meaningless. Results will be poor and may look plausible. The fix is to re-embed every chunk with the new model (and embed queries with it too), then rebuild the index.