Retrieval-Augmented Generation
The questions here are about a product that does not exist, so no model has ever read a word about it. Retrieval is the only thing standing between a cited answer and a confident invention.
Overview
Quick Context
A language model knows what was in its training data, frozen at some cutoff date. It does not know your company's handbook, last week's incident report, or a product invented for a teaching page. Asked anyway, it will answer — fluently, and wrongly.
Retrieval-augmented generation is the fix that does not involve training anything. Find the passages that look relevant, paste them into the prompt, and ask the question with the evidence attached. The model stops recalling and starts reading.
The Question
0 means no retrieval at all — the model on its own
This Retrieval
1. The Index — Every Chunk Scored
—2. The Prompt Actually Sent
3. What Comes Back
Why This Chunk
The Trade
RAG: A Practical Guide
Give the model the page before you ask it the question.
The pipeline
- Chunk. Split the documents into passages small enough to be specific and large enough to stand alone.
- Embed. Turn each chunk into a vector with an embedding model, and store it.
- Retrieve. Embed the question the same way and find the nearest chunks, usually by cosine similarity.
- Augment. Paste the top k chunks into the prompt above the question.
- Generate. The model answers from what is in front of it, and can cite it.
Only steps 3 to 5 happen per question. Steps 1 and 2 happen once, when the documents change — which is why RAG updates in the time it takes to re-index rather than the time it takes to retrain.
The scores on this page are real cosine similarities over word-frequency vectors rather than a neural embedding, so the retrieval you are watching genuinely runs. A production system embeds meaning rather than words, which is exactly why it can match "descale" to "limescale" where this cannot.
Giving a model documents instead of retraining it
A language model knows what was in its training data, up to a cut-off date. It does not know your company's handbook, last week's incident report, or the contents of a customer's account.
Two ways to fix that. Fine-tuning updates the weights on your data — expensive, slow to iterate, and it teaches style and format far better than it teaches facts. Retrieval-augmented generation leaves the model alone and puts the relevant documents into the prompt.
The pipeline has two halves, and the first is done once:
Indexing (offline). Split documents into chunks, embed each chunk into a vector, store the vectors in an index.
Retrieval and generation (per query). Embed the question, find the nearest chunks, paste them into the prompt with the question, and let the model answer from them.
question → embed → search → top k chunks → prompt → answer + citations
Why it is usually the right first choice
| RAG | Fine-tuning | |
|---|---|---|
| Adds new facts | Yes | Poorly |
| Update cost | Re-index a document | Retrain |
| Citations | Natural — you know the source | Impossible |
| Access control | Filter at retrieval | Baked into weights |
| Teaches format and tone | Weakly | Well |
| Inference cost | Higher — longer prompts | Unchanged |
The citation row is the one that decides most enterprise deployments. If an answer must be traceable to a source document, retrieval gives you that for free and fine-tuning cannot give it at all.
The access-control row matters nearly as much. Fine-tuning on documents means the model can reproduce them for anyone; retrieval means permissions can be enforced at query time, per user.
Where RAG systems actually fail
Almost never in the language model. The failures are in retrieval, and they have distinct causes:
The right chunk was never retrieved. The most common failure by a wide margin. Poor chunking, an embedding model that does not cover the domain vocabulary, or a query phrased differently from the document.
The chunk was retrieved but incomplete. A table split down the middle, or a paragraph whose subject was named in the previous chunk.
The right chunk was buried. Retrieved at position 9 of 10, where models attend to it less — the "lost in the middle" effect.
Contradictory chunks. Two versions of a policy retrieved together, and the model picks one arbitrarily.
The model ignored the context and answered from its parametric knowledge instead.
That distribution is why the practical advice is: measure retrieval separately from generation. Recall@k on a set of question-and-known-answer pairs tells you whether the right chunk is even reaching the model. Debugging the prompt when recall is 0.4 is wasted effort.
Where the quality actually comes from
A RAG pipeline is a chain, and a chain's output is bounded by its weakest link -- which means the arithmetic of stage-by-stage success rates tells you where to spend your effort. This computes that, and then shows why the obvious first instinct is usually the wrong one.
Guided tour
- Turn retrieval off. Set Chunks Retrieved to 0. The prompt is the bare question, and the answer is what a model does when it has nothing: something plausible and unsupported, flagged in red.
- Turn it back on. At k = 1 the top-scoring chunk is pasted in and the answer arrives with a citation. Same model, same question, different prompt.
- Meet the distractor. Ask about the warranty and read the scores: chunk 1 wins on 0.213, but chunk 7 — the warranty for the previous model — is right behind it on 0.183, because it talks about warranties too. At k = 1 the ranking has to be right; at k = 2 breadth covers you instead. Retrieval fails quietly, and this is the shape it fails in.
- Watch the prompt grow. Push k to 6 and the prompt words climb steeply. Everything you retrieve is paid for on every request, in latency and in cost, and the useful chunk gets harder for the model to find among the noise.
- Ask something the documents do not cover. Choose the voltage question. Retrieval still returns its best matches — it always returns something — but none of them answer it, so the honest response is "not in the documents". A system that cannot say that is a system that will invent.
Why not just fine-tune?
Fine-tuning changes how a model behaves; retrieval changes what it knows right now. Facts that change weekly, documents with access rules, anything that needs a citation — all of those want retrieval. Tone, format, a domain's vocabulary, a stubborn output schema — those want fine-tuning. They are not competitors, and production systems often use both.
Retrieval also has a property fine-tuning cannot offer: you can show the user where the answer came from, and delete a document and have it genuinely gone.
Common mistakes
- Chunking badly. Too small and a passage loses the context that made it meaningful; too large and the embedding averages several topics into mush. Overlapping windows of a few hundred tokens are the usual compromise.
- Assuming retrieval succeeded. Similarity search always returns its best k, however bad they are. Without a relevance floor, an unanswerable question quietly becomes a confident wrong answer.
- Stuffing the context. More chunks is not more accuracy. Models attend unevenly across a long context, and a fact buried in the middle of twenty passages can be missed entirely.
- Pure vector search. Embeddings are poor at exact identifiers — part numbers, error codes, names. Hybrid retrieval, combining keyword search with vectors, is standard for a reason.
- A stale index. The documents changed and nobody re-embedded them. Now the system cites yesterday's policy with complete confidence.
What to remember
RAG answers questions a model was never trained on by finding relevant passages and putting them in the prompt, so generation becomes reading rather than recall. The retrieval step is ordinary similarity search and it always returns something, which makes the quality of your chunking, your ranking and your "I could not find it" path the whole ballgame. Raising k buys robustness against a bad ranking and costs latency, money and attention, so it is a trade rather than a setting. Use retrieval for facts that change or need citing, fine-tuning for behaviour that needs to change, and never assume the top result was actually relevant.
The decisions that determine quality
Chunk size. 200–500 tokens is the usual range. Too small and the chunk lacks context; too large and the embedding is a blurred average of several topics, and the prompt fills up. Overlap of 10–20% keeps sentences that straddle a boundary intact.
Chunking strategy. Splitting on structure — headings, sections, paragraphs — beats splitting on a fixed character count almost always, because it respects where topics actually change.
Hybrid retrieval. Combine dense embedding search with keyword search (BM25). Embeddings catch paraphrase; keywords catch names, codes, numbers and exact terms that embeddings blur. Reciprocal rank fusion merges the two ranked lists. This is the single highest-value improvement in most systems.
Reranking. Retrieve 50 candidates cheaply, then score each against the query with a cross-encoder that reads both together. Far more accurate than embedding similarity, affordable because it runs on 50 items rather than a million.
How many chunks to pass. 3–10 typically. More is not better: irrelevant context degrades answers, and the middle of a long context receives less attention.
Prompting the generation step
Three instructions do most of the work:
Answer using only the provided context. If the context does not contain
the answer, say "I don't know based on the available documents."
Cite the source id after each claim.
Context:
[1] {chunk_1}
[2] {chunk_2}
Question: {question}"Only the provided context" reduces the model answering from memory, which is what produces confident wrong answers about your domain.
An explicit escape hatch matters more than it looks. Without permission to say "I don't know", a model will construct something plausible from whatever it was given.
Numbered sources make citations checkable, which is what turns an answer into something an auditor can verify.
Measuring it
Evaluate the two stages separately, then end to end:
| Stage | Metric |
|---|---|
| Retrieval | Recall@k, MRR, nDCG |
| Generation, faithfulness | Groundedness — is every claim supported by the context? |
| Generation, usefulness | Relevance and completeness against the question |
| End to end | Correctness against known answers |
Build a small evaluation set — 50–100 real questions with known correct answers and known source documents — before optimising anything. Without it, changes to chunk size and prompt wording are guesswork, and the usual outcome is a system that feels better and measures worse.
Questions people ask
RAG or fine-tuning? RAG for facts, currency, citations and access control. Fine-tuning for format, tone and task-specific behaviour. They combine.
How large a corpus can this handle? Millions of chunks, with an approximate index. Below about 100,000, a plain vector matrix and a dot product is adequate.
Do long context windows make RAG obsolete? No. Retrieval is cheaper, more precise, and it tells you which source an answer came from. Stuffing a million tokens is expensive and dilutes attention.
Why does it hallucinate even with the right context? Usually the prompt does not constrain it firmly enough, or the context is contradictory, or the answer genuinely is not there and it has no permission to say so.
Which embedding model? Start with a strong general one, then test domain-specific alternatives on your own evaluation set. The benchmark leaderboard is a weaker signal than your own data.
Should I re-embed when I change models? Yes — vectors from different models are not comparable, so the whole corpus must be re-indexed.
Recap in one screen
- Index documents as embedded chunks; at query time retrieve the nearest and put them in the prompt.
- It adds facts, supports citations and enforces permissions — none of which fine-tuning does well.
- Almost all failures are retrieval failures, so measure recall separately before touching the prompt.
- Hybrid search plus reranking is the highest-value improvement in most systems.
- Instruct the model to use only the context and to admit when the answer is absent.