Sub topic 12
Answering from your own documents with retrieval
Retrieval-augmented generation (RAG) lets a model answer questions from documents it was never trained on. Your program finds the relevant passages and puts them in the prompt. The model then writes an answer based on that text.
This chapter assumes you can write Python and call a model API, and that you have read the chapter on embeddings and semantic search. You should know that an embedding is a vector, and that cosine similarity measures how close two vectors are.
Why retrieval instead of pasting everything
A model's knowledge stops at its training data. It has never seen your handbook, tickets, or contracts. You could paste every document into each prompt, but that fails for three reasons:
- Your corpus is usually larger than the context window.
- You pay for every token on every request, and long prompts are slower.
- Models tend to use information in the middle of a very long prompt less reliably than information near the ends.
Retrieval sends only the few passages that matter for the current question. It also lets you update knowledge by changing an index, not by retraining anything.
The pipeline
RAG has an indexing phase that runs ahead of time and a query phase that runs per question.
Chunking
Embedding a whole document produces one vector that blurs every topic in it. So you split documents into chunks, usually a few hundred tokens each. Two rules of thumb:
- Split on natural boundaries (headings, paragraphs) when you can, and fall back to fixed sizes.
- Overlap neighboring chunks slightly so a sentence cut at a boundary still appears whole in one chunk.
Chunks that are too small lose context ("it expires after 30 days" with no subject). Chunks that are too large dilute the match and waste prompt space. Start around 200 to 500 tokens and adjust using test questions.
Keep metadata with each chunk: source file, section title, page, date. You need it for citations and for filtering.
Retrieval, threshold, and prompt
The top_k function from the embeddings chapter always returns k results, even when nothing is relevant. For RAG, add a minimum score so weak matches are dropped. Then build a prompt that numbers each passage and tells the model what to do when the passages do not contain the answer.
The code below uses toy two-dimensional vectors so it runs without an API. In a real system, an embedding model produces the vectors.
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 chunk(text, size=40, overlap=10):
words = text.split()
step = size - overlap
return [" ".join(words[i:i + size])
for i in range(0, max(len(words) - overlap, 1), step)]
def retrieve(query_vec, index, k=3, min_score=0.5):
scored = [(cosine(query_vec, item["vector"]), item) for item in index]
scored.sort(key=lambda pair: pair[0], reverse=True)
return [item for score, item in scored[:k] if score >= min_score]
def build_prompt(question, passages):
if not passages:
return None
context = "\n\n".join(
f"[{i}] {p['text']} (source: {p['source']})"
for i, p in enumerate(passages, 1)
)
return (
"Answer the question using only the numbered passages below.\n"
"Cite passage numbers like [1]. If the passages do not contain "
"the answer, reply exactly: I don't know.\n\n"
f"Passages:\n{context}\n\nQuestion: {question}"
)
index = [
{"text": "Refunds are issued within 14 days of a request.",
"source": "refund.md", "vector": [1.0, 0.0]},
{"text": "Standard shipping takes 3 to 5 business days.",
"source": "shipping.md", "vector": [0.0, 1.0]},
]
passages = retrieve([0.95, 0.05], index)
print(build_prompt("How long do refunds take?", passages))
print(build_prompt("Who founded the company?", retrieve([-1.0, -1.0], index)))The second call prints None because no passage clears the threshold. In a real application, return a fixed "I couldn't find that in the documents" message at that point, without calling the model. That is cheaper and safer than asking the model to improvise.
Where RAG fails
Most RAG bugs are retrieval bugs. When an answer is wrong, first look at which passages were retrieved. Common failure modes:
| Symptom | Likely cause | Fix |
|---|---|---|
| Right document exists but is not retrieved | Chunk too large, or question wording differs from the text | Smaller chunks, query rewriting, hybrid search |
| Exact terms such as product codes are missed | Embeddings capture meaning, not exact strings | Combine keyword search (BM25) with vector search |
| Answer mixes two similar documents | Several versions of a policy are indexed | Filter by date or version metadata |
| Confident answer with no support | Prompt allows outside knowledge | "Only use the passages" plus a refusal rule |
| Answer cites a passage that does not say that | Model paraphrased loosely | Check citations in code or with a second model call |
Two techniques help often. Hybrid search runs keyword and vector search and merges the rankings. Reranking retrieves around 20 candidates cheaply, then uses a stronger model or a cross-encoder to reorder them and keep the best 3 to 5.
Access control and freshness
If users have different permissions, filter at retrieval time. A user must never receive a chunk they could not open themselves. Do this filtering in the search query, using metadata, and not by asking the model to hide things.
For freshness, re-embed a document when it changes and delete the old chunks. Store a document ID on every chunk so that deletion is possible. Stale chunks are a common source of answers that were once right.
Evaluating a RAG system
Test retrieval and generation separately.
- Write 30 to 50 real questions, each with the document that answers it.
- Measure recall at k: how often the correct chunk appears in the top k results. If this is low, fix chunking, embeddings, or search before touching the prompt.
- Check answers for faithfulness: does every claim appear in the passages?
- Include questions with no answer in the corpus and confirm the system declines.
Rerun this set whenever you change the chunk size, embedding model, or prompt.
When RAG is the wrong tool
RAG answers questions whose answers sit in a few passages. It handles questions that need the whole corpus poorly, such as "summarize all complaints this year" or "how many contracts mention arbitration." Those need aggregation over structured data, a different pipeline, or tools. RAG also does not change a model's style or skills. If you need a consistent output format or tone, work on the prompt, or consider fine-tuning.
Exercise
Users report that your documentation assistant gives wrong answers about "error code E-4012". You check the logs and see that the retrieved passages were about general error handling, and the page that defines E-4012 was not retrieved. Name the likely cause and two changes you would try before editing the prompt.
Show answer
Vector embeddings capture meaning, so an exact identifier like "E-4012" is a weak signal and similar-sounding pages outrank the right one. Try adding keyword search (BM25) alongside vector search as a hybrid, and add a reranking step over a larger candidate set. Smaller chunks, or storing the error code as metadata that can be filtered on, would also help. The prompt is not the problem because the right passage never reached the model.
Exercise
In the retrieve function, what happens if you set min_score=0.0, and why is that a problem for a question the documents cannot answer?
Show answer
Almost every chunk passes the threshold, so the function returns the k closest chunks even when they are unrelated. The prompt then contains irrelevant passages, and the model may produce a plausible but unsupported answer instead of the "I don't know" path. A sensible threshold lets the program detect "nothing relevant found" before calling the model.