Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 4 steps

Build Your First LLM App with Claude
  1. 1
    LLM Tokens, Context Windows and Cost: What One Question Really Costs
  2. 2
    The Claude Messages API: Your First Call, Field by Field
  3. 3
    Claude Tool Use: How tool_use and tool_result Work in the Messages API
  4. 4
    The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

Learning path: Build Your First LLM App with Claude · Step 4 of 4

Also in:
Build and Measure a RAG System

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.

Chaand Sheikh

·27 November 2026Retrieval and RAG

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

The RAG pipeline: a prepare lane and an answer lane Prepare: once, and again when a file changes 1 Ingest read the files 2 Chunk cut into pieces 3 Embed text to numbers 4 Store keep together vector store: chunks + vectors question, embedded by the same model Answer: on every question 5 Retrieve nearest five 6 Rerank read closely, keep two 7 Generate answer with a source search [Annual Leave #1]
The prepare lane fills the vector store once. The answer lane runs for every question.
  • 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.

RankChunkCosine
1Annual Leave #10.53
2Sick Leave #20.42
3Leaving Brightfield #10.40
4Leaving Brightfield #20.39
5Expenses and Travel #10.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.

KeptChunkCross-encoder score
1Annual Leave #1+4.29
2Leaving 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

StageWhat it doesBrightfield run
1 IngestRead the files6,121 characters
2 ChunkCut into pieces with ids26 chunks of up to 3 sentences
3 EmbedText to vectors384 numbers each, length one
4 StoreKeep vectors next to chunks26 × 384
5 RetrieveNearest chunks by cosineTop 5, best 0.53
6 RerankCross-encoder reads each pairKeeps 2, +4.29 and -2.16
7 GeneratePrompt with sources, answer with id644-character prompt, cites [Annual Leave #1]

Try it yourself

  1. Run python pipeline.py and read the seven lines it prints.
  2. Pass your own question, for example python pipeline.py "How much is the daily meal allowance?", and watch the rerank order.
  3. Change k=5 in retrieve() to 10. Does the rerank result change?
  4. Ask something the handbook can't answer and look at the scores.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Build Your First LLM App with Claude · step 4 of 4

Previous
Claude Tool Use: How tool_use and tool_result Work in the Messages API

Related course on Udemy

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 (paid course, opens in a new tab)

Related posts

What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break

A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".

Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors

Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.

Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning

A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.

Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations

Swap a toy embedder for a model that learned. Two roads (all-MiniLM-L6-v2 on your machine, or OpenAI's API with your key), three sizes (384, 1,536 and 3,072 numbers), one rule, and three use cases built on the same rank function, with real scores.

On this page

  • A kitchen works at two times
  • Seven stages, two lanes
  • The whole pipeline in one file
  • Stages 1 and 2: ingest and chunk
  • Stages 3 and 4: embed and store
  • Stage 5: retrieve the nearest five
  • Stage 6: rerank, read closely, keep two
  • Stage 7: generate an answer with a source
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

Related course on Udemy

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 (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.