SimpleA plain explanation, one diagram and an analogy, with where the analogy breaks.
Guess first: When you're unsure of an answer, what do you do before replying? Show the answerYou look it up. RAG makes the model look things up first instead of guessing from memory.
If you ask a friend a question about a local museum, they might check the museum's website before answering.
RAG makes the AI look things up first instead of guessing from memory.
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.
How it worksAn interactive demo first, then the mechanism: light maths, pseudo-code and trade-offs.
Try it
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. The mechanism section below 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.
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?
The mechanism
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)?
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.
ResearchWhere the simple picture breaks, open problems and primary sources.
"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.
Security on this concept: 2 threats Pending expert review
Hidden instructions in content the AI reads Pending expert review
Exposed
Emails, web pages, documents and tool results that enter the model's context
Private data and outbound channels the assistant can reach
Attacks
Planting instructions in content the assistant will read (indirect prompt injection)
Leaking data through links or images the app loads automatically
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.
Prompt injection Instructions hidden in text an AI reads (a web page, an email, a file, a tool result) that make it do what an attacker wants instead of what its user asked.
Tool poisoning Attacks through the tools an AI agent installs: hidden instructions in a tool's description, look-alike packages, or a trusted tool that changes after you install it.