Retrieval-augmented generation (RAG)
Look up relevant documents first, then give them to the model to answer from.
Read first: How a model predicts the next token.
D1 · StoryFor young children and total beginners
If you ask a friend a question about your school, they might check the school website before answering.
RAG makes the AI look things up first instead of guessing from memory.
Look it up first, then answer
- Your question
- Look it up: search pages you trust
- Add what was found: next to the question
- Answer: based on what it found
Like: Checking the website before answering.
D2 · PictureFor curious beginners
Documents are split into chunks and turned into vectors (embeddings) stored in an index.
At question time the question is embedded too; the closest chunks are retrieved, often combined with keyword search and re-ranked, and placed in the prompt.
The model answers from that context, ideally with citations. Quality depends mostly on retrieval: if the right chunk isn't found, the model can't use it.
Answering with retrieval
- Question
- Embed: to a vector
- Search: vector + keyword
- Re-rank: best chunks
- Prompt: chunks + question
- Answer: with citations
Like: An open-book exam.
Where it breaks: In an open-book exam you choose what to read. In RAG the model only sees what retrieval hands it, and it can still blend in its own, possibly wrong, memory.
D3 · PlayFor motivated learners
Before the model sees anything, retrieval decides what it reads. The documents are cut into chunks, every chunk is scored against the question, and only the top few are pasted into the prompt.
Here the score is simple word overlap, weighted so rare words count for more (TF-IDF). Production retrieval is often hybrid: keyword scoring like this plus embeddings, which match meaning rather than exact words, often followed by a reranker. D4 opens that up. The shape stays the same: rank, cut, paste.
Change the chunk size and how many chunks are kept, then read the box at the bottom. That box is everything the model gets. If the answer is not in it, the model cannot give it.
Try the interactive version in the map.
Things to try
- Pick "Last winter ferry" with chunks of 20 words. Is the time in the context? Now raise the chunk size until it is.
- Pick "North cliffs in June". No passage says "June". Is the answer in the context anyway, and what does the model still have to work out for itself?
- Type your own question using different words from the passages, such as "seabird breeding season". What does word overlap miss that meaning-based search might find?
D4 · MechanismFor practitioners
Production retrieval usually runs two searches over the same chunks. Keyword search (BM25) scores a passage by the query words it contains, weighting rare words more and long passages less. Meaning search compares embeddings: vectors that put texts with similar meaning close together.
Each fails in its own way. Keyword search misses paraphrases; meaning search blurs exact strings such as error codes, IDs and names. Reciprocal rank fusion merges the two lists using ranks alone: RRF(d) = Σ 1 ÷ (k + rank), with k = 60 in the original paper. A reranker then reads the query together with each of the top few candidates and reorders them. Only the top k go into the prompt.
BM25 and RRF below are the real formulas. The meaning search and the reranker are small hand-made stand-ins, so their numbers are illustrative. The table at the end is how retrieval is measured: for test questions with known answers, what share of the right passages reach the top k (recall@k)?
Try the interactive version in the map.
Things to try
- Pick "Error code". Where does the meaning search put the E-4013 page, and why does the "30 days" passage score at all?
- Pick "Paraphrase". Keyword search puts the profile picture page first. What lifts the password page into the prompt: the fusion or the rerank?
- Compare the recall table at top k = 2 and at 3. Which method needs the bigger k, and what does each extra passage cost the prompt?
- Set the RRF constant to 1, then 60. How much more does a first place count than a third place under each?
def retrieve(query, k=5, pool=50, c=60):
by_words = bm25_index.search(query, top=pool) # exact terms; rare words weigh more
by_meaning = vector_index.search(embed(query), top=pool) # nearest neighbours by cosine
fused = {}
for results in (by_words, by_meaning):
for rank, doc in enumerate(results, start=1):
fused[doc] = fused.get(doc, 0) + 1 / (c + rank) # reciprocal rank fusion
shortlist = sorted(fused, key=fused.get, reverse=True)[:pool]
scores = reranker.score(query, shortlist) # reads query and passage together
best = sorted(zip(shortlist, scores), key=lambda x: x[1], reverse=True)
return [doc for doc, _ in best[:k]]
def recall_at_k(test_set, k): # test_set: (question, set of relevant ids)
found = [len(set(retrieve(q, k)) & relevant) / len(relevant) for q, relevant in test_set]
return sum(found) / len(found)Trade-offs
- Two indexes cost more to build, store and keep up to date than one, but each covers the other's blind spot: exact codes and names for keyword search, paraphrases for meaning search.
- RRF needs no tuning and never compares raw scores, which is why it is a common default. It also throws away how confident each search was; a weighted blend of scores can do better but has to be tuned for each collection.
- A reranker is slower per passage than either search, so it only sees a shortlist. It cannot rescue a passage that neither search returned.
- A bigger top k raises recall but makes the prompt longer, slower and dearer, and gives the model more irrelevant text to read past.
- Recall@k needs test questions with the right passages marked. Building that set is tedious, but without it you cannot tell whether a change to chunking, search or reranking helped.
D5 · FrontierFor experts
"Retrieve, then answer" assumes the right passage is found and then used faithfully. Neither is guaranteed.
Faithfulness. On one citation benchmark even the best models lacked complete support for their claims about half the time (ALCE, 2023).
Retrieval or long context? Given enough compute, long-context models beat retrieval on average but cost far more; routing each query to one or the other is one compromise (Li et al., 2024).
Poisoned knowledge. Five crafted texts per target question, planted among millions, steered answers 90% of the time (PoisonedRAG, 2024). Anyone who can write to your index can write to your answers.
Agentic retrieval. Letting the model decide when to search and critique what it found can beat fixed retrieval (Self-RAG, 2023), but adds steps, cost and new ways to go wrong.
Examples as of 2026-10-30
- Vector databases: pgvector, Pinecone, Weaviate, Qdrant
- Frameworks: LlamaIndex, LangChain
- Embedding models from OpenAI, Cohere and Voyage AI (MongoDB)
Sources
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020)
- Retrieval-Augmented Generation for Large Language Models: A Survey (2023-12-18)
- Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (Cormack, Clarke and Büttcher, SIGIR 2009) (2009)
- The Probabilistic Relevance Framework: BM25 and Beyond (Robertson and Zaragoza) (2009-12-17)
- Retrieve & Re-Rank (Sentence Transformers documentation) (2026)
- Reciprocal rank fusion (Elasticsearch reference) (2026)
- Enabling Large Language Models to Generate Text with Citations (2023-05-24)
- Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach (2024-07-23)
- PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models (2024-02-12)
- Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection (2023-10-17)
How it connects
- Retrieval-augmented generation (RAG) grounds The agent loop.
- Retrieval-augmented generation (RAG) supplies your data to AI features inside products.
- Retrieval-augmented generation (RAG) supplies passages to Context engineering.
- Memory searches past notes via Retrieval-augmented generation (RAG).
More in Layer 7 · Orchestration & Tooling
- Tool use & protocols (MCP)
Letting a model call functions and services through structured requests, standardised by protocols such as MCP. - Memory
How an AI application remembers beyond one call: short-term memory in the context window, long-term memory in stores it saves to and searches. - Context engineering
Choosing what goes into the model's context window, in what order, and what to leave out, because the model sees nothing else. - Guardrails & evals
Checks around model calls (input and output filters, permission gates, prompt-injection defences) plus automated tests that measure whether the system still behaves.