Sub topic 6
RAG: giving the model the facts at query time
Retrieval-augmented generation (RAG) fetches relevant text from your own data when a question arrives and puts that text in the prompt. The model's weights stay the same. Only the input changes.
This chapter assumes you can call a chat-style LLM API, read Python, and know what an embedding and a context window are.
When RAG fits
RAG fits a knowledge gap. The model gives wrong or vague answers because it lacks the facts, not because it writes in the wrong way. Typical cases:
- Private data, such as internal policies or product manuals.
- Fresh data, such as prices or release notes newer than the model's training data.
- Answers that must be traceable to a source document.
If the model already knows the facts but formats answers badly, RAG will not help. That is a behavior gap, which prompting or fine-tuning addresses.
The working model
A RAG system has two phases. Before any question arrives, you split documents into chunks and compute an embedding (a vector of numbers that captures meaning) for each chunk. You store the pairs of text and vector. At query time, you embed the question, find the chunks whose vectors are closest to it, and place those chunks in the prompt.
Ranking and grounding in code
The usual ranking measure is cosine similarity. It compares the direction of two vectors and ignores their length. The code below ranks stored chunks 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
)Two parts matter here. top_k is the retrieval step. grounded_prompt is the grounding step, and its instruction to say "I don't know" gives the model a safe way out when retrieval finds nothing useful.
A production system replaces the sorted list with a vector index, but the logic is the same.
Worked example
Suppose a support bot must answer "How many days do I have to request a refund?" The policy lives in your handbook, and the model has never seen it.
- At indexing time, you split the handbook into chunks of a few hundred words and embed each one.
- At query time, you embed the question and call
top_kwithk=3. - The refund-policy chunk ranks first because its meaning is close to the question.
grounded_promptputs that chunk and the question into one prompt.- The model answers from the chunk, such as "30 days from purchase", instead of guessing.
When the policy changes, you update the chunk and re-embed it. No retraining is needed. This is why RAG handles freshness well.
Common errors
- Retrieval misses the right chunk. The model cannot use a fact it never sees. When an answer is wrong, first print the retrieved chunks. Most RAG bugs are retrieval bugs.
- Chunks are too large or too small. Large chunks dilute the match and waste context. Small chunks lose the surrounding meaning. Tune the size against your evaluation set.
- Mixed embedding models. Query and chunk vectors must come from the same model. Vectors from different models are not comparable.
- Too many chunks. Adding more passages raises cost and latency, and irrelevant text can distract the model.
- No instruction to stay grounded. Without it, the model may blend its own memory with the context and state invented details.
Exercise
Exercise
A RAG bot gives a wrong answer about a refund policy. The correct policy chunk exists in the store. What should you check first, and why?
Show answer
Check which chunks were retrieved for the question. If the correct chunk is not in the top k, the model never saw the fact, so the fault is in retrieval (chunking, embedding model, or k), not in the model. If the chunk was retrieved and the answer is still wrong, then examine the prompt instructions.