Unit 4 · Inference and Interaction

Lesson 15 · Available to read

Retrieval-Augmented Generation (RAG)

Grounding answers in external documents: embeddings, vector search, chunking and the RAG pipeline.

An LLM's built-in knowledge is frozen at its training cutoff, can't include your private documents, and is stored too diffusely to cite. Retrieval-augmented generation (RAG) — named in a 2020 research paper — fixes this by fetching relevant text at question time and handing it to the model as part of the prompt. It's the most common way to build assistants over company wikis, product manuals, legal archives and support tickets.

Why RAG?

  • Fresh knowledge — update the document index and the assistant knows the change immediately; no retraining.
  • Private data — your documents never need to be part of model training.
  • Citations — the model can point to the exact passage it used, so people can verify.
  • Fewer hallucinations — answering from supplied text is more reliable than answering from memory (though not perfectly, see below).
  • Cost — far cheaper and easier to maintain than fine-tuning new facts into a model (Lesson 11).

The two halves of a RAG system

RAG has an offline indexing pipeline (chunk, embed, index) and an online query path (embed question, retrieve top chunks, build prompt, answer with citations).
RAG has an offline indexing pipeline (chunk, embed, index) and an online query path (embed question, retrieve top chunks, build prompt, answer with citations).

Offline: indexing

  1. Parse documents into clean text (PDFs, web pages, slides, tables — often the messiest step).
  2. Chunk the text into passages, commonly a few hundred to about a thousand tokens, often with some overlap so a fact isn't split across a boundary. Keep metadata (title, section, date, permissions).
  3. Embed each chunk with an embedding model, producing one vector per chunk (Lesson 3).
  4. Store the vectors in a vector index — a database built for fast nearest-neighbour search. Approximate nearest-neighbour (ANN) algorithms such as HNSW graphs find close matches among millions of vectors in milliseconds, trading a tiny bit of accuracy for huge speed.

Online: answering a question

  1. Embed the question with the same embedding model.
  2. Retrieve the top-k most similar chunks by cosine similarity.
  3. Build the prompt: instructions + retrieved passages (labelled for citation) + the question.
  4. Generate an answer grounded in those passages, with citations.

A tiny retrieval example with 2-D vectors: the question embeds to q = (0.6, 0.8). Chunks: A = (1, 0), B = (0.8, 0.6), C = (0, 1), all unit length, so cosine = dot product. Scores: A = 0.6, B = 0.48 + 0.48 = 0.96, C = 0.8. With k = 2 we retrieve B and C.

Getting retrieval right

Most RAG failures are retrieval failures: if the right passage isn't retrieved, the best model can't answer. Common improvements:

  • Chunking strategy — split on natural boundaries (headings, paragraphs); too small loses context, too large dilutes relevance. Prepending each chunk with its document title and section (a "contextual header") often helps.
  • Hybrid search — combine embedding search (good at paraphrases: "refund" ≈ "money back") with classic keyword search such as BM25 (good at exact strings: product codes, names, error messages).
  • Reranking — retrieve a generous candidate set (say 50), then use a reranker model that reads the question and each passage together to score relevance more accurately, keeping the best handful.
  • Query rewriting — have the LLM turn a vague or conversational question ("what about the other one?") into a standalone search query, or into several sub-queries.
  • Metadata filters — restrict by date, product, language or — critically — the user's access permissions.
Hybrid retrieval combines vector and keyword search, then a reranker picks the best few passages.
Hybrid retrieval combines vector and keyword search, then a reranker picks the best few passages.

Getting generation right

  • Instruct the model to answer only from the provided sources, to cite them, and to say when the sources don't contain the answer.
  • Put sources before the question (Lesson 7) and label them clearly.
  • Handle conflicts — two documents disagree, or one is outdated: prefer newer sources, or show both.

Evaluating a RAG system

Measure the two halves separately:

  • Retrieval quality — for test questions with known relevant passages, is the right passage in the top k? (recall@k)
  • Faithfulness / groundedness — is every claim in the answer supported by the retrieved text?
  • Answer quality — is the answer correct, complete and relevant? (often judged by humans or an LLM judge, Lesson 17)

Failure modes to watch

  • Right document, wrong chunk — the key sentence fell just outside the retrieved passage.
  • Stale index — documents changed but weren't re-embedded.
  • The model ignores or contradicts the context and answers from memory instead.
  • Prompt injection — a retrieved document contains hidden instructions ("ignore previous instructions and…"). Treat retrieved text as data, not commands (Lesson 19).

RAG vs. long context

With context windows of hundreds of thousands of tokens, why not paste everything? Sometimes that's the right call for a handful of documents. But RAG still wins for large or changing collections: it's cheaper and faster per question, scales to millions of documents, enforces permissions, and avoids burying the answer in the middle of a huge prompt. Many systems combine the two — retrieve generously, then let a long-context model read it all.

Increasingly, retrieval is also done by agents that decide what to search for, read the results and search again (Lesson 16).

The takeaway

RAG grounds an LLM in your documents: chunk and embed them once, then for each question retrieve the most relevant passages and put them in the prompt with instructions to cite them — which keeps answers current, checkable and less prone to hallucination.

Practice

0 of 7 attempted

  1. 1Recall

    List the four offline indexing steps and four online answering steps of a RAG system.

    Saved in this browser

  2. 2Calculate

    A question embeds to q = (0, 1). Chunks (unit vectors): A = (0.6, 0.8), B = (−0.8, 0.6), C = (1, 0), D = (0.28, 0.96). Rank the chunks by cosine similarity and give the top 2.

    Saved in this browser

  3. 3Explain in your own words

    Why does hybrid search (embeddings + keywords) often beat either method alone?

    Saved in this browser

  4. 4Multiple choice

    A RAG assistant gives a wrong answer. Logs show the correct passage was not among the retrieved chunks. Which fix is most directly targeted at the problem?

  5. 5Explain in your own words

    What is the difference between retrieval quality and faithfulness when evaluating RAG? Why measure both?

    Saved in this browser

  6. 6Apply

    Write a system prompt for a RAG-based HR policy assistant. It should handle citations, missing information and conflicting documents.

    Saved in this browser

  7. 7Explain in your own words

    Give two reasons RAG is still useful even when a model has a very long context window.

    Saved in this browser

See what unlocked