Ask a large language model about your company's leave policy, last week's sales or a contract signed yesterday, and it will either refuse or, worse, invent a confident answer. The model only knows what was in its training data, and your private, changing information was never part of it.
There are three main ways to fix that: retrieval-augmented generation (RAG), fine-tuning and, increasingly, agentic RAG. They are often presented as rivals. In practice they solve different problems, and choosing the wrong one is one of the most expensive mistakes teams make with generative AI.
In this guide I explain what RAG is and how it works step by step, build a working RAG pipeline in Python, compare RAG with fine-tuning and agentic RAG side by side, and cover how to make RAG accurate, how to evaluate it and how to keep it secure. If you want the retrieval layer in depth, read How to Design Semantic Search Systems with Vectors alongside this.
What is RAG (retrieval-augmented generation)?
RAG is a technique that retrieves relevant information from your own documents or data at the moment a question is asked and gives it to a large language model, so the answer is grounded in that information instead of the model's memory.
The simplest analogy is an open-book exam. A model without RAG answers from memory and sometimes misremembers. A model with RAG gets to look up the right pages first and quote them.
The term comes from a 2020 research paper by Patrick Lewis and colleagues, Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, presented at NeurIPS 2020. It described models that combine two kinds of memory:
- Parametric memory: what the model learned during training, stored in its weights.
- Non-parametric memory: an external index of documents the model can search at answer time.
That split is still the clearest way to think about RAG. The model supplies language and reasoning; your documents supply the facts. You can update the documents every minute without retraining anything.
Why do large language models need RAG?
LLMs need RAG because they cannot see your private data, their knowledge stops at a training cut-off, and without sources they cannot show where an answer came from.
| Problem without RAG | What RAG adds |
|---|---|
| No access to private data: policies, contracts, tickets, product docs | Answers drawn from your own documents |
| Outdated knowledge after the training cut-off | Fresh information as soon as a document is indexed |
| Hallucination: fluent answers with invented facts | Answers constrained to retrieved evidence, with an "I don't know" path |
| No citations | Every claim can point to its source passage |
| No access control | Retrieval can respect who is allowed to see which documents |
RAG reduces hallucination but does not eliminate it. If retrieval returns the wrong passage, the model can still write a confident, wrong answer. That is why most of the work in a good RAG system goes into retrieval and evaluation, not the prompt.
How does RAG work, step by step?
RAG works in two phases: an indexing phase that prepares your documents ahead of time, and a query phase that retrieves the best passages for each question and passes them to the model with instructions to answer only from them.
Phase 1: indexing (done ahead of time)
- Load documents from their sources: PDFs, wikis, tickets, databases.
- Chunk them into passages of a few hundred words, keeping the source and section so you can cite them.
- Index each chunk, usually as a vector embedding for meaning-based search, a keyword index for exact terms, or both (hybrid search).
- Store chunks with metadata such as document, date and who may see it.
Phase 2: query (done for every question)
- Retrieve the top few chunks that best match the question, filtered by the user's permissions.
- Augment the prompt: put those chunks into it with clear instructions.
- Generate an answer that uses only the provided sources and cites them.
- Refuse when unsupported: if the sources do not contain the answer, say so instead of guessing.
How do you build a simple RAG pipeline in Python?
A minimal RAG pipeline needs four pieces: a chunker, a retriever, a prompt that forces grounded and cited answers, and a call to the model. The version below uses a small BM25 keyword retriever written in plain Python, so you can run it with no database or API keys for the retrieval part.
import math, re
from collections import Counter
def chunk(doc_id, text, size=80, overlap=20):
"""Split a document into overlapping word windows, keeping the source for citations."""
words = text.split()
step = size - overlap
return [{"id": f"{doc_id}#{i // step + 1}", "text": " ".join(words[i:i + size])}
for i in range(0, max(len(words) - overlap, 1), step)]
def tokens(text):
return re.findall(r"[a-z0-9]+", text.lower())
class BM25:
"""Keyword retriever. Swap in vector or hybrid search later; the RAG flow stays the same."""
def __init__(self, chunks, k1=1.5, b=0.75):
self.chunks, self.k1, self.b = chunks, k1, b
self.docs = [Counter(tokens(c["text"])) for c in chunks]
self.avg = sum(sum(d.values()) for d in self.docs) / len(self.docs)
df = Counter(t for d in self.docs for t in d)
n = len(self.docs)
self.idf = {t: math.log(1 + (n - f + 0.5) / (f + 0.5)) for t, f in df.items()}
def search(self, query, k=3):
scores = []
for c, d in zip(self.chunks, self.docs):
length = sum(d.values())
s = sum(self.idf.get(t, 0) * d[t] * (self.k1 + 1) /
(d[t] + self.k1 * (1 - self.b + self.b * length / self.avg))
for t in tokens(query) if t in d)
scores.append((s, c))
return [c for s, c in sorted(scores, key=lambda x: -x[0])[:k] if s > 0]
PROMPT = """Answer the question using ONLY the sources below.
Cite the source id in square brackets after each fact, like [leave-policy#2].
If the sources do not contain the answer, say "I don't know based on the documents."
Sources:
{sources}
Question: {question}"""
def build_prompt(question, hits):
sources = "\n\n".join(f"[{h['id']}] {h['text']}" for h in hits)
return PROMPT.format(sources=sources, question=question)
def answer(question, index, k=3):
hits = index.search(question, k)
if not hits: # nothing relevant: do not let the model guess
return "I don't know based on the documents.", []
reply = call_model([{"role": "user", "content": build_prompt(question, hits)}])
return reply["content"], [h["id"] for h in hits]
Using it takes three lines:
chunks = [c for doc_id, text in documents.items() for c in chunk(doc_id, text)]
index = BM25(chunks)
reply, sources = answer("How many days of annual leave do I get?", index)
As in my other guides, call_model is your thin wrapper around any LLM provider's chat API. Three design choices do most of the work:
- Source ids on every chunk, so the model can cite
[leave-policy#1]and a person can check it. - "Only use the sources" plus an explicit "I don't know" line, which gives the model a safe way out instead of inventing.
- No model call when nothing relevant is found. If retrieval returns nothing, the code answers "I don't know" itself.
I tested this code on three sample HR, expense and IT policy documents: questions about annual leave and meal allowances retrieved the right policy first, an unrelated question retrieved nothing and never reached the model, and the prompt carried the source ids and the refusal instruction. For real workloads, replace BM25 with hybrid vector and keyword search; the rest of the flow stays the same. My semantic search guide shows that step with pgvector.
What is fine-tuning?
Fine-tuning means continuing to train a pre-trained model on your own examples so that it changes its behaviour: its style, its output format, or how well it performs a specific task. The changes are stored in the model's weights, not in an external index.
There are two broad approaches:
- Full fine-tuning updates all of the model's weights. It is powerful but expensive and needs serious hardware.
- Parameter-efficient fine-tuning (PEFT) trains a small set of extra weights instead. The best-known method, LoRA (Low-Rank Adaptation, 2021), reported that compared with fully fine-tuning GPT-3 175B, it cut trainable parameters by 10,000 times and GPU memory needs by 3 times.
Most model providers now offer fine-tuning through an API, so you supply examples (usually hundreds to thousands of input and ideal-output pairs) rather than running training yourself.
Fine-tuning is good at teaching a model how to respond: always answering in your JSON schema, matching your brand voice, classifying tickets into your categories, or letting a smaller, cheaper model do a narrow task as well as a larger one.
RAG vs fine-tuning: what is the difference?
RAG gives a model knowledge at question time from documents you control; fine-tuning changes the model's behaviour by training it on examples. A useful rule: RAG for knowledge, fine-tuning for behaviour.
| RAG | Fine-tuning | |
|---|---|---|
| What it changes | What the model can see for this question | How the model behaves on every question |
| Where knowledge lives | In an external index you can edit | In the model's weights |
| Keeping facts current | Re-index a document, live in minutes | Retrain on new data |
| Citations | Natural: answers point to source passages | Not possible: the model cannot say which example taught it |
| Access control | Filter retrieval per user | Anything trained in is available to every user |
| Upfront effort | Build ingestion, chunking and search | Collect and clean training examples, run and evaluate training |
| Running cost | Longer prompts (retrieved text) on every call | Shorter prompts; can let a smaller model do the job |
| Best for | Policies, product docs, support answers, research over documents | Format, tone, classification, domain-specific style, cost reduction |
Research backs up the knowledge rule. A 2023 study comparing the two for adding knowledge to LLMs, Fine-Tuning or Retrieval?, found that while unsupervised fine-tuning offered some improvement, RAG consistently outperformed it, for both existing and entirely new knowledge, and that models struggle to learn new facts through that kind of fine-tuning.
The two also combine well. A common production setup fine-tunes a model to follow your answer format and citation style, then uses RAG to supply the facts.
When should you use RAG, fine-tuning or both?
Start with prompting, add RAG when the model needs facts it does not have, and add fine-tuning only when prompting and RAG cannot get the behaviour or cost you need.
| Your situation | Best choice |
|---|---|
| Answer questions over policies, manuals or knowledge bases that change | RAG |
| Different users may see different documents | RAG with permission filters |
| Answers must cite sources for audit or trust | RAG |
| Output must always follow a strict format or house style | Fine-tuning (try structured outputs and examples in the prompt first) |
| A high-volume narrow task, such as ticket classification, is too slow or costly on a large model | Fine-tuning a smaller model |
| Facts from documents and a specialised output style | Both |
| A small, stable set of documents | Long context: put it all in the prompt |
| Questions that need several searches, sources or steps | Agentic RAG |
Do you even need RAG? The long-context option
Modern models accept very long prompts. Anthropic's guidance is that if your knowledge base is smaller than about 200,000 tokens (roughly 500 pages), you can simply include all of it in the prompt, and prompt caching makes that faster and cheaper. Researchers call a version of this cache-augmented generation (CAG): preload a limited, manageable set of documents into the model's context and skip retrieval entirely, which removes retrieval latency and retrieval errors.
Long context does not replace RAG for large or fast-changing collections, per-user permissions or citations at scale. But for a 50-page handbook, it is often the simplest correct answer.
What is agentic RAG?
Agentic RAG puts an AI agent in charge of retrieval: instead of one fixed search before answering, the agent decides what to search for, checks whether the results are good enough, searches again or uses other tools, and only then answers.
A 2025 survey of the field describes agentic RAG as embedding autonomous AI agents into the RAG pipeline, using four agentic design patterns: reflection, planning, tool use and multi-agent collaboration.
In practice, agentic RAG adds four abilities:
- Query planning: breaking "Compare our Q3 refund policy with what customers complained about" into separate searches.
- Self-checking: judging whether the retrieved passages actually answer the question.
- Query rewriting: trying different wording when the first search misses, such as "reimbursement approval" instead of "who signs off expenses".
- Tool choice: searching documents, running SQL on a database or querying an API, depending on the question.
Related research ideas include Self-RAG (2023), which trains a model to retrieve on demand and critique its own output with special reflection tokens, and corrective patterns that grade retrieved documents and retry when they are weak.
RAG vs agentic RAG: which should you use?
Use classic RAG for direct questions that one search can answer; use agentic RAG when questions need several searches, sources or steps, and the extra cost and latency are acceptable.
| Classic RAG | Agentic RAG | |
|---|---|---|
| Flow | Fixed: retrieve once, then answer | Dynamic: plan, retrieve, check, retry |
| Best for | "What is our leave policy?" | "Which policy changes explain the rise in Q3 complaints?" |
| Model calls per question | One | Several |
| Latency and cost | Low and predictable | Higher and variable |
| Handles a bad first search | No: a miss means a weak answer | Yes: it can notice and retry |
| Can use other tools | No | Yes: SQL, APIs, web search |
| Testing and debugging | Straightforward | Harder: needs traces of every step |
A sensible path is to build classic RAG first, measure where it fails, and add agentic steps only for those failure types. Many teams put a router in front: simple questions go to classic RAG, complex ones to the agent.
How do you build an agentic RAG loop in Python?
A minimal agentic RAG loop retrieves, asks the model to grade whether the evidence is enough, rewrites the query if it is not, and repeats up to a hard limit before answering. It reuses the retriever and prompt from the pipeline above.
import json
from rag import build_prompt
MAX_ROUNDS = 3 # hard cap on search-grade-rewrite cycles
GRADER = """You check whether the evidence is enough to answer the question.
Return JSON: {{"enough": true or false, "missing": "...", "next_query": "..."}}.
next_query must be a NEW search query aimed at what is missing.
Question: {question}
Evidence:
{evidence}"""
def agentic_answer(question, index, k=3):
query, evidence, trail = question, [], []
for _ in range(MAX_ROUNDS):
hits = index.search(query, k)
evidence += [h for h in hits if h not in evidence] # keep what earlier rounds found
trail.append(query)
if not evidence:
verdict = {"enough": False, "next_query": question}
else:
text = "\n".join(f"[{h['id']}] {h['text']}" for h in evidence)
verdict = json.loads(call_model([{"role": "user", "content":
GRADER.format(question=question, evidence=text)}])["content"])
if verdict["enough"]:
break
query = verdict["next_query"]
else:
if not evidence:
return "I don't know based on the documents.", [], trail
reply = call_model([{"role": "user", "content": build_prompt(question, evidence)}])
return reply["content"], [h["id"] for h in evidence], trail
What makes this safe to run:
- A hard cap of three search rounds, so a confused agent cannot loop forever or run up a bill.
- Evidence accumulates across rounds, so a good passage found early is not lost when the query changes.
- The grader asks for a specific missing piece and a new query aimed at it, rather than repeating the same search.
- An honest exit: if nothing relevant turns up in any round, it says it does not know.
I tested the loop with a stubbed model: for "Who signs off a big travel reimbursement?", the first search missed the approval rule, the grader asked for "claims approval director", the second round found the expense-policy passage and the loop stopped. A nonsense question ran all three rounds, found nothing and returned "I don't know". For more on loops, limits and tool design, see How to Build Your First AI Agent.
What other types of RAG should you know?
Beyond classic and agentic RAG, the variants worth knowing are hybrid RAG, contextual retrieval, GraphRAG, Self-RAG and cache-augmented generation.
| Variant | What it does | Use it when |
|---|---|---|
| Hybrid RAG | Combines vector (meaning) search with keyword search | Almost always: product codes, names and exact phrases need keywords |
| Contextual retrieval | Adds a short description of each chunk's context before indexing it | Chunks lose meaning on their own ("revenue grew 3%" — whose, when?) |
| GraphRAG | Builds a knowledge graph of entities and pre-summarises related groups | Broad questions about a whole collection, such as "What are the main themes?" |
| Self-RAG | A model trained to decide when to retrieve and to critique its own output | Research and specialised setups; the ideas inspire agentic checks |
| Cache-augmented generation (CAG) | Preloads a small knowledge base into the context and skips retrieval | Limited, stable document sets |
GraphRAG deserves a note: Microsoft's 2024 paper showed that plain RAG fails on "global" questions directed at an entire corpus, because no single passage contains the answer. If your users ask for themes, trends or summaries across thousands of documents, classic RAG is the wrong tool.
How do you make RAG more accurate?
Most RAG accuracy problems are retrieval problems, so improve retrieval first: better chunking, hybrid search, contextual retrieval and reranking, then tighten the prompt. Work through these in order of value for effort:
- Clean and chunk well. Split on headings and sections, not arbitrary character counts. Keep tables intact. Attach titles and dates.
- Use hybrid search. Meaning-based search misses exact terms; keyword search misses paraphrases. Together they cover both.
- Add contextual retrieval. Anthropic reported that adding generated context to each chunk cut retrieval failures by 35% with contextual embeddings, by 49% when combined with contextual BM25, and by 67% with reranking added.
- Rerank. Retrieve 20 to 50 candidates, then use a reranking model to keep the best 3 to 5.
- Filter with metadata. Restrict by department, product, date or permission before ranking.
- Tighten the prompt. Require citations, allow "I don't know", and tell the model what to do with conflicting sources.
- Close the loop with evaluation, below, so you know each change helped.
The details of embeddings, hybrid search and reranking are in How to Design Semantic Search Systems with Vectors.
How do you evaluate a RAG system?
Evaluate retrieval and generation separately: check that the right passages were retrieved, then check that the answer is faithful to them and actually answers the question. A single "looks good" score hides which half is broken.
| Metric | What it measures | Tells you to fix |
|---|---|---|
| Context recall | Whether the retrieved passages contain the information needed for the reference answer | Retrieval coverage: chunking, search, filters |
| Context precision | Whether relevant passages are ranked above irrelevant ones | Ranking: reranking, hybrid weights |
| Faithfulness | The share of claims in the answer supported by the retrieved passages | Generation: prompt, model, citation rules |
| Response relevancy | Whether the answer addresses the question asked | Prompt and question understanding |
These four come from RAGAS, a widely used open-source RAG evaluation library. Whatever tool you use, the habits matter more:
- Build a test set of 30 to 100 real questions with reference answers and the source passage each should come from.
- Include unanswerable questions and check the system says "I don't know".
- Include questions with exact terms, such as product codes and policy numbers.
- Rerun the whole set after every change to chunking, search, prompt or model.
- Review a sample of answers by hand each week. Automated judges are useful but not infallible.
For agentic RAG, also track rounds per question and cost per answer. Repeated-run testing is covered in AI Agents That Work.
What are the security and privacy risks of RAG?
The main RAG risks are leaking documents to people who should not see them, prompt injection hidden inside retrieved documents, and answers built on stale or wrong sources.
- Enforce permissions at retrieval time. Filter results by the user's access rights before anything reaches the model. Never rely on the prompt to hide confidential text.
- Treat retrieved text as untrusted data. A document or web page can contain instructions such as "ignore previous instructions". In agentic RAG, where retrieval can trigger tools, this matters even more. See Prompt Injection and AI Agent Security.
- Keep the index fresh. Remove superseded documents and show the date of each source in the answer.
- Mind what you send to the model provider, and follow your organisation's data policies for sensitive content.
- Log questions, retrieved sources and answers so you can audit any response.
What are the most common RAG mistakes?
- Using fine-tuning to teach facts. It is slower, harder to update, cannot cite and leaks across users. Use RAG for knowledge.
- Blaming the model for retrieval failures. Check context recall before changing models or prompts.
- Vector search only. Exact names, codes and numbers need keyword search too.
- Chunks without context. A passage that says "the limit is 50,000" without saying what limit is useless on its own.
- No "I don't know" path. Without one, the model fills gaps with plausible fiction.
- Going agentic too early. Agents add cost and complexity; prove classic RAG falls short first.
- Building RAG for a 50-page handbook. If it fits in the context window, try long context first.
- No evaluation set. Without one, every change is a guess.
Checklist: is your RAG system ready for real users?
- You confirmed the knowledge base is too large or changes too often for long context alone
- Documents are chunked by structure, with source, title, date and permissions attached
- Retrieval uses hybrid search, with reranking where accuracy matters
- Permission filters are applied at retrieval, before the model sees anything
- The prompt requires citations and allows "I don't know"
- No model call is made when nothing relevant is retrieved
- Retrieved text is treated as data, never as instructions
- An evaluation set measures context recall, context precision, faithfulness and relevancy
- Unanswerable and exact-term questions are part of the test set
- Agentic steps, if any, have round, step and cost limits
- Questions, sources and answers are logged for audit
- Stale documents are removed and source dates are shown to users
Sources and further reading
- Lewis et al.: Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (NeurIPS 2020)
- Ovadia et al.: Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs
- Hu et al.: LoRA: Low-Rank Adaptation of Large Language Models
- Singh et al.: Agentic Retrieval-Augmented Generation: A Survey on Agentic RAG
- Anthropic: Introducing Contextual Retrieval
- Edge et al.: From Local to Global: A Graph RAG Approach (Microsoft)
- Asai et al.: Self-RAG
- Chan et al.: Don't Do RAG: When Cache-Augmented Generation is All You Need
- RAGAS: available metrics
Key takeaways
- RAG retrieves relevant passages from your documents at question time and makes the model answer from them, with citations.
- RAG for knowledge, fine-tuning for behaviour; combine them when you need both.
- If your documents fit in about 200,000 tokens, try long context before building RAG.
- Agentic RAG adds planning, self-checking, query rewriting and tool use, at higher cost and latency.
- Most accuracy gains come from retrieval: hybrid search, contextual retrieval and reranking.
- Evaluate retrieval and generation separately, and enforce permissions before the model sees anything.
Frequently asked questions
What is RAG in AI?
RAG (retrieval-augmented generation) is a technique that searches your own documents or data when a question is asked and gives the most relevant passages to a large language model, so it answers from that evidence with citations instead of relying only on what it learned in training.
What is the difference between RAG and fine-tuning?
RAG gives a model knowledge at question time from documents you can update, filter by user and cite. Fine-tuning trains the model on examples to change its behaviour, such as format, tone or performance on a narrow task. Use RAG for knowledge and fine-tuning for behaviour.
Is RAG better than fine-tuning?
For adding knowledge, usually yes. A 2023 study found RAG consistently outperformed unsupervised fine-tuning for both existing and new knowledge. Fine-tuning is better for teaching consistent formats, styles or narrow tasks, and the two are often combined.
What is agentic RAG?
Agentic RAG puts an AI agent in charge of retrieval. The agent plans searches, checks whether the results answer the question, rewrites the query or uses other tools such as SQL when they do not, and answers only when it has enough evidence, within set limits.
What is the difference between RAG and agentic RAG?
Classic RAG retrieves once and answers, which is fast, cheap and predictable. Agentic RAG can search several times, judge its own results and use other tools, which handles complex multi-step questions better but costs more, takes longer and is harder to test.
When should I not use RAG?
If your knowledge base is small and stable, roughly under 200,000 tokens or about 500 pages, putting it all in the prompt is often simpler. RAG is also the wrong tool for teaching a model a style or format, and plain RAG struggles with broad questions about themes across an entire collection.
Does RAG stop hallucinations?
It reduces them but does not eliminate them. If retrieval returns the wrong passages, the model can still give a confident wrong answer. Require citations, allow the model to say it does not know, and measure faithfulness on a test set.
What do I need to build a RAG system?
Documents, a way to split them into chunks, a search index (vector, keyword or hybrid), a prompt that tells the model to answer only from the retrieved sources and cite them, and an LLM. For production, add permission filters, reranking, logging and an evaluation set.
How do you evaluate a RAG system?
Measure retrieval and generation separately. Context recall and context precision show whether the right passages were found and ranked well; faithfulness and response relevancy show whether the answer sticks to those passages and addresses the question. Include unanswerable questions in the test set.
What is GraphRAG?
GraphRAG, from Microsoft research, builds a knowledge graph of entities from your documents and pre-summarises groups of related entities. It is designed for broad questions about a whole collection, such as the main themes, which plain RAG handles poorly.
Build RAG your team can trust
A RAG demo takes an afternoon. A RAG system that gives correct, cited, permission-aware answers takes careful retrieval design and honest evaluation. If you want help choosing between RAG, fine-tuning and agentic RAG, reviewing your pipeline, or training your team to build it, let's talk.
Next read: How to Design Semantic Search Systems with Vectors