Nguyen Le Phong

RAG Basics: Search First, Answer Second

How retrieval-augmented generation works, from chunks and embeddings to cited answers, and how to tell which layer broke when a RAG answer comes back wrong.

Just before lunch, someone drops a question in the team chat: "What did we settle on for refunds on annual plans?" One person remembers a meeting note. Another remembers a help center draft. The product spec says one thing, the support macro says another, and the latest decision sits in a doc whose title nobody can recall. Ask a plain chatbot and you'll get a confident, nicely written answer about refund policies in general. Your policy was never in its training data.

Retrieval-augmented generation, or RAG, is the usual fix for that gap. Before the model answers, the system searches your own documents for the passages that matter and hands them over along with the question. Search first, answer second. This post walks through the moving parts, then spends most of its time on the bit demos skip: working out which part broke when an answer comes back wrong.

Three teammates compare printed policies, notes and a laptop, trying to answer a refund question before lunch.
The answer exists somewhere. Nobody trusts their memory to find the latest version.

Where the idea comes from

The name comes from a 2020 paper by Patrick Lewis and colleagues at Facebook AI Research, University College London and New York University (Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks). They paired the knowledge stored inside a language model's weights, which they call parametric memory, with a dense vector index of Wikipedia, the non-parametric memory. On knowledge-heavy tasks, the combined model wrote more specific, diverse and factual text than the language model on its own.

Most product setups today are looser than the paper's. The authors fine-tuned the retriever and the generator together, while most teams plug an off-the-shelf model into a separate search step. The reasoning still holds, though. A model's training data stops at some date and never included your wiki. Retrieval lets it read the current version at question time, and you update what it knows by editing a document instead of retraining anything.

The pipeline in two halves

A RAG system does some work ahead of time and some at question time. Ahead of time, it builds the index:

  • Split documents into chunks. A chunk might be one section of a runbook or a few paragraphs of a policy. Too big and each chunk drags in noise. Too small and it loses the context that made it make sense.
  • Turn each chunk into an embedding, a list of numbers that puts text with similar meaning close together. A question about "canceling a yearly subscription" can then land near a chunk titled "refund rules for annual billing" even though the words barely overlap.
  • Store the embeddings in a vector index along with metadata such as source, owner, date and access level. Vector Databases Explained goes deeper on this layer.

At question time, it answers:

  • Embed the user's question the same way and fetch the closest chunks. Many teams also run a keyword search and merge the two result lists, because exact strings like error codes and product names are where meaning-based search slips.
  • Build a prompt with the question, the retrieved chunks and instructions like "answer only from these sources, cite them, and say so if they don't cover the question."
  • Generate the answer and show the citations right next to it.
Two teammates sketch document chunks and the links between them on a whiteboard, with a laptop running a search beside them.
Chunks and embeddings let the system match a question to your documents by meaning, even when the wording differs.

Small retrieval choices, big differences

A lot of RAG quality comes down to what retrieval hands the model. Anthropic put numbers on how much retrieval choices matter in its write-up on contextual retrieval (Introducing Contextual Retrieval, September 2024, checked November 2026). Their trick is to have a model write a short note for each chunk explaining where it sits in the document, then embed the note and the chunk together. A chunk that says "the company's revenue grew by 3% over the previous quarter" names neither the company nor the quarter, and the note puts that back. Averaged across their test sets, this cut the share of relevant chunks missing from the top 20 results by 35%. Adding keyword search (BM25) over the same annotated chunks brought the cut to 49%, and adding a reranking step brought it to 67%.

The same post has advice that's easy to miss: if your whole knowledge base is under 200,000 tokens, about 500 pages, you may not need RAG at all. Put everything in the prompt and use prompt caching to keep it fast and cheap. Context limits differ by model and keep changing, so check yours before you build an index for a few dozen documents.

When the answer is wrong, find the layer

RAG cuts down on guessing. It doesn't remove it. When an answer is wrong, the useful question is which layer failed, because each one has a different fix. Citations are what make this possible: you can see what the model was given and compare it with what it said.

What you see Likely layer First thing to check
The right document exists, but it isn't among the retrieved chunks Retrieval Run the search yourself. Look at chunk boundaries and whether exact terms need keyword search.
The retrieved chunk is on topic but out of date Source content Who owns the doc, and is the old version still in the index?
Two chunks disagree and the answer blends them Prompt Tell the model to flag conflicts and name both sources.
The answer adds a detail none of the chunks contain Generation Tighten the "only from sources" instruction and score faithfulness in your tests.
The answer is right but cites the wrong chunk Citation wiring Follow chunk IDs from retrieval into the prompt and back to the UI.
It answers when it should say "I don't know" Prompt and tests Add questions with no answer in your docs to the test set.

One more trap is stuffing the prompt with every chunk that looks close. Nelson Liu and colleagues found that language models use information best when it sits at the start or end of a long context, and that performance drops significantly when the key passage is in the middle (Lost in the Middle, TACL). They tested 2023 models, so measure with yours, but a handful of good chunks is a safer default than a big pile. For more ways to keep answers tied to evidence, see Reducing Hallucinations in LLMs, One Layer at a Time.

Test it with real questions before you trust it

A demo that answers five questions nicely tells you very little. Build a small test set instead: a few dozen real questions pulled from chat logs or support tickets, each paired with the document that should answer it. Throw in some questions your docs can't answer, so you can check the system admits it.

Then score the halves separately. The Ragas framework splits RAG quality into three parts: whether retrieval finds relevant, focused passages, whether the model uses them faithfully, and the quality of the answer itself (Es et al., 2023). Scoring them apart stops a retrieval bug from hiding behind a fluent answer, and stops a generation bug from getting blamed on search.

Once it's live, keep a list of questions that fail more than once. They usually point to a missing document, a doc nobody owns, stale content or a chunking choice that looked fine in a notebook and falls apart on real questions.

Three teammates go through source dates, citations and failed answers with a checklist, dashboards blurred behind them.
Tests stay honest when the team can see how fresh each source is, which citation backs each answer and where the docs are drifting.

The boring part decides the quality

RAG retrieves whatever you feed it. If your docs are outdated, duplicated or contradict each other, the system serves that mess with a citation attached. For many teams the hardest part of RAG is document hygiene: deciding which sources count, who updates them, how old versions get retired and which documents each user is allowed to see. Get that right and a plain setup works well. Skip it and no embedding model will save you.

If you're still deciding whether RAG is the right tool at all, Prompting, RAG or Fine-Tuning? helps you name the failure first.

Try this week

  • Pull ten real questions from your team chat and find the document that should answer each one. Where nobody's sure, you have a docs problem to fix before any RAG.
  • If you already run RAG, log the retrieved chunks next to every answer for a week.
  • Add three questions your docs can't answer to your test set and check the system says so.
  • Next time an answer is wrong, use the table above to name the layer before you change anything.
What did you think?

Frequently asked questions

What is retrieval-augmented generation (RAG)?
RAG is a setup where a system searches your own documents for relevant passages before a language model answers, then gives the model those passages along with the question. The model writes the answer from that material and can cite it. The name comes from a 2020 paper by Patrick Lewis and colleagues, which paired a language model with a searchable index of Wikipedia.
Does RAG stop AI hallucinations?
It reduces them but doesn't remove them. The model can still blend conflicting sources, add details the sources don't contain or answer when it should say it doesn't know. Showing citations and testing retrieval and generation separately is how you catch those cases.
Do I always need a vector database for RAG?
No. In September 2024 Anthropic suggested that if a knowledge base is under 200,000 tokens, about 500 pages, you can put all of it in the prompt and use prompt caching instead of building retrieval. Context limits vary by model, so check yours first. Many RAG setups also combine vector search with keyword search.
How do you evaluate a RAG system?
Build a test set of real questions, each paired with the document that should answer it, plus a few questions your docs can't answer. Score retrieval (did the right passages come back), faithfulness (did the answer stick to them) and answer quality separately. The Ragas framework uses roughly this split.