Retrieval-Augmented Generation (RAG)
Retrieval puts the facts in the prompt instead of the weights. Indexing, chunking and re-ranking, and the failures that survive good retrieval.
Jump to a section
Answers the weights cannot hold
A support assistant is asked for the cancellation deadline on a plan whose terms changed last month. The model's weights were fixed long before that, so whatever it says comes from an outdated policy or from nowhere. Retraining for every policy edit is not an option.
Retrieval-augmented generation (RAG) leaves the weights alone and changes the input instead. Before the model answers, the system searches a document collection for passages relevant to the question and places them in the prompt. Update a document, re-index it, and the next answer can use it.
The original RAG paper (Lewis et al., 2020) did this over Wikipedia: a December 2018 dump split into 100-word passages, about 21 million of them. A dense retriever encoded the question, fetched the top 5 or 10 passages, and a BART generator conditioned on them. The pattern has since become standard, usually with a general-purpose LLM in place of the trained generator.
RAG has two separate places to fail. Finding the right evidence is necessary but not sufficient: the generator can still misread it, drop a qualification, or add a claim the evidence does not support.
Indexing offline, retrieving at query time
The common implementation splits documents into chunks offline and embeds each chunk with an encoder into a vector index. At query time the question is embedded into the same space, the nearest chunks are retrieved, and they are pasted into the prompt as context. The model then answers from that evidence instead of from its parametric memory alone.
Retrieve evidence before generating
Retrieved passages enter the prompt alongside the question.
Exact inputs and equations appear with the figure.
Preparing the scientific figure…
A retrieval pipeline schematic. The index is built offline from the embedded corpus; access checks and reranking are omitted. Retrieved context does not guarantee correctness.
Authored analytic exampleExperiment with related Studio inputs
Follow the question through retrieval into the model’s prompt. Retrieved passages provide evidence for the answer, not a guarantee of correctness.
This view assumes the corpus has already been chunked, embedded, and indexed. Reranking and access checks are not shown.
Read the related Studio connections
Question -> Encode query : query Encode query -> Retrieve chunks : vector Retrieve chunks -> Build prompt : passages Build prompt -> Generate answer : question + context
Relevance is estimated by similarity in the embedding space. With cosine similarity, chunk scores
and the retriever keeps the highest-scoring chunks, . The prompt becomes and the model decodes as usual. Some retrievers use the raw dot product instead; DPR, the retriever inside the original RAG, scores by inner product.
None of this requires a vector database. Keyword retrieval such as BM25, or a hybrid of keyword and vector search, is RAG too. Keyword search is often better at exact identifiers, product codes and rare names, which embeddings tend to blur together.
Chunks, recall and re-ranking
Two levers decide most of the quality. The first is chunking. A chunk must be small enough that its embedding is about one thing, and large enough to stand on its own when pasted into a prompt. A chunk that says "the deadline is 14 days" without naming the plan retrieves well and answers badly.
The second is retrieval quality, usually measured as recall@k: how often the passage that answers the question appears in the top . If it is not there, the generator has nothing to ground the answer on, however capable it is.
Exact top- search compares the query with every vector, which is slow at scale. The original paper's index is 21 million 768-dimensional vectors, about 64.5 GB in fp32 before any compression. Approximate nearest-neighbour indexes such as HNSW (a navigable graph) and IVF (clustered lists) search a small fraction of the vectors and occasionally miss a true neighbour in exchange.
A common way to recover precision is a re-ranker. The first stage casts a wide net, returning more candidates than the prompt needs, and a stronger model such as a cross-encoder reads the query and each candidate together and re-scores them. Only the best few go into the prompt.
More context is not free. Each chunk costs prompt tokens, and models use evidence unevenly: Liu et al. found that accuracy on multi-document question answering dropped when the relevant passage sat in the middle of a long context rather than near its start or end. Order the chunks with that in mind, and prefer a few good ones to many marginal ones.
In code
This toy uses word-count vectors, not learned embeddings, so its retrieval is lexical. It shows indexing, cosine ranking and prompt assembly with no external service; a semantic retriever would replace embed with a trained encoder.
1import math
2import re
3from collections import Counter
4
5docs = ["Batch norm normalizes per feature.", "Attention scales by sqrt(d_k).", "RAG retrieves context."]
6
7
8def embed(text):
9 return Counter(re.findall(r"[a-z_]+", text.lower())) # word counts, not learned embeddings
10
11
12def cosine(a, b):
13 dot = sum(count * b[word] for word, count in a.items())
14 norm = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values()))
15 return dot / norm if norm else 0.0
16
17
18index = [embed(doc) for doc in docs] # offline: index the chunks
19
20
21def retrieve(query: str, k: int = 2) -> list[str]:
22 q = embed(query)
23 scores = [cosine(q, d) for d in index] # similarity to every chunk
24 top = sorted(range(len(docs)), key=scores.__getitem__, reverse=True)[:k]
25 return [docs[i] for i in top if scores[i] > 0] # no match: no evidence
26
27
28query = "how does attention scale scores?"
29context = retrieve(query)
30assert context == [docs[1]]
31assert retrieve("what is the cancellation deadline?") == []
32prompt = "Context:\n" + "\n".join(context) + f"\n\nQuestion: {query}\nAnswer only if the context supports it."The second assertion matters as much as the first. When nothing relevant is found, the retriever returns nothing, and the prompt should make "I don't know" an acceptable answer.
RAG or fine-tuning
Use RAG for knowledge and fine-tuning for behaviour. RAG puts knowledge in at inference time through the index, so updating it means re-indexing documents, and fresh or private data fits naturally. It can show which sources were retrieved, although each claim in the answer still needs checking against them.
Fine-tuning bakes changes into the weights. Every knowledge update needs a new training run, and the weights do not record where a fact came from. Where fine-tuning earns its cost is style, output format and task behaviour, which are hard to convey through retrieved passages. The two combine well: a model fine-tuned to read retrieved context carefully still gets its facts from the index.
Where it goes wrong
Take the cancellation question again. Retrieval returns three passages, all from the old policy. The generator quotes them accurately and gives the wrong deadline for the current plan. Nothing in the fluent answer reveals which stage failed.
So check the stages separately. Was the current policy indexed? Did a metadata filter, such as product or date, drop it? Did it rank high enough to make the top ? Did it survive into the prompt? Did the answer stay within what it says?
For each evaluation case, keep the question, the source versions, the retrieved passage IDs and scores, the context actually supplied, the answer, and whether each claim is supported. Measure retrieval (recall@k) and generation (faithfulness to the supplied context) separately, since a single end-to-end score cannot tell you which one to fix.
Two habits prevent the worst failures. Treat retrieval similarity as a ranking signal, not as a probability that a passage answers the question. And when the evidence is missing, let the answer say so, rather than filling the gap with a confident citation to a passage that does not support it.
Sources and further reading
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks: combining retrieval with generation; the toy code here illustrates prompt assembly, not the paper's full trained architecture.
- Karpukhin et al., Dense Passage Retrieval for Open-Domain Question Answering (2020): the dual-encoder retriever used inside the original RAG.
- Liu et al., Lost in the Middle: How Language Models Use Long Contexts (2023): where in the prompt retrieved evidence gets used.
Keep going
Ask your own question about Retrieval-Augmented Generation (RAG), or start a guided session on it: six short pages, from the big picture to code you can run.