Sub topic 6
RAG: giving the model the facts at query time
This chapter assumes you can call a chat-style LLM API, read Python, and know what an embedding and a context window are. It covers retrieval-augmented generation (RAG): what it fixes, how it works, and where it breaks. The next chapter goes inside the retrieval pipeline.
What RAG does
A language model only knows what was in its training data, and that data stops at a cutoff date. It has never seen your internal wiki, last week's pricing change, or a customer's contract. When you ask about those things, it may guess, and the guess can sound confident.
Retrieval-augmented generation (RAG) fixes this at query time. Before calling the model, your code searches a store of your own documents for passages related to the question. It then puts the best passages into the prompt and tells the model to answer from them. The model's weights do not change. Only the input does.
This makes RAG the lever for knowledge gaps, the case from the diagnosis chapter where the model lacks facts. It does not teach the model a new tone or output format. That is a behavior gap, and prompting or fine-tuning handles it better.
The two phases
RAG has an offline phase and an online phase.
- Indexing (offline). Split documents into chunks. Convert each chunk to an embedding, which is a vector of numbers that captures meaning. Store the text and vector together.
- Querying (online). Embed the user's question with the same embedding model. Find the chunks whose vectors are closest to the question vector. Put those chunks in the prompt. Call the model.
Ranking by similarity
The usual measure of closeness is cosine similarity. It compares the direction of two vectors and ignores their length. Two vectors pointing the same way score near 1. Unrelated ones score near 0.
The code below implements the core of RAG. It ranks stored chunks against the query vector and builds a grounded prompt.
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]]
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
)This version scans every chunk, which is fine for thousands of chunks. Production systems use a vector database or an approximate nearest-neighbor index so the search stays fast at millions of chunks. The idea is unchanged.
Here is a tiny run with made-up two-dimensional vectors. Real embeddings have hundreds or thousands of dimensions, but the logic is the same.
chunks = [
("Refunds are issued within 14 days of purchase.", [0.9, 0.1]),
("The office is closed on public holidays.", [0.1, 0.9]),
("Refund requests need an order number.", [0.8, 0.3]),
]
query_vec = [0.85, 0.2] # pretend embedding of "How do I get a refund?"
passages = top_k(query_vec, chunks, k=2)
print(grounded_prompt("How do I get a refund?", passages))The two refund chunks rank first, and the holiday chunk is left out. The prompt then carries only relevant facts.
Why the instruction in the prompt matters
Look at the wording of grounded_prompt: "Answer using only the context below. If the answer is not in the context, say you don't know." Retrieval supplies facts, but the model still chooses whether to use them. Without this instruction, it may blend the passages with its own memory, or fill a gap with a plausible guess.
Grounding also gives you something prompting alone does not: traceability. If you keep a source ID with each chunk, you can show the user where an answer came from and check it.
What RAG is good at
- Freshness. Update the index and the next query sees the new fact. No retraining is needed.
- Private data. The model can answer from documents it was never trained on.
- Access control. You can filter chunks by the user's permissions before they reach the prompt. A fine-tuned model cannot forget a fact for one user and not another.
- Citations. Each answer can point to its source passages.
- Cheap corrections. Fixing a wrong answer often means fixing one document.
What RAG costs
- More tokens per request. Every retrieved chunk is billed as input and adds latency. Five chunks of 400 tokens add about 2,000 input tokens to each call.
- Extra moving parts. You now run an embedding model, an index, and a retrieval step. Each can fail on its own.
- A new failure surface. If retrieval returns the wrong chunks, the model answers from the wrong facts, however good it is.
- Context limits. Passages must fit in the context window along with the instructions and the answer.
Where RAG fails
Most RAG bugs fall into a few groups. It helps to find which stage failed before changing anything.
| Symptom | Likely stage | Typical fix |
|---|---|---|
| Right document exists, never retrieved | Retrieval | Better chunking, a better embedding model, hybrid keyword and vector search |
| Retrieved chunk is relevant but cut mid-explanation | Chunking | Larger chunks or overlap between chunks |
| Right chunk retrieved, answer ignores it | Generation | Stronger grounding instruction, fewer or better-ordered chunks |
| Answer mixes in outdated facts | Index | Re-index changed documents, store dates, filter by date |
| Model invents an answer when nothing relevant exists | Generation | Refusal instruction, a minimum similarity score |
| Answer is right but wrong style | Not a RAG problem | Prompting or fine-tuning |
Two failures deserve extra attention.
Retrieval misses. Embeddings capture meaning but can miss exact strings such as product codes, error numbers, or names. A question about "error E-4471" may retrieve text about errors in general. Many systems combine vector search with keyword search for this reason.
Too much context. Adding more chunks does not always help. Irrelevant passages distract the model, and facts buried in the middle of a long prompt are used less reliably than those near the start or end. Start with a small k, such as 3 to 5, and measure.
Measuring a RAG system
Evaluate retrieval and generation separately, using the evaluation set from the earlier chapter.
- Retrieval check. For each test question, record which chunk should be found. Measure how often it appears in the top k. This is called recall at k.
- Generation check. Given the correct chunks, does the model answer correctly and stay within them?
- End-to-end check. Does the full pipeline answer correctly, and decline when the answer is absent?
If recall at k is low, tuning the prompt will not help. If recall is high but answers are wrong, retrieval is fine and the problem is in generation.
When to choose RAG
Choose RAG when the diagnosis says the model lacks facts, when those facts change often, when they are private, or when you must cite sources. Skip it when the problem is style, format, or reasoning habits, and when the whole knowledge base is small enough to paste into the prompt. A few pages of reference text often work better as plain prompt context than as an index you must maintain.
Exercise
A support bot answers questions about your company's return policy. Users report it quotes a policy from two years ago. You check the logs and see that the correct, updated policy page was never among the retrieved chunks, but an old archived page was. Which stage failed, and what are two fixes?
Show answer
Retrieval and the index failed. The bot used the old page, so generation followed the context it was given. Two fixes: remove or re-index the archived page so it no longer competes with the current one, and store a date or version field with each chunk so retrieval can filter out outdated documents. Adding a hybrid keyword search could also help the current page rank higher. Changing the prompt or fine-tuning would not address the cause.
Exercise
Your evaluation set shows that the correct chunk is in the top 5 results for 95% of questions, but only 60% of final answers are correct. Where should you look first, and why?
Show answer
Look at generation. Recall at k is high, so retrieval is mostly working. The model is receiving the right facts but not using them correctly. Check the grounding instruction, the order and number of chunks, and whether irrelevant chunks distract the model. Tuning the embedding model or chunking would likely change little.