Gradient LabStart the lesson

Lessons › Chapter 11: Transformers and LLMs

Retrieval-augmented generation

rag first runs a vector search over your documents to find the few passages most relevant to the question.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Answer from the handbook

Policies change. Pip must answer from the current handbook, not from memory.

Problem

Models don’t know your documents

A model only knows what was in its training data. It hasn’t read your company handbook or this morning’s policy update, and if asked anyway it may guess, confidently and wrongly.

Key idea

Retrieve the right pages

rag first runs a vector search over your documents to find the few passages most relevant to the question.

Build

Add them to the prompt

Those passages are pasted into the prompt next to the question, so the model reads the actual source right before answering.

Build

Answer, with sources

The model writes its answer grounded in the retrieved text and can point to where it came from. Update the documents and the answers update too, with no retraining.

Real life

In real life: a help desk that cites its sources

Company help bots, customer-support assistants and “chat with your PDF” tools mostly work this way: search the documents, hand the best passages to the model, and answer with links so you can check.

Quick check: What does the “retrieval” step in RAG do?

It fetches the most relevant passages so the model can answer from them.

Pseudocode

question = "How many holiday days do new staff get?"
docs = vector_search(question, company_handbook)    # retrieve
prompt = docs + question                            # augment
answer = model(prompt)                              # generate
show the answer with links to the source documents

Key terms

rag
Retrieval-augmented generation: fetching relevant documents and giving them to the model before it answers.

Build it: Build a mini search engine (the R in RAG) (30 min, runs in your browser)

See the project

In the news

Recent models and papers that build on this idea: