Book a 30-min callBook a call

RAG explained: how retrieval-augmented generation works, step by step

How retrieval-augmented generation works, step by step: parsing, chunking, embedding, indexing, retrieval, reranking and prompting, with a Python sketch.

Documents passing through three pipeline boxes into a field of dots, three of them circled, which feed a chat bubble.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
13 min read

Questions people ask

How many chunks should a RAG system retrieve?

There is no universal number. A common shape is to retrieve a few dozen candidates, rerank them, and pass somewhere between five and twenty to the model. Anthropic reports that passing the top 20 chunks worked better than 5 or 10 in its tests. More passages raise recall but cost tokens and can bury the best one, so measure on your own questions.

Do I need a vector database for RAG?

Not always. A few thousand chunks can be searched exactly with a flat scan in memory, and many relational and search databases now offer vector indexes. A dedicated vector database earns its place with large collections, heavy filtering or high query volume.

Is a long context window a replacement for RAG?

For a small, stable set of documents, putting all of it in the prompt can be simpler and works well. For large or changing collections, retrieval keeps prompts smaller and faster, lets you enforce per-user access, and gives you citations. Long prompts also suffer from the lost-in-the-middle effect, so even a large window benefits from putting the relevant passages first.

Does RAG stop hallucinations?

It reduces them for questions your documents answer, because the facts are in front of the model. It does not stop them: the model can misread a passage, blend in what it memorized, or answer when retrieval found nothing relevant. Citations, an allowed "not in the sources" answer and tests with unanswerable questions make those failures visible.

Building something like this?