Sub topic 7
Inside a retrieval pipeline
This chapter opens the retrieval step of RAG and shows what happens between a user's question and the passages that reach the prompt. It assumes you have called a chat-style LLM API, can read Python, and know what an embedding and a context window are. It does not cover the decision of whether to use RAG. Earlier chapters cover that.
The two phases of a pipeline
A retrieval pipeline has an offline phase and an online phase.
- Indexing (offline): load documents, split them into chunks, embed each chunk, and store the text with its vector.
- Querying (online): embed the question, rank stored chunks by similarity, select the best few, and place them in the prompt.
Most quality problems come from the indexing phase, because the query phase can only return what indexing stored.
Chunking
A chunk is a piece of a document that is embedded and retrieved as one unit. You chunk because embedding models have input limits, and because one vector for a whole document blurs many topics together.
Chunk size is a trade-off:
| Choice | Benefit | Risk |
|---|---|---|
| Small chunks (about 100 to 200 tokens) | Precise matches, cheap prompts | A chunk may lack the context needed to answer |
| Large chunks (about 800 to 1000 tokens) | Each chunk is self-contained | The vector blurs topics, and the prompt fills quickly |
Common practices:
- Split on structure first. Break at headings, paragraphs, or list items before falling back to a fixed token count. A chunk that ends mid-sentence is harder to embed well.
- Use overlap. Repeat 10 to 20 percent of the previous chunk at the start of the next one. A fact that straddles a boundary then appears whole in at least one chunk.
- Attach metadata. Store the source file, section title, and date with each chunk. You need them for citations, filtering, and debugging.
- Keep the section title in the text. A chunk that says "The limit is 30 days" is ambiguous. "Refund policy: the limit is 30 days" is not.
Here is a simple chunker that splits on paragraphs and packs them up to a size limit. It counts words as a rough stand-in for tokens.
def chunk_text(text, max_words=120, overlap_words=20):
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
chunks = []
current = []
count = 0
for para in paragraphs:
words = para.split()
if current and count + len(words) > max_words:
chunks.append(" ".join(current))
# start the next chunk with the tail of the previous one
tail = " ".join(current).split()[-overlap_words:]
current = [" ".join(tail)]
count = len(tail)
current.append(para)
count += len(words)
if current:
chunks.append(" ".join(current))
return chunks
doc = (
"Refund policy\n\nCustomers may request a refund within 30 days of purchase.\n\n"
"Refunds are issued to the original payment method.\n\n"
"Shipping\n\nOrders ship within two business days."
)
for i, c in enumerate(chunk_text(doc, max_words=20, overlap_words=5)):
print(i, c)A paragraph longer than max_words becomes one oversized chunk in this version. A production splitter would break it further.
Embeddings
An embedding is a vector of numbers that represents the meaning of a text. Texts with similar meaning get vectors that point in similar directions. An embedding model produces these vectors.
Rules that prevent common errors:
- Use the same model for chunks and queries. Vectors from different models live in different spaces and cannot be compared.
- Record the model name and version with the index. If you change models, re-embed everything.
- Respect the input limit. Text beyond the limit is usually truncated without an error, so the end of a long chunk is silently ignored.
- Check whether the model expects a prefix or task type. Some embedding models are trained to embed queries and documents differently. Using the wrong mode lowers quality.
Ranking
Ranking measures how close each chunk vector is to the query vector. The usual measure is cosine similarity. It compares direction and ignores length, and returns a value near 1 for similar meaning.
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_vec, chunks, k=3):
# chunks is a list of (text, vector) pairs
ranked = sorted(chunks, key=lambda c: cosine(query_vec, c[1]), reverse=True)
return [text for text, _ in ranked[:k]]This code compares the query with every chunk, which is exact but slow for millions of chunks. Vector databases use approximate nearest neighbor (ANN) indexes to avoid the full scan. They trade a small loss in recall for large gains in speed. At a few thousand chunks, the brute-force version above is fine and easier to debug.
Beyond a single similarity score
Pure vector search has known weak spots. Two additions are common.
- Hybrid search. Combine vector search with keyword search such as BM25. Vectors handle paraphrases. Keywords handle exact strings like error codes, product names, and part numbers, which embeddings often blur. Merge the two ranked lists, for example with reciprocal rank fusion.
- Reranking. Retrieve a wide set, such as the top 20, then score each question and chunk pair with a cross-encoder, a model that reads both texts together. Keep the top 3 to 5. A reranker is slower per item but more accurate than a vector comparison, so it runs only on the short list.
Choosing k and a threshold
k is the number of passages you send to the model. Too small and the answer may be missing. Too large and you add noise, cost, and latency, and the model may lose track of the relevant passage in a long prompt.
Also consider a similarity threshold. If the best score is low, nothing relevant exists in the index. Sending the top 3 anyway invites the model to build an answer from unrelated text. With a threshold, you can return "I don't know" or fall back to another path.
Building the grounded prompt
The retrieved passages go into the prompt along with an instruction to rely on them.
def grounded_prompt(question, passages):
context = "\n\n".join(passages)
return (
"Answer using only the context below. "
"If the answer is not in the context, say you don't know.\n\n"
"Context:\n" + context + "\n\nQuestion: " + question
)Improvements worth making in real systems:
- Label each passage with an ID such as
[1]and ask the model to cite IDs. You can then check that each cited passage supports the claim. - Delimit passages clearly so the model can tell where one ends and the next begins.
- Treat retrieved text as data. A document that contains the sentence "ignore your instructions" is an injection attempt, not a command. Tell the model in the system prompt that context is reference material only.
- Respect permissions. Filter by the user's access rights at retrieval time, not after generation.
Putting it together
This end-to-end example uses a toy embedding so it runs without any API. It counts how many times chosen keywords appear. A real system would call an embedding model instead.
import math
VOCAB = ["refund", "days", "ship", "business", "payment", "method"]
def toy_embed(text):
words = text.lower().replace(".", "").split()
return [float(sum(1 for w in words if w.startswith(v))) for v in VOCAB]
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
chunks = [
"Customers may request a refund within 30 days of purchase.",
"Refunds are issued to the original payment method.",
"Orders ship within two business days.",
]
index = [(c, toy_embed(c)) for c in chunks]
question = "How many days do I have to ask for a refund?"
qvec = toy_embed(question)
scored = sorted(index, key=lambda item: cosine(qvec, item[1]), reverse=True)
for text, vec in scored:
print(round(cosine(qvec, vec), 2), text)The refund-window chunk scores highest because it shares "refund" and "days" with the question. Note the guard in cosine. A zero vector, such as a question with no known words, would otherwise cause a division by zero.
Failure modes
When answers are wrong, find which stage failed before changing anything.
| Symptom | Likely stage | Check |
|---|---|---|
| The right passage is not in the top k | Chunking or ranking | Does any chunk contain the answer whole? Try hybrid search or a larger k with reranking |
| The right passage is retrieved but the answer is wrong | Prompt or model | Does the prompt tell the model to use the context? Is the passage buried among noise? |
| The answer is fluent but unsupported | Missing threshold | Add a "don't know" path and require citations |
| Results are outdated | Indexing | Re-index changed documents and store timestamps |
| Exact identifiers are never found | Embedding-only search | Add keyword search |
| Quality dropped after a model change | Embedding mismatch | Confirm chunks and queries use the same model version |
Measure retrieval separately from generation. For each question in your evaluation set, record which chunk should answer it, then compute recall at k: the share of questions where that chunk appears in the top k. If recall is low, no prompt change will fix the answers.
Exercise
Your RAG system answers "What does error E-4417 mean?" incorrectly. The manual contains the exact sentence "E-4417: the license server is unreachable", but vector search ranks it 14th and k is 3. Name two changes that could fix retrieval and explain why each helps.
Show answer
Add hybrid search, so a keyword match on the exact token "E-4417" lifts that chunk, because embeddings often blur identifiers. Alternatively, retrieve the top 20 and rerank with a cross-encoder, which reads the question and chunk together and can put the exact match at the top, then keep the top 3. Raising k to 14 or more would also include the chunk but adds noise and cost, so it is the weaker fix.
Exercise
Each question in your evaluation set has one known correct chunk. In 50 questions, the correct chunk appears in the top 5 results 41 times. What is recall at 5, and what does it tell you about where to look when answers are wrong?
Show answer
Recall at 5 is 41 / 50 = 0.82. In 18 percent of cases the correct chunk never reaches the model, so those failures come from chunking, embedding, or ranking, and prompt changes cannot fix them. For the other 82 percent, retrieval worked, so inspect the prompt and the model's use of the context.