Learning path: Build Your First LLM App with Claude · Step 4 of 4
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
What you will learn
- Name the seven stages of a RAG pipeline and say which run once and which run per question
- Chunk a document with ids and embed the chunks with sentence-transformers
- Retrieve the nearest chunks by cosine similarity, then rerank them with a cross-encoder
- Build a prompt that makes the model cite the chunk id
Before you start
- Basic Python
- numpy arrays
RAG (retrieval augmented generation) can look like a pile of tools: loaders, splitters, embedding models, vector stores, rerankers. Underneath, it's one line with seven stages. Put that line in your head once and every RAG system you meet gets easier to read.
We'll follow one question, Can I carry over unused vacation days?, through a small pipeline built on the employee handbook of a company called Brightfield. The whole thing is one Python file, and it prints one line per stage.
A kitchen works at two times
Think of a restaurant kitchen. In the morning there's prep: the groceries come in, the cooks wash and chop, label every box and stack them in the fridge. No guest has ordered anything yet.
Then an order comes in. The cook grabs the five boxes that look right, tastes them, keeps the best two, and plates the dish.
A RAG pipeline is exactly this kitchen. You prep the documents once, then cook an answer for every question.
Seven stages, two lanes
- Prepare lane, run once (and again when a file changes): ingest reads the files, chunk cuts them into pieces, embed turns each piece into numbers, store keeps them together.
- Answer lane, run on every question: retrieve finds the nearest five chunks, rerank reads them closely and keeps two, generate writes the answer.
One detail ties the lanes together. Before the question can retrieve anything, it's embedded with the same model as the chunks. Different models put text in different number spaces, and the comparison would mean nothing.
The whole pipeline in one file
The project uses sentence-transformers for two local models (the all-MiniLM-L6-v2 embedder and the ms-marco-MiniLM-L-6-v2 cross-encoder) and numpy. Here's pipeline.py:
import pathlib
import re
import sys
import numpy as np
from sentence_transformers import CrossEncoder, SentenceTransformer
from model import get_model
HERE = pathlib.Path(__file__).parent
embedder = SentenceTransformer("all-MiniLM-L6-v2")
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
# 1. ingest: read the source file
def ingest():
return (HERE / "handbook.md").read_text(encoding="utf-8")
# 2. chunk: each section in pieces of three sentences
def chunk(text):
chunks = []
for part in text.split("\n## ")[1:]:
head, body = part.strip().split("\n", 1)
sents = re.split(r"(?<=[.!?])\s+", body.strip())
for i in range(0, len(sents), 3):
cid = f"{head} #{i // 3 + 1}"
chunks.append({"id": cid, "text": " ".join(sents[i:i + 3])})
return chunks
# 3. embed: text -> 384 numbers
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
# 4. store: keep the vectors next to the chunks
def store(chunks):
return {"chunks": chunks, "vectors": embed([c["text"] for c in chunks])}
# 5. retrieve: nearest chunks by cosine
def retrieve(index, question, k=5):
scores = index["vectors"] @ embed([question])[0]
top = np.argsort(-scores)[:k]
return [(index["chunks"][i], float(scores[i])) for i in top]
# 6. rerank: a cross-encoder reads question + chunk together
def rerank(question, hits, keep=2):
scores = reranker.predict([(question, c["text"]) for c, _ in hits])
order = np.argsort(-scores)[:keep]
return [(hits[i][0], float(scores[i])) for i in order]
# 7. generate: prompt with sources -> answer
def generate(question, best):
passages = "\n".join(f"[{c['id']}] {c['text']}" for c, _ in best)
prompt = ("Answer using only the passages below. Cite the id in brackets.\n\n"
f"{passages}\n\nQuestion: {question}")
return prompt, get_model().ask(prompt)
The file's __main__ block runs the stages in order and prints one line each. Now let's walk the question through.
Stages 1 and 2: ingest and chunk
Ingest reads handbook.md: 6,121 characters. Chunk splits it at every ## heading, then cuts each section into pieces of up to three sentences. That gives 26 chunks. Here's one:
[Annual Leave #1] Every full-time employee gets twenty-five days of paid annual leave per calendar year, plus public holidays. Leave builds up month by month, so someone who joins in July receives about twelve days for that first year. You may carry over up to five unused days into the next year, and they must be used by the end of March.
Look at the id. It carries the section name and the piece number, so any answer built from this chunk can point back to where it came from.
Stages 3 and 4: embed and store
The embedding model turns that chunk into 384 numbers. The first five are 0.097 0.001 0.037 0.042 0.061. Because of normalize_embeddings=True, every vector has a length of one.
Do that for all 26 chunks and you have a 26 × 384 table, kept right next to the chunks. That's the store. In a bigger system this is a vector database; here it's a Python dict.
The prepare lane ends here. Nobody has asked anything yet.
Stage 5: retrieve the nearest five
Now the question arrives. It's embedded with the same model, and one dot product scores it against all 26 chunks at once. Since every vector has length one, the dot product is the cosine similarity. argsort puts the scores in order, best first, and we keep five.
| Rank | Chunk | Cosine |
|---|---|---|
| 1 | Annual Leave #1 | 0.53 |
| 2 | Sick Leave #2 | 0.42 |
| 3 | Leaving Brightfield #1 | 0.40 |
| 4 | Leaving Brightfield #2 | 0.39 |
| 5 | Expenses and Travel #1 | 0.38 |
The top hit is the right one. But retrieval is fast and rough. Number four says unused annual leave is paid out when you leave, which is useful for this question, and it sits behind sick leave.
Stage 6: rerank, read closely, keep two
A cross-encoder works differently from the embedder. It reads the question and a chunk together, as one pair, and scores the pair. That's slower per chunk, which is why we only hand it the five retrieved chunks, not all 26.
| Kept | Chunk | Cross-encoder score |
|---|---|---|
| 1 | Annual Leave #1 | +4.29 |
| 2 | Leaving Brightfield #2 | -2.16 |
Leaving Brightfield #2 jumped from fourth to second, and sick leave is gone. These scores are on a different scale from cosine, so you only compare them with each other.
Stage 7: generate an answer with a source
The prompt has three parts: the rule, the two chunks each with its id in square brackets, and the question last. It comes to 644 characters:
Answer using only the passages below. Cite the id in brackets.
[Annual Leave #1] Every full-time employee gets twenty-five days of paid annual leave per calendar year, plus public holidays. Leave builds up month by month, so someone who joins in July receives about twelve days for that first year. You may carry over up to five unused days into the next year, and they must be used by the end of March.
[Leaving Brightfield #2] Unused annual leave is paid out with your final salary. We would love to hear honest feedback in an exit conversation, and you are always welcome to return one day.
Question: Can I carry over unused vacation days?
The run in the lecture uses a stand-in test model, so it works without an API key. Put a key in .env and get_model() sends the same prompt to a real Claude model instead. The test model's reply:
You may carry over up to five unused days into the next year, and they must be used by the end of March. [Annual Leave #1]
The model only saw these two chunks, and the id in brackets lets a person open the handbook and check.
Common mistakes
- Embedding the question with a different model from the chunks. The scores become meaningless.
- Dropping the chunk id. Without it, nobody can check where an answer came from.
- Trusting cosine order as final. Retrieval is a rough first pass; the useful chunk may sit at rank four.
- Reranking everything. A cross-encoder is slow per pair. Retrieve a few, then rerank those.
- Comparing cosine and rerank scores. They're on different scales.
- Re-running the prepare lane on every question. Prep once; redo it only when a file changes.
Quick recap
| Stage | What it does | Brightfield run |
|---|---|---|
| 1 Ingest | Read the files | 6,121 characters |
| 2 Chunk | Cut into pieces with ids | 26 chunks of up to 3 sentences |
| 3 Embed | Text to vectors | 384 numbers each, length one |
| 4 Store | Keep vectors next to chunks | 26 × 384 |
| 5 Retrieve | Nearest chunks by cosine | Top 5, best 0.53 |
| 6 Rerank | Cross-encoder reads each pair | Keeps 2, +4.29 and -2.16 |
| 7 Generate | Prompt with sources, answer with id | 644-character prompt, cites [Annual Leave #1] |
Try it yourself
- Run
python pipeline.pyand read the seven lines it prints. - Pass your own question, for example
python pipeline.py "How much is the daily meal allowance?", and watch the rerank order. - Change
k=5inretrieve()to 10. Does the rerank result change? - Ask something the handbook can't answer and look at the scores.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (opens in a new tab)