RAG basics: the retrieve-then-generate pipeline, step by step, and when it beats fine-tuning
Retrieval-augmented generation lets a language model answer from your documents instead of its memory. This guide walks the pipeline stage by stage with runnable code, worked token costs and a clear rule for when RAG beats fine-tuning.
- Reading time
- 15 min
- Sections
- 7
- Code examples
- 2
- Tables
- 3
- Sources
- 8
- Published
- 24 Nov 2026
- What changed
- Sentence Transformers 6.3.0 reaches PyPI
- Why it matters
- For most teams the first RAG system should be boring.
- What to do
- Write 50 test questions first
A language model knows what was in its training data and nothing else. Ask it about your refund policy, last week's incident report or a contract signed yesterday, and it will either refuse or, worse, guess. Retrieval-augmented generation (RAG) fixes this with a simple idea: before the model answers, search your own documents for the passages that matter and paste them into the prompt. The model then writes its answer from that evidence.
The idea is old by AI standards. Lewis and colleagues named it in a 2020 paper, and it is now the default way to connect a model to private or fast-changing knowledge. What has changed is the tooling around it. The libraries that do the parsing, embedding and searching ship new versions every few weeks, and several did so this month. This article uses those releases as the starting point and then teaches the whole pipeline from first principles, with code you can run on a laptop and numbers you can check.
Think of RAG as an open-book exam. Fine-tuning is studying harder before the exam; RAG is bringing the right pages into the room. Most of the engineering is about finding the right pages fast.
What happened
Sentence Transformers 6.3.0 reaches PyPI (11 November 2026)
The Sentence Transformers library, which many RAG stacks use to compute embeddings, published version 6.3.0 on PyPI on 11 November 2026. It follows 6.0.0 on 18 August 2026. The project README now describes four model families under one package: dense Sentence Transformer models, Cross-Encoder rerankers, Sparse Encoder models such as SPLADE, and Multi-Vector Encoder models for ColBERT-style late interaction. The package summary on PyPI reads "Embeddings, Retrieval, and Reranking". For a RAG builder this means the retrieval and reranking stages of the pipeline below can come from one dependency.
LlamaIndex raises Python floors across integrations (13 November 2026)
The LlamaIndex changelog entry dated 13 November 2026 relocks the lock files of all its integration packages for security fixes and marks a breaking change that raises the required Python version across integrations. LlamaIndex core moved to 0.14.26 the same day on PyPI. If you pin an older Python in production, check the integration packages before you upgrade.
Docling 2.152.0 improves PDF ingestion (23 November 2026)
Docling, the open-source document converter started by IBM Research Zurich, released v2.152.0 on 23 November 2026. The changelog lists cancelling queued PDF parsing when conversions stop, reading heading keyword markers in other languages, and native MLX support for the Nemotron 3.5 Parse vision-language parser. Parsing is the first stage of every RAG pipeline, and heading detection matters because headings become the boundaries and metadata of chunks.
The pipeline, stage by stage
A RAG system has two halves. The offline half prepares your documents once (and again when they change). The online half runs for every question. The table lists each stage, its job and the failure it causes when it goes wrong.
| Stage | When it runs | Job | Typical failure |
|---|---|---|---|
| Parse | Offline | Turn PDFs, HTML and Office files into clean text with structure | Tables flattened, headers and footers mixed into text |
| Chunk | Offline | Split text into passages of a few hundred tokens | Answer split across two chunks |
| Embed and index | Offline | Turn chunks into vectors or term statistics and store them | Wrong embedding model for the language or domain |
| Retrieve | Online | Find the top k chunks for the question | The right chunk is not in the top k |
| Assemble prompt | Online | Put instructions, chunks and question together | Too much noise, no citation rule |
| Generate | Online | The model writes the answer from the context | Model ignores context or invents details |
Parse. Raw files are messy. A PDF is a set of positioned characters, not paragraphs. A parser such as Docling or PyMuPDF rebuilds reading order, headings and tables. Keep the structure: the heading above a paragraph is often the best context for it.
Chunk. Models and search indexes work best on passages, not whole documents. A common starting point is 300 to 800 tokens per chunk with some overlap. The site's chunking strategies simulation shows how chunk size changes what a search can find.
Embed and index. Each chunk becomes something searchable. For keyword search that is a table of term counts used by BM25. For semantic search it is a dense vector from an embedding model. Storage is easy to estimate: one million chunks with 768-dimension float32 vectors take 1,000,000 × 768 × 4 bytes, which is about 3.07 GB before any index overhead.
Retrieve. At question time the system scores every chunk (or an approximate subset) against the question and keeps the top k, often 3 to 10.
Assemble the prompt. The prompt has three parts: rules ("answer only from the sources, cite them"), the retrieved passages with identifiers, and the question.
Generate. The model reads the prompt and writes the answer. Good prompts tell it what to do when the sources do not contain the answer.
A runnable minimal pipeline
The smallest useful RAG system needs no GPU and no vector database. The code below uses the rank_bm25 package for keyword retrieval and prints the prompt you would send to any chat model. Install it with pip install rank_bm25 and run it.
from rank_bm25 import BM25Okapi
docs = [
"Refunds are issued within 14 days of receiving the returned item.",
"Standard shipping takes 3 to 5 working days inside the EU.",
"Gift cards cannot be refunded or exchanged for cash.",
"Returns are free for orders above 50 euros; otherwise a 4.95 euro fee applies.",
"Our support line is open Monday to Friday, 9:00 to 17:00 CET.",
]
tok = lambda s: s.lower().replace(";", " ").replace(".", " ").replace(",", " ").split()
bm25 = BM25Okapi([tok(d) for d in docs])
def retrieve(query, k=2):
scores = bm25.get_scores(tok(query))
ranked = sorted(range(len(docs)), key=lambda i: -scores[i])[:k]
return [(i, round(float(scores[i]), 3)) for i in ranked]
def build_prompt(query, hits):
context = "\n".join(f"[{i}] {docs[i]}" for i, _ in hits)
return ("Answer only from the sources. Cite them as [n]. "
"If the sources do not contain the answer, say so.\n\n"
f"Sources:\n{context}\n\nQuestion: {query}\nAnswer:")
q = "Is there a fee for returns?"
hits = retrieve(q)
print(hits)
print(build_prompt(q, hits))
Running it prints [(3, 2.238), (4, 1.082)]. Chunk 3, the returns-fee sentence, wins clearly. The second hit is chunk 4, the support-hours sentence, which matched only because both contain the word "is". That small accident teaches two lessons. First, keyword search matches words, not meaning, so common words create noise; real systems remove stopwords or use a tokenizer with better weighting. Second, k is a trade-off: the second chunk adds nothing here, but on another question it might hold half the answer.
To turn this into a full RAG system you send the printed prompt to a model. Any chat API works. The only rule that matters is that the model sees the sources and the instruction to cite them. You can watch this exact loop, with each stage highlighted, in the naive RAG simulation.
The arithmetic of a RAG answer
Two numbers decide whether a RAG system is good and affordable: how often retrieval finds the right passage, and how many tokens each answer costs.
Quality is a product, not a sum. If the retriever puts a correct passage in the top five for 80 percent of questions (recall@5 = 0.80), and the model answers correctly 90 percent of the time when it has the right passage, then end-to-end accuracy is at most about 0.80 × 0.90 = 0.72. A better model cannot recover a passage the retriever never found. This is why most RAG work goes into retrieval, and why you should measure the two stages separately.
Cost per answer is mostly input tokens. Take a typical prompt: five chunks of 400 tokens (2,000 tokens), 150 tokens of instructions and a 30-token question, so 2,180 input tokens, plus 200 output tokens. At an example price of 3 dollars per million input tokens and 15 dollars per million output tokens:
- input: 2,180 × 3 / 1,000,000 = 0.00654 dollars
- output: 200 × 15 / 1,000,000 = 0.00300 dollars
- total: about 0.0095 dollars per answer, or about 954 dollars for 100,000 answers
Halving k to 2 or 3 chunks cuts input cost by close to half, but may lower recall. Prompt caching helps when the instructions are long and repeated; the retrieved chunks change per question, so they rarely cache. The site's article on prefix caching and context prices explains how cached input is billed.
Latency adds up stage by stage. A dense query embedding takes a few milliseconds on a GPU, an approximate vector search a few more, and a reranker tens of milliseconds. Generation dominates: hundreds of milliseconds to seconds depending on output length. Retrieval is rarely the slow part unless you add many sequential steps.
RAG versus fine-tuning, and where basic RAG breaks
When RAG beats fine-tuning
Fine-tuning changes the model's weights by training on your data. RAG leaves the weights alone and changes the input. They solve different problems, and the confusion between them is the most common design mistake in this area.
Ovadia and colleagues compared the two for knowledge injection in "Fine-Tuning or Retrieval?" (arXiv 2312.05934). They found that RAG consistently outperformed unsupervised fine-tuning, both for knowledge the models had seen before and for entirely new knowledge, and that models struggled to learn new facts through unsupervised fine-tuning. The practical reading is simple: if the goal is "know these facts", retrieve them.
| Need | Better choice | Why |
|---|---|---|
| Answer from documents that change weekly | RAG | Re-index in minutes; no retraining |
| Cite the source of every claim | RAG | Each answer can point to a chunk |
| Respect per-user access rights | RAG | Filter what is retrieved per user |
| Adopt a fixed output format or tone | Fine-tuning | Behaviour, not facts |
| Learn a narrow skill (a domain-specific extraction schema) | Fine-tuning | Skills live in weights |
| Very short latency budget, tiny model | Fine-tuning, maybe both | No retrieval round trip |
| Small, stable corpus that fits in context | Neither: long context | Put it all in the prompt and cache it |
The two combine well. A common pattern is to fine-tune a small model to follow the RAG prompt format (cite, refuse when unsupported) and keep the facts in the index. For the wider range of methods that adapt weights, see the site's fine-tuning overview.
There is also a third option that has grown with context windows: put the whole corpus in the prompt. For a few hundred pages that are reused across many questions, long context with caching can be simpler than a retrieval stack. Beyond that size, cost per question and the model's attention over very long inputs favour retrieval.
Where basic RAG breaks and what fixes it
The minimal pipeline fails in predictable ways. Each failure has a known fix, and each fix is its own topic on this site.
| Symptom | Likely cause | Standard fix |
|---|---|---|
| Exact codes, names or IDs not found | Dense embeddings blur rare tokens | Hybrid search: BM25 plus dense |
| Right document, wrong passage in top k | Coarse first-stage ranking | Cross-encoder reranking |
| Vague or multi-part questions miss | Query wording differs from documents | Query rewriting, multi-query, HyDE |
| "Summarise themes across all reports" fails | Answer is spread across many chunks | GraphRAG community summaries |
| Answer invents details | Model ignores or overreaches context | Faithfulness checks, citation rules |
| Old answers after a policy update | Stale index | Incremental re-indexing with timestamps |
The RAG types simulation puts these variants side by side, and the site's longer survey of RAG types from naive to GraphRAG explains each in turn.
Continue learning
How this article connects
6 pages link to or from it. Drag to turn, click a dot to open it.
What it means in practice
For most teams the first RAG system should be boring. Parse well, chunk at a few hundred tokens, retrieve with a hybrid of keyword and dense search, and assemble a prompt that demands citations. The library releases this month do not change that recipe; they make each stage easier to run from a single dependency and easier to keep secure.
The biggest practical shift is in measurement. Because end-to-end quality is the product of retrieval quality and generation quality, you need a small labelled set of questions with known source passages before you tune anything. With 50 to 100 such questions you can compute recall@k for retrieval and faithfulness for generation, and you will know which half to fix. Tools such as Ragas automate the generation-side metrics.
Cost is predictable. The worked example above shows that input tokens dominate, so k and chunk size are your main cost levers, and they are also quality levers. Change them together and measure.
What to do now
- Write 50 test questions first. For each one, record the document and passage that contains the answer. Without this set every later change is a guess.
- Keep document structure when you parse. Store the heading path and page number with every chunk; they help retrieval and make citations useful.
- Start with 300 to 800 token chunks and 10 to 20 percent overlap. Tune only after you can measure recall@k.
- Use hybrid retrieval from day one. BM25 catches exact terms and identifiers; dense embeddings catch paraphrases. Fuse the two lists.
- Retrieve more, then rerank to fewer. Pull 20 to 50 candidates cheaply and let a cross-encoder choose the best 3 to 5 for the prompt.
- Demand citations and allow refusal. The prompt should say "answer only from the sources, cite them, say so if the answer is missing".
- Log every retrieval. Store the question, the chunk IDs returned and their scores, so you can debug wrong answers later.
- Budget cost per answer. Multiply your input and output tokens by your model's prices, as in the worked example, before launch.
- Pin and review library upgrades. This month's LlamaIndex release raised Python floors across integrations; upgrade in a branch and rerun your test questions.
Risks and open questions
Retrieval is a ceiling. No model can answer from a passage it never saw. Teams that judge RAG only by final answers often waste weeks swapping models when the fault is in recall.
Context can be wrong or hostile. Retrieved text is untrusted input. A document that says "ignore previous instructions" is a prompt injection, and RAG puts it straight into the prompt. Treat retrieved text as data, and test with adversarial documents.
Citations can be decorative. A model can cite chunk [3] and still state something chunk [3] does not say. Faithfulness has to be checked, not assumed.
Fine-tuning versus RAG results depend on the setup. The Ovadia study tested unsupervised fine-tuning on specific knowledge tasks. Supervised fine-tuning on question-answer pairs, or newer continual-training methods, may narrow the gap for some domains.
Long context keeps moving the boundary. As context windows and caching discounts grow, the corpus size where retrieval pays off rises. The right answer for a 200-page handbook may differ next year.
Watch next: how far one-package retrieval stacks (dense, sparse, multi-vector and reranking in one library) simplify production systems, and whether parsers with vision-language models close the gap on complex PDFs and tables.
Frequently asked questions
What is the difference between RAG and a search engine?
A search engine returns a ranked list of documents for a person to read. RAG uses the same kind of search, then passes the top passages to a language model that writes a direct answer with citations. The search part is the same technology; the generation step is what RAG adds.
Do I need a vector database to build RAG?
No. A small corpus can be searched with BM25 in memory, as the example shows, or with exact vector search in NumPy. A vector database becomes useful when you have millions of chunks, need filtering and updates, or need low latency at scale.
How many chunks should I retrieve?
Start by retrieving 20 to 50 candidates and passing 3 to 5 to the model after reranking. More chunks raise recall but also cost and noise. Measure recall@k on your test questions to find the point where adding chunks stops helping.
Is RAG better than fine-tuning?
For adding facts, especially facts that change, research such as Ovadia et al. found RAG consistently better than unsupervised fine-tuning. For changing behaviour, format or a narrow skill, fine-tuning is the better tool. Many production systems use both.
Why does my RAG system still hallucinate?
Usually because retrieval missed the right passage, so the model filled the gap, or because the prompt does not allow it to say "not found". Check recall first, then add a refusal rule and a faithfulness check on the output.
Summary
Retrieval-augmented generation answers questions from your documents by searching them first and giving the best passages to a language model. The pipeline has six stages: parse, chunk, embed and index offline, then retrieve, assemble the prompt and generate online. End-to-end quality is roughly retrieval recall times generation accuracy, so retrieval sets the ceiling, and cost is dominated by the input tokens you choose to retrieve. RAG beats fine-tuning for adding and updating facts, while fine-tuning remains the better tool for behaviour and format. This month's releases of Sentence Transformers, LlamaIndex and Docling change the tools, not the recipe: parse with structure, retrieve with a hybrid, rerank, cite, and measure each stage on your own questions.
Sources
- Paper arXiv: Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (Lewis et al.)
- Paper arXiv: Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs (Ovadia et al.)
- Code PyPI: sentence-transformers release history
- Code GitHub: Sentence Transformers README
- Code GitHub: LlamaIndex changelog
- Code PyPI: llama-index-core release history
- Code GitHub: Docling changelog
- Code PyPI: rank-bm25
Cite this article
Kelahmet, Ö. C. (2026, November 24). RAG basics: the retrieve-then-generate pipeline, step by step, and when it beats fine-tuning. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/rag-basics-retrieve-then-generate-pipeline
BibTeX
@online{kelahmet2026basics,
author = {Kelahmet, {\"O}zer Cem},
title = {{RAG basics: the retrieve-then-generate pipeline, step by step, and when it beats fine-tuning}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/rag-basics-retrieve-then-generate-pipeline}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.