Written by the AgileFever editorial team. Facts checked on December 1, 2026 against the official pages of the organizations named in this post. AgileFever sells training for some of the topics covered here, and we say so wherever it applies. The code sample was run on this date with Python’s standard library.
A RAG pipeline lets a language model answer from your own documents instead of only from its training data. RAG stands for retrieval-augmented generation. The method comes from a 2020 paper by Patrick Lewis and 11 co-authors, titled Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. This tutorial is for engineers who have called an LLM API and want to see every stage in code before choosing a framework. The code uses only the Python standard library, so it runs with no API key. You will build the index, the retriever and the prompt, then read what a basic setup gets wrong.
The five stages of a RAG pipeline
Each stage has one job. Errors in an early stage show up as wrong answers in the last one, which is why the stages are worth learning separately.
Split each document into pieces small enough to fit a prompt and specific enough to answer one question.
Turn each chunk, and each incoming question, into a vector that represents its meaning.
Save each vector with its original text and source name. For a small set, keeping them in memory is enough.
Compare the question vector with every stored vector and keep the top k matches.
Put the retrieved text into the prompt, ask the model to answer from it, and return the answer with its source.
The sample in this post replaces the embedding model with word counts, so it is a toy version. The five stages are the same.
Chunking and embedding set the ceiling
Chunking decides what the retriever can ever find. A chunk that is too large mixes several topics, so its vector matches none of them well. A chunk that is too small splits an answer across pieces, so no single piece holds the full fact. A preview chapter of a RAG guide lists several methods. The table summarizes them, with the risk each one carries.
| Method | How it splits | Strength | Risk |
|---|---|---|---|
| Fixed size with overlap | By characters or tokens, with some text repeated between neighbours | Simple and predictable size | Cuts sentences, lists and tables in half |
| Paragraph | At blank lines | Keeps each thought together | Long paragraphs give large chunks. a vendor tutorial dated July 29, 2026 uses this method and calls it simple, not production ready |
| Structure-aware | At HTML or Markdown headers, JSON keys or code blocks | Each chunk keeps its section title | Needs a parser for each format |
| Semantic (experimental) | Where neighbouring sentences drift in meaning, using embeddings | Groups sentences by topic | Uses embeddings at index time and is less proven than the others |
Method list: a preview chapter of a RAG guide. Paragraph chunking and its limits: a vendor tutorial, published July 29, 2026.
Use the same embedding model for chunks and for questions. Vectors from two different models sit in different spaces, so their scores mean nothing. the vendor tutorial embeds with text-embedding-3-small and stores 162 chunks in ChromaDB. Its FAQ entries are not split, so each FAQ is one chunk.
Retrieval: how top k adds noise
The simplest retriever scores every stored chunk by cosine similarity to the question and returns the top k. A course on a naive RAG pipeline uses this flat cosine search as its baseline, and the vendor tutorial sets k to 5. A larger k raises the chance that the right chunk is present. It also adds more text that is off topic, and the model may use it. Chunk size and k interact, so change one at a time.
Anthropic’s post on contextual retrieval, dated September 19, 2024, measured how often the right chunk was missing from the top 20. It added context to each chunk before embedding, then combined embeddings with BM25 keyword search and a reranker. Anthropic says general RAG chunks are usually no more than a few hundred tokens. These are Anthropic’s results on its own test sets, so your numbers will differ.
Share of questions where the right chunk was missing from the top 20. Lower is better.
Source: Anthropic’s contextual retrieval post, September 19, 2024, read December 1, 2026. Figures are from Anthropic’s test sets, not from AgileFever data.
Build it: a runnable pipeline in about 50 lines
Save the code below as rag_pipeline.py and run it with python3 rag_pipeline.py. The corpus is three short policy notes, and chunks hold 12 words, so the output is easy to read. Real chunks are much larger. This is an illustrative example, and the output below is what this file printed on this date.
import math
import re
from collections import Counter
DOCS = {
"refund.txt": "Refunds are issued within 14 days of cancellation. Refunds go to the original payment method.",
"leave.txt": "Employees get 20 days of paid leave per year. Unused leave carries over up to 5 days.",
"wfh.txt": "Work from home needs manager approval. Remote staff must be online between 10 AM and 4 PM.",
}
def chunk(text, size=12):
words = text.split()
return [" ".join(words[i:i + size]) for i in range(0, len(words), size)]
def vectorize(text):
return Counter(re.findall(r"[a-z0-9]+", text.lower()))
def cosine(a, b):
dot = sum(a[w] * b[w] for w in a if w in b)
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
# Indexing: split, vectorize, store
index = []
for name, text in DOCS.items():
for i, piece in enumerate(chunk(text)):
index.append({"source": f"{name}#{i}", "text": piece, "vec": vectorize(piece)})
# Retrieval: score every chunk against the query, keep top k
def retrieve(query, k=2):
q = vectorize(query)
scored = sorted(index, key=lambda d: cosine(q, d["vec"]), reverse=True)
return [(d["source"], round(cosine(q, d["vec"]), 3), d["text"]) for d in scored[:k]]
# Augmentation: put the retrieved text into the prompt
def build_prompt(query, hits):
context = "\n".join(f"[{src}] {text}" for src, _, text in hits)
return f"Answer only from the context.\nContext:\n{context}\nQuestion: {query}\nAnswer:"
if __name__ == "__main__":
print(f"Indexed {len(index)} chunks")
q = "How many days of paid leave do employees get?"
hits = retrieve(q)
for src, score, text in hits:
print(src, score, text)
print("---")
print(build_prompt(q, hits))
Output from that run:
Indexed 6 chunks
leave.txt#0 0.624 Employees get 20 days of paid leave per year. Unused leave carries
refund.txt#0 0.178 Refunds are issued within 14 days of cancellation. Refunds go to the
---
Answer only from the context.
Context:
[leave.txt#0] Employees get 20 days of paid leave per year. Unused leave carries
[refund.txt#0] Refunds are issued within 14 days of cancellation. Refunds go to the
Question: How many days of paid leave do employees get?
Answer:
| Rank | Chunk | Cosine score | What it means |
|---|---|---|---|
| 1 | leave.txt#0 | 0.624 | The correct source |
| 2 | refund.txt#0 | 0.178 | Off topic, but it still goes into the prompt because k is 2 |
Two things show up in this output. First, the chunk boundary falls inside the carry-over rule. The phrase “Unused leave carries” lands in chunk 0, and “over up to 5 days.” lands in chunk 1. Chunk 1 did not make the top 2, so the model never sees the limit. Second, k=2 sends a refund passage to the model for a leave question. A score cutoff or a smaller k would drop it. Both problems are cheap to see here and expensive to find in production.
Stage 5: generate, and handle a silent context
The build_prompt function tells the model to answer only from the context. Add one more line to it: if the context does not contain the answer, the model should say so. Ask the model to name the source chunk for each claim, so a reader can check it. The sample stops before the model call on purpose. Send the prompt to any chat model API you use. The model call is the easy part, and most of the engineering work sits in retrieval.
Where a basic pipeline fails
Most failures are visible in the answer, and each has a retrieval cause. The table maps the symptom to the fix to try first.
| Failure | What the user sees | First fix to try |
|---|---|---|
| The answer is split across two chunks | A partial answer | Add overlap, or split on headers and paragraphs |
| Too few chunks retrieved | “Not in the documents” for a question that is answered there | Raise k, then test retrieval hit rate on a question set |
| Too many off-topic chunks | The answer mixes in unrelated facts | Lower k, add a score cutoff, or rerank |
| Two documents disagree, and no metadata says which is current | A confident wrong answer | Store status and date with each chunk, and remove old versions |
| Ingestion is run by hand | The index drifts from the source | Re-index when a source changes, or on a schedule |
The conflicting-policy case comes from the vendor tutorial, where two return policies with no status field led the system to an outdated 60-day answer.
Measure retrieval before you tune
Build a test set of 20 to 30 questions, each with the chunk that should answer it. This is our planning figure, not a standard. Then check these in order:
- Retrieval hit rate: is the right chunk in the top k for each question?
- Precision: how many of the retrieved chunks are relevant?
- Faithfulness: does the generated answer use only the retrieved text?
One naive RAG course names retrieval precision, retrieval recall and generation faithfulness as the measures to track. Change one setting at a time, and record the three numbers after each change. A change that improves the answer but lowers hit rate often means the model is guessing better, not retrieving better.
When to skip RAG
A RAG pipeline is not always the right answer. If the whole source fits in the prompt and changes rarely, paste it in. If the model has the facts but gets the format or tone wrong, the fault is behaviour, and examples or fine-tuning may fix it. Our comparison of prompting, RAG and fine-tuning walks through that choice. Fine-tuning vs RAG vs prompting: how to choose.
Retrieved text can also carry instructions written by someone else. Treat it as data, not as commands. Prompt injection guardrails covers how to limit that risk.
Next steps for engineers
If you are preparing for interviews, AI engineer interview questions on LLMs, RAG and agents gives model answers for the retrieval questions interviewers ask most. For the design side of what you put in the prompt, read prompt engineering vs context engineering. To test answers at scale, see how to evaluate an LLM application.
If you want a structured course, the Gen AI BootCamp lists a RAG module and a RAG chatbot project built with a vector database and LangChain, on its product page as read on December 1, 2026. The page lists 72 hours of live training. Check the schedule and the current price on the product page.
Questions people ask
What is a RAG pipeline?
A RAG pipeline is the set of steps that finds relevant text for a question and gives it to a language model as context. It has an indexing side that chunks, embeds and stores documents, and a query side that retrieves chunks and generates an answer. Retrieval-augmented generation names the method. The pipeline is the code that runs it.
What chunk size should I use in a RAG pipeline?
There is no universal size. Anthropic says general RAG chunks are usually no more than a few hundred tokens, but that comes from its own tests. Start with a size that holds a few complete paragraphs, measure retrieval hit rate on your question set, and change one setting at a time.
How many chunks should I retrieve?
Start with k between 3 and 5. the vendor tutorial uses 5. A higher k raises the chance the right chunk is included, but it also adds noise. Test k against your question set, and add a score cutoff if off-topic chunks keep reaching the prompt.
Do I need a vector database for a RAG pipeline?
Not for a small set of documents. the vendor tutorial stores its chunks in ChromaDB on a local machine and notes that ChromaDB is meant for local development and does not scale well. Move to a larger vector index when the corpus grows, when you need metadata filters, or when several services query the same data.
Is RAG better than fine-tuning?
They solve different problems. RAG adds facts that change often or are too large for the prompt. Fine-tuning changes behaviour, such as format, tone or labels. Many production systems use both, and the right first step depends on which fault you see.
How do I know my RAG answers are correct?
Check retrieval first. For each test question, confirm that the chunk holding the answer appears in the top k. Then confirm that the answer uses only what was retrieved. Track both numbers each time you change chunking, embeddings or k, so you can see which change helped.