Sub topic 1
Where Chunking Sits in a RAG Pipeline
Prerequisites
This chapter assumes you know basic Python and what an embedding is. It also assumes you know that vector similarity search finds the stored vectors closest to a query vector. You should have a general idea of retrieval-augmented generation (RAG): retrieve relevant text, then give it to a language model to generate an answer. You should know that a token is the unit of text a language model reads, usually a word or part of a word.
The four stages
A RAG system has two phases. The indexing phase runs ahead of time on your documents. The query phase runs each time a user asks a question. Chunking belongs to the indexing phase, but its effects show up in the query phase.
The four stages are:
- Ingest. Load documents (PDFs, web pages, Markdown, tickets) and extract plain text. Then split that text into chunks. A chunk is a piece of a document stored and retrieved as one unit.
- Embed. Pass each chunk through an embedding model to get a vector. Store the vector, the chunk text, and any metadata in a vector index.
- Retrieve. Embed the user's question with the same model. Ask the index for the top k chunks whose vectors are closest to the question vector.
- Generate. Put the retrieved chunks and the question into a prompt. The language model writes an answer from that context.
Why the position matters
Chunking happens before everything else that you can tune. Each later stage only sees what chunking produced.
- Embedding turns one chunk into one vector. A chunk that mixes three topics gets one vector that blurs all three.
- Retrieval returns whole chunks. It cannot return a sentence that was split away from the sentence it depends on.
- Generation can only use the text it is given. If the chunk holding the answer was cut in half, the model sees half an answer.
Changing the chunking means re-embedding and re-indexing the whole corpus. The embedding model, the number of results k, and the prompt template are cheaper to change. This is why chunking decisions deserve care early.
A minimal pipeline
The sketch below shows the whole flow in one place. The embed function is a stand-in that you would replace with a real embedding model. The chunker is a simple word-based splitter, which later chapters improve on.
import math
def chunk_words(text, size=200, overlap=40):
if overlap >= size:
raise ValueError("overlap must be smaller than size")
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
def embed(text):
# Placeholder: counts of a few letters. Use a real model in practice.
return [text.lower().count(c) for c in "aeiou"]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
return dot / norm if norm else 0.0
def build_index(documents):
index = []
for doc_id, text in documents.items():
for n, chunk in enumerate(chunk_words(text, size=50, overlap=10)):
index.append({"doc": doc_id, "n": n, "text": chunk, "vec": embed(chunk)})
return index
def retrieve(index, question, k=3):
q = embed(question)
ranked = sorted(index, key=lambda item: cosine(q, item["vec"]), reverse=True)
return ranked[:k]
docs = {"faq": "Refunds are issued within 14 days of purchase. " * 30}
index = build_index(docs)
for hit in retrieve(index, "How long do refunds take?", k=2):
print(hit["doc"], hit["n"], hit["text"][:40])Each stage is a separate function. The retrieve and generation steps never see the original document, only the chunks that build_index stored.
Common errors at this stage
- Chunking before cleaning. Navigation menus, page footers, and repeated headers become chunks and compete with real content in retrieval. Clean the extracted text first.
- Changing the chunker without re-indexing. Old and new chunks then sit in one index and give inconsistent results.
- Embedding the question and the chunks with different models. Their vectors are not comparable.
- Treating chunking as a fixed default. The right setting depends on your documents and questions, which you can measure later in this tutorial.
Exercise
You change your chunk size from 200 words to 100 words. Which pipeline stages must be re-run, and why?
Show answer
Chunking, embedding, and index storage must be re-run for the whole corpus. Smaller chunks produce different text pieces, so each needs a new vector, and the old vectors no longer match the new chunks. Question embedding and generation do not change, although retrieval results and answers may differ.