RAG: Look It Up, Then Answer

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

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

  1. Three documents: a shop's own facts. No language model was trained on these.
  2. A customer's question.
  3. Its words, for matching.
  4. Step 1, retrieve: one score per document.
  5. First document: "shop opens at 9 am".
  6. None of its words are in the question: score 0.
  7. doc changes from 'shop opens at 9 am' to 'returns are free for 30 days'.
  8. "returns", "are" and "free" all appear in the question: score 3.
  9. doc changes from 'returns are free for 30 days' to 'we ship to india and nepal'.
  10. Score 0.
  11. Python moves to the next item of the loop: for doc in docs.
  12. The best match is the returns document.
  13. Step 2, augment: put the fact into the prompt, next to the question.
  14. 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

Best practices

Key takeaways

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.

·

More in Building with Models