Learn AI / 6. Building with AI / 6.2
Retrieval-augmented generation (RAG)
12 min read
Models don't know your company's documents, last week's news, or your customer records. Retrieval-augmented generation fetches relevant information at question time and puts it in the prompt.
How RAG works
Ahead of time (indexing):
- Collect documents: policies, manuals, tickets, web pages.
- Split them into chunks of a few hundred words.
- Turn each chunk into an embedding vector (Module 4) with an embedding model.
- Store the vectors in a vector database (or a search index), with links back to the source.
At question time:
- Embed the user's question.
- Retrieve the chunks whose vectors are closest to it (semantic search), often combined with traditional keyword search (hybrid search) and a re-ranker that re-orders the best candidates.
- Put the top chunks into the prompt with instructions: "Answer using only these sources; cite them; say if the answer isn't there."
- The model generates a grounded answer with citations.
Why it's so widely used
- Answers come from your current, authoritative sources, not the model's memory.
- Citations let users check.
- Updating knowledge means updating documents, not retraining.
- Access control can be applied at retrieval: users only get chunks they're allowed to see.
What goes wrong
- Bad chunks: splitting tables or sections mid-thought loses meaning.
- Retrieval misses: the right passage isn't found, so the model answers from memory or says nothing. Most RAG failures are retrieval failures.
- Conflicting or stale documents.
- Prompt injection hidden in retrieved content.
Measure retrieval quality separately (did we fetch the right passages?) from answer quality (did we use them correctly?).
RAG vs long context vs fine-tuning
| Approach | Best when |
|---|---|
| Put everything in a long context window | A few documents that fit; simplest option |
| RAG | Large or changing knowledge bases; citations and access control needed |
| Fine-tuning | Teaching a consistent style, format or narrow skill, not facts that change |
Check your understanding
Check 1 of 2Module 6 · Building with AI
In RAG, what is stored in the vector database?
Check 2 of 2Module 6 · Building with AI
A company's policy documents change monthly. The best way to let an assistant answer policy questions is:
Answer the checks, then mark this lesson complete
Completion and scores are saved in this browser.