5. Retrieval-augmented generation
Why and how to ground LLM answers in your own documents. The RAG pipeline step by step, chunking, context building, citations, failure modes, and RAG versus fine-tuning and long context.
The problem RAG solves
A model knows only what was in its training data, up to a cut-off date. It does not know your employee handbook, last week’s tickets or your product catalogue, and when asked, it may confidently make something up. Retrieval-augmented generation (RAG) (Lewis et al., 2020) fixes this by retrieving relevant passages from your data at question time and putting them in the prompt, so the model generates an answer grounded in them.
Benefits:
- Fresh and private knowledge without retraining: update documents, re-index, done.
- Fewer hallucinations, because the model answers from evidence and can say I don’t know.
- Citations: users can verify claims against sources.
- Access control: retrieve only what this user may see.
The pipeline
flowchart LR
subgraph Indexing
A[Load] --> B[Clean] --> C[Chunk] --> D[Embed] --> E[(Vector store + keyword index)]
end
subgraph Answering
Q[Question] --> R[Retrieve top-k] --> S[Build context] --> T[Generate with citations] --> U[Verify citations]
end
E --> R1. Load and parse
Turn files into text with structure and metadata: PDFs (per page, so citations can name pages), Word, slides, spreadsheets, HTML, Markdown, JSON. Scanned documents need OCR. Keep source metadata (filename, page, section): you will need it for citations and filters.
2. Clean
Normalise Unicode, remove control characters, join words hyphenated across lines, collapse whitespace, drop empty pages. Garbage in, garbage retrieved.
3. Chunk
Split documents into chunks, the unit of retrieval. Chunk size is a trade-off:
| Smaller chunks (100–300 tokens) | Larger chunks (800–1500 tokens) |
|---|---|
| Precise matching | More context per hit |
| Facts may be split across chunks | Matching is diluted by unrelated text |
| More chunks to store and rank | Fewer chunks fit in the prompt |
Overlap (repeating a little text between neighbouring chunks) reduces the chance of cutting a fact in half. Better still is structure-aware chunking: split at headings, keep tables and lists whole, pack whole sentences. Semantic chunking splits where the topic changes. Parent-child chunking matches on small chunks but sends their larger parent sections to the model (chapter 6).
Keep exact offsets from each chunk back into its source: citations can then highlight the precise span, and evaluation can check which chunk was retrieved.
4. Embed and index
Embed each chunk (chapter 4) and store vector + text + metadata. Also build a keyword index (BM25) for exact-term matching. Re-index incrementally: skip chunks whose content hash has not changed.
5. Retrieve
Embed the question, fetch the top-k most similar chunks (k = 3–10 typically), optionally with metadata filters and a minimum score. Advanced pipelines rewrite the query, combine vector and keyword search, and rerank (chapter 6).
6. Build the context
- Number the chunks as sources
[1],[2], … - Deduplicate identical or overlapping chunks.
- Fit a token budget: the best chunks first.
- Order: by relevance, or by reading order for narrative documents.
- Instruct: answer only from the sources, cite each claim, say I don’t know if the sources do not contain the answer.
7. Generate and verify
The model answers with citation markers. The system then verifies citations: parses [n], maps them to real sources, removes markers that point nowhere, and optionally rejects answers with no valid citation. Verifying that a cited passage actually supports the claim is harder: that is faithfulness or groundedness, usually measured with an LLM judge (chapter 12).
Why RAG fails (and what to do)
| Symptom | Likely cause | Fix |
|---|---|---|
| Right answer exists, model says I don’t know | Retrieval missed it | Hybrid search, query rewriting, better chunking, larger k |
| Right chunk retrieved but ranked 8th | Weak first-stage ranking | Reranker |
| Answer mixes up two policies | Chunks lack context (which section?) | Keep section headings in chunks; parent-child; contextual headers |
| Follow-up questions fail (and for managers?) | Query is not standalone | Query rewriting with chat history |
| Answer contradicts the source | Model ignored context, or too much noise | Stronger instructions, fewer but better chunks, compression, a better model |
| Confident answer, no source | Grounding not enforced | Require citations; evaluate groundedness |
| Tables come out garbled | Parsing lost structure | Layout-aware parsing; keep tables whole |
The golden rule: debug retrieval before generation. Look at what was retrieved for a failing question. If the evidence is not there, no prompt will save the answer.
RAG vs fine-tuning vs long context
| Approach | Best for | Weak at |
|---|---|---|
| RAG | Facts that change, private data, citations, access control | Teaching new skills or styles |
| Fine-tuning | Consistent format, tone or a narrow skill; smaller models doing one task well | Keeping facts fresh; citing sources; cost of retraining |
| Long context (paste everything) | Small corpora, one-off analysis | Cost and latency on every call; lost in the middle; scale |
They combine: a fine-tuned model can use RAG, and long context windows let RAG pass more chunks.
Agentic RAG
In a fixed pipeline, retrieval happens exactly once. In agentic RAG, an agent has a search tool and decides when to search, what to search for, and whether to search again after reading results, combining it with other tools (a calculator for 3 employees × 25 days). More flexible, more expensive, harder to predict. Start with a pipeline; move to an agent when questions need multiple hops or tools.
Try it in AgenticMind
- RAG answers with citations: the full basic pipeline, from Document Loader to Citation Builder.
- Advanced RAG: Query Rewriter, Hybrid Search, Reranker, Context Compressor.
- RAG with parent-child chunks: layout-aware parsing and parent expansion.
- Agent with tools: agentic RAG with a Knowledge Search tool.
- The Evaluation Lab with
examples/datasets/employee-handbook-qa.jsonmeasures retrieval (recall@K, MRR) and answers (required facts, citations, judges).
See RAG pipelines for settings.
Key takeaways
RAG retrieves relevant passages at question time and asks the model to answer from them with citations. Quality is decided by parsing, chunking and retrieval more than by the model. Debug retrieval first. Use RAG for facts, fine-tuning for behaviour, and measure both with an evaluation set.

