Simple definition#
Retrieval-augmented generation (RAG) answers a question in two steps: first retrieve the most relevant pieces of your own documents, then ask the LLM to generate an answer using those pieces as context.
Analogy: an open-book exam. The model is a smart student who has not read your company handbook. RAG hands them the right pages before they answer.
The problem RAG solves#
An LLM on its own:
- does not know your private data (policies, contracts, tickets, product docs);
- does not know anything after its training cutoff;
- cannot tell you where an answer came from;
- invents plausible answers when it does not know.
Fine-tuning does not fix these well (see prompting vs RAG vs fine-tuning). RAG does: knowledge stays in your systems, is updated by re-indexing, can be filtered per user, and every answer can cite its sources.
The two pipelines#
RAG is really two systems: an offline ingestion (indexing) pipeline and an online query pipeline.
flowchart TB
subgraph Ingestion["Ingestion pipeline — offline, continuous"]
direction LR
S["Sources<br/>SharePoint, Confluence, PDFs,<br/>databases, tickets"] --> L["Load & parse<br/>text, tables, metadata"]
L --> C["Clean & chunk<br/>split into passages"]
C --> E1["Embed chunks<br/>embedding model"]
E1 --> I[("Vector store<br/>+ keyword index<br/>+ metadata & ACLs")]
end
subgraph Query["Query pipeline — online, per request"]
direction LR
Q["User question"] --> E2["Embed query<br/>same embedding model"]
E2 --> R["Retrieve top-k<br/>similar chunks + filters"]
R --> A["Augment prompt<br/>instructions + chunks + question"]
A --> G["Generate<br/>LLM"]
G --> O["Answer + citations"]
end
I --> R
Ingestion, step by step#
- Load — connectors pull documents from source systems, with metadata (title, URL, owner, date, permissions).
- Parse — extract clean text from PDF, Word, HTML, slides; handle tables and images (OCR, or a vision model for complex layouts).
- Chunk — split into passages of a few hundred tokens so each chunk is about one topic. See chunking.
- Enrich — add metadata: section headings, document type, product, region, access-control lists; optionally summaries or keywords.
- Embed — convert each chunk into a vector with an embedding model.
- Index — store vector, text and metadata in a vector database, usually also a keyword (BM25) index.
- Keep fresh — detect changes and deletions in sources and re-index incrementally.
Query, step by step#
- Understand the question — optionally rewrite it (resolve “it” from chat history, fix typos, expand acronyms).
- Embed the question with the same embedding model used for chunks.
- Retrieve the top-k most similar chunks, applying metadata filters (user permissions, region, date).
- Rerank (advanced RAG) — reorder candidates with a more precise model and keep the best few.
- Augment — build the prompt: instructions, numbered sources, question.
- Generate — the LLM writes the answer, citing sources.
- Post-process — validate citations, apply output guardrails, log the trace.
What the augmented prompt looks like#
SYSTEM:
Answer using only the sources below. Cite sources like [2].
If the sources do not answer the question, say you don't know.
<sources>
[1] (Travel Policy 2026, §4.2) Economy class is required for flights under 6 hours...
[2] (Travel Policy 2026, §4.3) Business class may be booked for flights over 6 hours
with director approval...
[3] (FAQ: Travel) Approval requests are submitted in the Expenses portal...
</sources>
USER:
Can I fly business class to Singapore?
Naive, advanced and modular RAG#
flowchart LR
N["Naive RAG<br/>chunk → embed → top-k → generate"] --> A["Advanced RAG<br/>+ query rewriting, hybrid search,<br/>reranking, better chunking,<br/>metadata filters"]
A --> M["Modular / agentic RAG<br/>routing across sources, iterative retrieval,<br/>self-checking, tools, GraphRAG"]
| Naive RAG | Advanced RAG | Modular / agentic RAG | |
|---|---|---|---|
| Retrieval | Single vector search | Hybrid + rerank + filters | Multiple sources, chosen dynamically |
| Query handling | As typed | Rewritten, expanded | Decomposed into sub-questions, iterative |
| Good for | Prototypes | Most production assistants | Complex research, multi-hop questions |
| Cost / latency | Lowest | Moderate | Highest |
Details: advanced retrieval, GraphRAG, agentic RAG.
Where RAG fails#
flowchart LR
A["Missing content<br/>answer not in corpus"] --> B["Bad parsing<br/>tables garbled, headers lost"]
B --> C["Bad chunking<br/>answer split across chunks"]
C --> D["Missed retrieval<br/>right chunk not in top-k"]
D --> E["Lost in context<br/>right chunk present but ignored"]
E --> F["Unfaithful answer<br/>model adds facts not in sources"]
F --> G["Wrong format<br/>or missing citation"]
Each failure needs a different fix, which is why you evaluate retrieval and generation separately.
| Symptom | Likely cause | Fix |
|---|---|---|
| “I don’t know” but the answer exists | Retrieval miss | Hybrid search, better chunking, query rewriting, more candidates + reranking |
| Wrong answer citing the right document | Ambiguous or conflicting chunks; poor prompt | Rerank, add metadata (dates, versions), instruct to prefer latest |
| Answer mixes products or regions | No metadata filtering | Filter by product/region; ask clarifying question |
| Confident answer with no support | Unfaithful generation | Stricter prompt, faithfulness check, lower temperature |
| User sees content they should not | Missing access control | Filter by ACL at retrieval time — never rely on the prompt |
Security: permissions in RAG#
The retrieval step must only return chunks the current user is allowed to see. Store ACL metadata (groups, roles, tenant) on every chunk at ingestion, and filter in the vector query. Never retrieve everything and ask the LLM to “only use what the user may see”.
Common mistakes#
Review questions#
What is RAG and why use it? Retrieval-augmented generation: retrieve relevant passages from your own data and include them in the prompt so the LLM answers from them. It gives the model private and current knowledge, enables citations and per-user access control, and reduces hallucinations — without retraining.
Walk me through a RAG pipeline. Offline: load documents, parse, chunk, enrich with metadata and ACLs, embed and index in a vector store (often with a keyword index). Online: rewrite the query if needed, embed it, retrieve top-k with filters, rerank, build a prompt with numbered sources, generate with citations, validate and log.
Why must the query and the documents use the same embedding model? Each embedding model defines its own vector space; vectors from different models are not comparable. Changing the embedding model requires re-embedding the whole corpus.
How do you enforce document permissions in RAG? Capture ACLs at ingestion as chunk metadata and filter on the user’s identity in the retrieval query, so unauthorised chunks never reach the prompt.
Your RAG system gives wrong answers. How do you debug it? Check retrieval first: was the right chunk retrieved, and at what rank? If not, fix parsing, chunking, hybrid search, query rewriting or reranking. If yes, check generation: faithfulness, prompt instructions, conflicting sources, context order. Use separate retrieval and generation metrics.
Summary#
- RAG = retrieve relevant passages from your data, then generate an answer grounded in them.
- Two pipelines: offline ingestion (load, parse, chunk, enrich, embed, index) and online query (rewrite, retrieve, rerank, augment, generate).
- Most failures happen before the LLM: parsing, chunking and retrieval.
- Enforce permissions at retrieval; handle updates and deletes; evaluate both halves.
References#
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, 2020.
- Gao et al., Retrieval-Augmented Generation for Large Language Models: A Survey, 2023.
- Barnett et al., Seven Failure Points When Engineering a Retrieval Augmented Generation System, 2024.