A model only knows what it was trained on. Retrieval-augmented generation finds the right document first and puts it in the prompt.
AI · beginner · 8 min · 14 steps · free
What you'll learn
Name the three steps of RAG: retrieve, augment, generate
Score documents against a question
Build a prompt that carries the retrieved fact
rag.py
# A model only knows what it was trained on. RAG looks facts up first, then puts them in the prompt.
docs = ["shop opens at 9 am", "returns are free for 30 days", "we ship to india and nepal"]
question = "are returns free"
asked = question.split(" ")
# 1. Retrieve: score every document by how many of the question's words it contains.
scores = []
for doc in docs:
scores.append(len([w for w in doc.split(" ") if w in asked]))
best = docs[scores.index(max(scores))]
# 2. Augment: put the best document into the prompt, next to the question.
prompt = "Use this fact: " + best + ". Question: " + question + "?"
# 3. Generate: the prompt is sent to the language model, which can now answer from the fact.
print(prompt)
Step by step
Three documents: a shop's own facts. No language model was trained on these.
A customer's question.
Its words, for matching.
Step 1, retrieve: one score per document.
First document: "shop opens at 9 am".
None of its words are in the question: score 0.
doc changes from 'shop opens at 9 am' to 'returns are free for 30 days'.
"returns", "are" and "free" all appear in the question: score 3.
doc changes from 'returns are free for 30 days' to 'we ship to india and nepal'.
Score 0.
Python moves to the next item of the loop: for doc in docs.
The best match is the returns document.
Step 2, augment: put the fact into the prompt, next to the question.
Step 3, generate: this prompt goes to the language model, which can now answer "Yes, returns are free for 30 days" from a fact it never learned. That is RAG.
Common mistakes
Expecting the model to know your private documents without retrieval
Putting every document in the prompt instead of the relevant ones
Best practices
Tell the model to answer only from the retrieved text, and to say when it is not there
Key takeaways
RAG = retrieve the relevant documents, augment the prompt with them, generate the answer.
It lets a model answer from information it was never trained on.
Retrieval scores documents against the question; real systems use embeddings.
Only the best matches go in the prompt, which keeps it short and focused.
Check yourself
Your model does not know your company's holiday policy. What does RAG do?
Answer: Finds the policy document and puts it in the prompt. RAG looks the fact up at question time; no retraining needed.
What are the three steps of RAG, in order?
Answer: Retrieve, augment, generate. Find the document, add it to the prompt, then let the model answer.