Retrieval-augmented generation
9 min read
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.
- 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.
- 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.
- Retrieve. When a question arrives, find the few chunks that best match it.
- 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.
- SplitCut each document into chunks. Done ahead of time.
- IndexStore the chunks so that they can be searched. Done ahead of time.
- RetrieveFind the few chunks that best match the question. Done on every question.
- GenerateAdd those chunks to the prompt and answer from them. Done 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.
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.
What fixes the problem?
A user asks about a policy that changed yesterday. The model quotes the old one.
The model cannot know new documents. Retrieval gives it text to answer from.
Where do you look first?
A RAG assistant gives a wrong answer. The correct passage exists in your documents.
If the right chunk was never retrieved, no prompt change will fix the answer.
Which step happens before any question arrives?
RAG has four steps: split, index, retrieve and generate.
Splitting and indexing prepare the documents ahead of time. Retrieval and generation run on every question.
Your reading position is saved
0 of 20 complete
Lesson complete
Retrieval-augmented generation
Up next