Quick Answer: How RAG works?
RAG works by splitting one hard job into two simpler ones: a retriever searches an external document store for passages related to the user’s question, and a generator then writes an answer conditioned on those passages. Teams use it to ground chatbots in private documents, cut down on invented facts, and refresh answers without retraining a model.
The original design came from a 2020 paper that paired a dense retriever with a sequence-to-sequence generator, and it defined two variants: one retrieval set for the whole answer, or fresh retrieval at every generated token. Modern systems stretch the term to cover keyword search, hybrid search, reranking, and multi-step agent loops.
Before building, check corpus freshness, chunk size, embedding model, retrieval metric, reranker need, latency budget, and how you will measure groundedness.
Why Anyone Bothers With Retrieval at All

Ask a language model about a company policy written last Tuesday and it will answer with total confidence and zero accuracy. That is the problem RAG was built to solve. Instead of hoping the model memorized something, you go fetch the relevant text first and hand it over.
The idea is simple enough to explain at a whiteboard, and the engineering is where it gets interesting. The term itself comes from a 2020 paper by Patrick Lewis and colleagues, and anyone building a system should read the original formulation of retrieval-augmented generation to see exactly what the authors proposed and what they did not claim.
The Two Halves: Retriever and Generator
Every RAG system, from a weekend prototype to a production assistant, has the same skeleton.
The retriever takes a query and returns a ranked list of passages from a corpus. The generator takes the query plus those passages and writes the answer. The corpus sits outside the model, which is the whole point: you can update a document without touching a single weight. (Write for 9481.org)
That separation is why RAG became popular so fast. Retraining a model is slow and expensive. Re-indexing a folder of PDFs takes minutes.
What Actually Happens in the Retriever
Retrieval comes in two broad flavors, and most serious systems use both.
Sparse retrieval matches words. BM25, the long-standing probabilistic ranking function still used as a baseline everywhere, scores documents by term overlap with some clever weighting for rarity and length. It is fast, cheap, and shockingly hard to beat on exact-match queries like part numbers or legal citations.
Dense retrieval matches meaning. A dual-encoder model maps queries and passages into the same vector space, so “how do I cancel my subscription” can find a document titled “ending your plan.” The Dense Passage Retrieval paper showed this approach outperforming BM25 on open-domain question answering, and it became the default for semantic search.
| Sparse (BM25) | Dense (embeddings) | |
|---|---|---|
| Matches on | Exact words and terms | Meaning and paraphrase |
| Strength | Rare tokens, IDs, codes | Natural-language questions |
| Weakness | Misses synonyms | Misses exact strings |
| Cost | Very low | Higher (embedding + index) |
| Best for | Structured or technical text | Conversational queries |
The practical answer for most teams is hybrid search: run both, merge the result lists, and let a reranker sort out the order. It costs more compute and buys noticeably better recall.
What Happens in the Generator
The generator receives a prompt assembled from the question and the retrieved passages, then produces text token by token. The 2020 paper described two modes worth knowing about. RAG-Sequence retrieves once and uses the same passages for the entire output. RAG-Token can, in principle, shift its retrieval as it generates each token, which allows more flexible answers at higher cost.
Most production systems today behave like RAG-Sequence with extra steps: retrieve, rerank, stuff into a context window, generate. The token-level variant is more of a research curiosity than a deployment pattern.
The Pipeline, Step by Step
Here is the sequence a real request travels through.
- Ingest. Documents are collected, cleaned, and stripped of boilerplate like navigation menus and footers.
- Chunk. Long documents are split into passages, typically a few hundred tokens each, with some overlap so a sentence is not orphaned across a boundary.
- Embed and index. Each chunk becomes a vector, stored in a vector database or an index like FAISS, the open-source library from Meta AI for similarity search over dense vectors.
- Query. The user’s question is embedded with the same model used at ingest time.
- Retrieve. The index returns the top-k nearest chunks. With hybrid search, a keyword index returns its own list in parallel.
- Rerank. A cross-encoder or similar model scores each candidate against the query and reorders them.
- Assemble the prompt. The best passages are inserted into a template alongside instructions and the question.
- Generate. The model writes an answer, ideally citing which passage supports which claim.
- Log and evaluate. The query, retrieved chunks, and answer are recorded so you can debug failures later.
Step nine is the one people skip, and it is the one that saves them.
Where RAG Quietly Breaks
Nobody warns you that most RAG failures are retrieval failures wearing a costume. The model gets bad context and writes a confident, fluent, wrong answer. Here is where it goes wrong most often.
Chunking destroys meaning. Split a table mid-row or a policy mid-exception and the retrieved passage is technically relevant but practically useless. Overlap helps. Respecting document structure helps more.
The wrong k. Retrieval of three chunks misses the answer that sits in chunk four. Retrieval of thirty buries the answer in noise and burns your context window. Tune this against real queries, not vibes.
Stale indexes. The corpus reflects whatever was indexed, including documents superseded six months ago. Contradictory sources produce contradictory answers, and the model has no reliable way to know which is current. Freshness is a pipeline problem, not a model problem.
Retrieval errors propagate. If the retriever returns irrelevant passages, the generator can still produce a polished answer that the sources do not support. RAG improves factual grounding. It does not guarantee it, and any vendor claiming it eliminates hallucination is overselling.
Embedding mismatch. Indexing with one model and querying with another produces garbage similarity scores. It sounds like an obvious mistake and it happens constantly when teams upgrade one component and forget the other.
No evaluation set. Without a fixed set of questions and known-good passages, every change is a guess. Track recall@k and mean reciprocal rank for the retriever, and groundedness or answer accuracy for the generator.
Practical Tips That Survive Contact With Production
Start with the boring baseline. Build BM25 retrieval over your corpus before you touch embeddings. It takes an afternoon, it gives you a number to beat, and it will occasionally outperform your fancy dense index on the queries that matter most.
Log everything from day one. Store the query, the retrieved chunk IDs, their scores, and the final answer. When a user complains, you can see in seconds whether the retriever missed or the generator wandered.
Let the model say “I don’t know.” A prompt that permits abstention when the passages do not contain the answer is worth more than another ten points of retrieval recall. Systems that force an answer from thin context invent things.
Treat citations as a feature, not decoration. Requiring the generator to name the passage behind each claim makes hallucination visible and gives reviewers something to check.
Watch latency. A reranker over fifty candidates can add hundreds of milliseconds. Hybrid search doubles your index infrastructure. None of this is free, and users notice.
Finally, keep an eye on how the term is used. RAG now describes everything from a single retrieve-then-generate call to multi-step agent loops that search, read, search again, and synthesize. The label has drifted well past the 2020 definition. If you are comparing systems, ask what the pipeline actually does rather than trusting the acronym. For ongoing coverage of how these systems are being built and discussed, the site’s blog and news sections track developments worth following. (News)
RAG Versus the Alternatives
RAG is not the only way to get a model to know things, and it is not always the right one.
| Approach | How it works | Best when |
|---|---|---|
| RAG | Retrieve documents at query time | Knowledge changes often; sources must be cited |
| Fine-tuning | Adjust model weights on examples | You need a style, format, or skill, not facts |
| Long context | Paste everything into the prompt | Corpus is small and fits the window |
| Prompt-only | Rely on what the model already knows | Question is general and stable |
Fine-tuning teaches behavior. RAG supplies facts. Confusing the two leads teams to fine-tune on a knowledge base and wonder why the model still cannot answer questions about last quarter’s numbers. Long context windows have absorbed some of RAG’s territory for small corpora, but cost and attention limits keep retrieval relevant once a document set grows past a few hundred pages.
Conclusion
RAG works because it refuses to make one model do two jobs. Retrieval finds the evidence; generation writes the answer. Everything that makes a system good or bad lives in the seams between those steps: how you chunk, what you index, how many passages you pull, whether you rerank, and whether you bothered to measure any of it.
The teams that succeed treat RAG as a search problem first and a prompting problem second. They build a baseline, log their failures, and tune against real queries. The teams that struggle ship a demo, skip evaluation, and discover six weeks later that their retriever has been returning the same three irrelevant chunks for every question.
Start simple. Measure honestly. Keep the corpus fresh. The rest is iteration.
Frequently Asked Questions
Does RAG stop a model from hallucinating?
No. It reduces the chance of unsupported claims by supplying evidence, but the generator can still misread, overgeneralize, or ignore the retrieved passages. Retrieval-augmented systems are measurably better grounded than closed-book models, yet they still fail when retrieval fails or when the model writes past its sources. (Blog)
Do I need a vector database to build RAG?
Not necessarily. For small corpora, a keyword index or even an in-memory array of embeddings works fine. Vector databases earn their keep when you need persistence, filtering, replication, and fast approximate search at scale. Start with the simplest thing that returns decent results, then upgrade when you hit a wall.
What chunk size should I use?
There is no universal number, but a few hundred tokens with modest overlap is a reasonable starting point. Smaller chunks improve precision and lose context; larger chunks preserve context and dilute relevance. Test against your own queries, and respect document structure such as headings, tables, and lists rather than splitting on character count alone.
Is fine-tuning a replacement for RAG?
They solve different problems. Fine-tuning adjusts how a model behaves, including tone, format, and task skill. RAG supplies current, specific, citable facts. Teams often need both, and using fine-tuning to inject facts that change weekly is a fast route to stale answers and wasted compute.
How do I measure whether my RAG system is any good?
Evaluate the retriever and the generator separately. For retrieval, track recall@k and mean reciprocal rank against a labeled set of question-passage pairs. For generation, check whether claims are supported by the retrieved context and whether the answer matches a reference. A small, curated evaluation set beats a large, vague one.
Can RAG handle images, tables, and PDFs?
It can, with extra work. Tables usually need structure-aware parsing so rows stay intact, and scanned PDFs need optical character recognition before chunking. Images require either captions or a multimodal embedding model. These formats are where most ingestion pipelines quietly fall apart, so budget time for them.
Where should a team start when building its first RAG system?
With a hundred real user questions and the documents that should answer them. Build keyword retrieval first, measure it, then add embeddings and reranking one change at a time. Keep a log of every query and retrieved chunk. That log becomes your evaluation set, your debugging tool, and eventually your roadmap.







