Sub topic 1
Where Chunking Sits in a RAG Pipeline
Prerequisites
Assume you know basic Python, embeddings, vector similarity search, tokens, and the general retrieve-then-generate pattern used by retrieval-augmented generation (RAG).
The RAG Pipeline
Chunking happens during ingestion, before documents are embedded and indexed. A typical pipeline is:
At query time, the system embeds the question, retrieves similar chunks, and passes those chunks to the language model. Chunking therefore affects both what can be found and what the model can understand.
Why We Chunk
A whole document is usually too large and contains unrelated material. Small chunks make similarity search more precise because each vector represents a narrower topic. However, chunks that are too small may omit the context needed to answer a question.
- Precision measures how many retrieved chunks are relevant.
- Recall measures how much of the relevant source material is retrieved.
- Noise is irrelevant text included in the model's context.
Large chunks often improve recall because related facts stay together, but they can lower precision and waste the context window. Small chunks can improve precision but may lower recall when an answer spans a boundary.
Tokens and Context Budgets
A token is a piece of text processed by a language model. Embedding models have a maximum input length. The generation model also has a context window, which limits the question, instructions, and retrieved chunks combined.
Choose chunk sizes in tokens, not only characters. Leave room for metadata and multiple retrieved chunks. A chunk that fits the embedding limit may still be too large for useful retrieval.
Choosing Chunk Size and Overlap
Overlap repeats text between neighboring chunks. It reduces boundary loss, but increases storage, embedding cost, and duplicate results.
| Content | Starting choice |
|---|---|
| Prose documentation | 300–600 tokens, 10–20% overlap |
| Short support articles | 150–400 tokens, small overlap |
| Code or tables | Preserve logical units before applying a size limit |
Test several settings against representative questions instead of treating these values as rules.
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
return [
" ".join(words[start:start + size])
for start in range(0, len(words), step)
if words[start:start + size]
]Exercise
Why can increasing overlap improve recall but reduce efficiency?
Show answer
Repeated boundary text makes it more likely that a needed fact appears in a retrieved chunk, but it creates more chunks, embeddings, storage, and duplicate results.