AlgoViz

Retrieval-Augmented Generation (RAG)

medium 12 min

A retrieval-augmented system maintains a searchable collection and consults it for each question.

Find the card. Fetch the page. Cite the line.

A librarian finds a catalog card, fetches the matching edition and points to the line that answers the reader.

A librarian finds a catalog card, fetches the matching edition and points to the line that answers the reader.
Find the cardRetrieve candidates
Fetch the pagePut selected evidence in context
Cite the lineLink the answer claim to its source
Practice recall

Video lesson · Chapter 1 of 6

The grounding problem

0:00 / 4:03

RAG in 90 seconds

1:30Reel coming soon

Retrieval-Augmented Generation (RAG) in one picture
Retrieval-Augmented Generation (RAG) in one picture

Theory

Read or listen first. About 2 min.

What it is

A retrieval-augmented system maintains a searchable collection and consults it for each question. Evidence passes from versioned sources through retrieval and context assembly into generation. Each stage can introduce a distinct error.

Why it exists

A refund answer can be stale because the index contains yesterday’s document, incomplete because an exception was dropped, or unsupported because the generator misread a correct passage. Inspect the document IDs and evidence at each boundary to distinguish those failures.

Which refund policy reached the answer?

Source revision → Evidence set (index revisions). Evidence set → Cited response (supply cited passages)
Source revision → Evidence set (index revisions). Evidence set → Cited response (supply cited passages)

Inside this chapter

Chapter sources
What is RAG?
Retrieval-augmented generation adds a source lookup before generation. The retriever chooses evidence and the generator conditions its answer on what it receives. For a refund question, inspect the retrieved policy revision first. Improving the wording of an answer cannot recover a policy clause that never entered context.

At query time the system does two separate jobs. First a retriever turns the question into a search and returns a handful of passages; then a prompt is built from the question plus those passages, and the model writes an answer conditioned on them. The model's weights never change, so updating knowledge means updating the index. When an answer is wrong, the first question is always whether the right passage was in the prompt at all: if it was not, no amount of prompt wording will fix it.

Example. Ask about a clause introduced this morning. Remove the new passage from the index, observe the failure, then reintroduce it and inspect the prompt.

Another example. An internal IT helpdesk bot answers VPN questions from a wiki. After the VPN client changes, the bot keeps quoting the old setup steps until the wiki page is re-indexed, even though nobody touched the model or the prompt.

Same question, with and without the new clause

The generator can only be as current as the passages it is handed.
RAG Use Cases & Applications
RAG is useful when answers depend on changing or private material such as a catalog, product manual or policy collection. Check that the corpus can actually answer the intended questions. Include unanswerable cases to distinguish a system that abstains from one that fills gaps with plausible prose.

Retrieval pays off when the facts are private, change faster than you could retrain, or must be cited. It adds little for pure style or reasoning tasks, and it actively hurts when the corpus cannot answer the question, because the model is handed loosely related text and tends to blend it into a confident reply. That is why the abstention case belongs in the very first test set, not as an afterthought.

Example. Pair “What is our refund window?” with an unrelated question absent from the corpus. Expect a sourced answer to one and an abstention on the other.

Another example. A contract-review assistant searches a firm's own clause library. A question about a jurisdiction the library does not cover should come back as "no matching clause found", not as a paraphrase of the nearest clause from another country.

Does this workload suit retrieval?

QuestionAnswer lives inChanges often?Expected behaviour
What is our refund window?Policy collectionYesSourced answer with citation
Which plan includes SSO?Product catalogueYesSourced answer
Who won the 1966 World Cup?Not in the corpusNoAbstain or say out of scope
Rewrite this email more politelyNo lookup neededn/aSkip retrieval
Mix answerable, unanswerable and no-retrieval-needed questions into every test set.
RAG Architecture Overview
Separate the offline indexing path from the online question path. The indexer reads, splits and embeds versioned sources. The online service searches an authorized subset and passes selected evidence to the generator. A stale answer can originate in either path, so log the indexed revision and cited chunk IDs.

The offline path runs on a schedule or on change events: it reads sources, splits them, embeds the pieces and publishes a new index generation. The online path runs per request and should be fast and read-only. Because the two run at different times, a stale answer can come from a slow publisher, a reader pinned to an old generation, or a cache in front of either. Logging the revision at every hand-off turns a vague "it's stale" into a specific broken link.

Example. Log the document revision at ingestion, candidate selection and citation. Three different versions identify a publishing or provenance bug.

Two paths that meet at the index

Log the index revision on the offline side and the cited chunk IDs on the online side.
RAG vs fine-tuning vs long context
Three ways to give a model knowledge it lacks. Retrieval fetches a few relevant passages per request; fine-tuning changes the weights so behaviour or style is learned; long context pastes a large body of text into every prompt. They solve different problems and are often combined.

Interviewers ask this to see whether you separate knowledge from behaviour. Weights are a poor place for facts that change or that only some users may see, because you cannot delete one fact or apply access rules inside a model. Long context avoids a retriever but pays for every token on every call and can still miss details buried in the middle. Retrieval keeps prompts small and auditable but adds a component that can fail on its own.

Example. A policy that changes weekly suits retrieval. A house tone of voice suits fine-tuning. A single 40-page contract that one user is asking about can simply be placed in context.

Choosing how knowledge reaches the model

NeedRetrievalFine-tuningLong context
Facts change weeklyRe-indexRetrain each timeRe-send each time
Citations requiredNatural fitHardPossible
Per-user access rulesFilter at searchNot enforceable in weightsOnly send allowed text
Learn a format or toneWeakStrongWeak to moderate
Cost per requestSmall promptSmall promptLarge prompt
A qualitative guide, not a benchmark.

How it works

Step through the idea, or press Play.

Step 1 of 3

Your question. A user query, e.g. “How do refunds work?”

Understand it

Worked example

Which refund policy reached the answer?

  1. 1

    Policy v7 · 30 days

    A revised policy extends the return period. Give its passages stable identifiers and retire superseded entries when the new index is published.

  2. 2

    v7 §2, v7 §4

    Search retrieves the standard window and a separate holiday exception. Keep both source IDs as the passages cross into the generation request.

  3. 3

    30 days, subject to §4

    Check that the answer uses the current release and that each claim can be traced to the supplied sections. A confident answer from v6 is still stale.

Follow the handoffs

A refund answer can be stale because the index contains yesterday’s document, incomplete because an exception was dropped, or unsupported because the generator misread a correct passage. Inspect the document IDs and evidence at each boundary to distinguish those failures.
Where the 14-day answer could have come from
  1. 1Policy v7 published?check source revision
  2. 2Index has v7, v6 retired?check index generation
  3. 3Search returned v7 §2, §4?check evidence IDs
  4. 4Prompt contained v7?check packed context
  5. 5Answer cites v7?check claim support

Walk the boundaries in order and stop at the first one that shows v6.

Reading the trace for the question

BoundaryHealthySeen in the failing case
Sourcev7 · 30 daysv7 · 30 days
Indexv7 live, v6 retiredv6 still live
Promptv7 §2, v7 §4v6 §2 only
Answer30 days, subject to §414 days
The first mismatch is at the index, so the fix is freshness and retirement, not prompting.
Whiteboard sketch: documents are cut into chunks and stored in a vector index. A question searches the index, the top-k chunks go to the LLM, and it returns a grounded answer.
Docs become chunks in a vector index. A question pulls the top-k chunks, and the model answers from them.

A language model only knows what was in its training data, and it can state wrong things confidently. RAG adds a lookup step: before the model answers, we search our own documents for the passages most related to the question and paste them into the prompt.

How it works

Two phases

Indexing (offline, ahead of time)
  1. 1SplitCut each document into chunks
  2. 2EmbedTurn every chunk into an embedding vector
  3. 3StoreKeep the vectors in an index you can search
Querying (online, per question)
  1. 1Embed the questionThe same way the chunks were embedded
  2. 2Find nearest chunksThe top-k vectors closest to the question
  3. 3Ask the modelSend the chunks and the question together

What the model finally receives is ordinary text: an instruction, the retrieved passages, and the question.

Text
Answer using only the context below. If the context does notcontain the answer, say you don't know.Context:[1] Refunds are issued to the original payment method within 5 days.[2] Refund timing depends on your bank, usually 3 to 5 business days.Question: How do refunds work?
A grounded prompt for “How do refunds work?” with k = 2 retrieved passages.

Do

  • Measure retrieval on its own first: for a set of test questions, check whether the right chunk shows up in the top-k.
  • Embed questions and chunks the same way, so their vectors are comparable.
  • Treat the retrieved passages as evidence and still check the answer against them.

Don't

  • Tune the prompt before you know the right chunk is being retrieved.
  • Assume an answer is correct because it sounds fluent and RAG is switched on.
  • Blame the model for a miss that happened at the search step.

Summary

The whole topic in one minute.

The correct policy never reached generation. Trace the document revision through indexing and candidate selection first.

A refund answer can be stale because the index contains yesterday’s document, incomplete because an exception was dropped, or unsupported because the generator misread a correct passage. Inspect the document IDs and evidence at each boundary to distinguish those failures.

  • RAG = look up relevant passages from your own data, then answer with them in the prompt.
  • Indexing (offline): split, embed, store. Querying (online): embed the question, find the nearest chunks, ask the model.
  • Check retrieval separately before touching prompts: no right chunk, no right answer.
  • Grounding makes answers better supported, not guaranteed correct.

Sources