Papa Programmer
Lesson 07 of 20

Retrieval-augmented generation

9 min read

Optional

The problem retrieval solves

A model learned from public text up to a fixed date. It has never seen your company handbook, today's prices or the file you saved this morning. If you ask about them, it will either say it does not know or write something that sounds right and is not. That second case is an AI hallucinationAn answer that sounds confident but is false. The model wrote text that fits the pattern instead of text that is true..

Retrieval-augmented generationA method where an app searches sources at question time and adds selected passages to the model's context. Updated information can inform later answers once it is available to retrieval, but the results and answers still need checking., or RAG, fixes this by changing the input. The program finds the relevant passages and puts them in the prompt. The model then answers from text it can read.

Four steps

RAG has the same four steps in nearly every system.

  1. Split. Cut each document into passages of a few hundred words, called chunks. A whole book will not fit in a prompt, but a chunk will.
  2. Index. Store the chunks so that you can search them. Many systems turn each chunk into Vector embeddingsLists of numbers that stand for the meaning of a piece of text. Texts with similar meanings get similar numbers, so a search can find a passage even when the words differ., which are lists of numbers that place similar meanings near each other.
  3. Retrieve. When a question arrives, find the few chunks that best match it.
  4. Generate. Add those chunks to the prompt and ask the model to answer using only them.

Steps 1 and 2 happen ahead of time. Steps 3 and 4 happen on every question.

  1. SplitCut each document into chunks. Done ahead of time.
  2. IndexStore the chunks so that they can be searched. Done ahead of time.
  3. RetrieveFind the few chunks that best match the question. Done on every question.
  4. GenerateAdd those chunks to the prompt and answer from them. Done on every question.
Retrieval-augmented generation: two steps happen ahead of time, two on every question

A tiny retriever in Python

Real systems use embeddings. The sketch below scores chunks by shared words, which is crude but shows the shape.

python
chunks = [
	"Refunds are accepted within 30 days of delivery.",
	"Standard shipping takes three to five working days.",
	"Gift cards never expire.",
]

def score(question, chunk):
	words = set(question.lower().split())
	return len(words & set(chunk.lower().split()))

def retrieve(question, top=1):
	return sorted(chunks, key=lambda chunk: score(question, chunk), reverse=True)[:top]

question = "How many days do I have for refunds?"
context = retrieve(question)[0]
prompt = f"Answer using only this text.\nText: {context}\nQuestion: {question}"
print(prompt)

The retriever picks the refund chunk, because it is the only one that shares a word with the question: "days". The match is weak. A question without that word would find nothing. An embedding-based version would also match a question that uses different words with the same meaning, such as "How long can I send it back?".

What goes wrong

RAG fails in quiet ways, so check each step.

  • Bad chunks. A chunk cut in the middle of a table or a sentence loses its meaning.
  • Missed retrieval. The right passage exists, but the search did not return it. The model then answers without it.
  • Too much retrieved. Ten loosely related chunks bury the one that matters and fill the context window.
  • Ignored evidence. The passage was in the prompt, but the model answered from habit. Tell it to use only the text, and to say so when the text lacks the answer.

When a RAG answer is wrong, look at the retrieved chunks first. If the right chunk was never retrieved, no prompt change will fix it.

Find, then answerThe program retrieves relevant passages and the model answers from them.
Four stepsSplit, index, retrieve and generate. The first two happen before any question arrives.
Debug the retrieval firstIf the right passage was never in the prompt, change the search, not the wording.

Your reading position is saved

0%

0 of 20 complete

Contents

Learning tools