Learning path: Build and Measure a RAG System · Step 4 of 12
Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
Where you cut decides what search can find. Cut a 13-section employee handbook three ways in plain Python and count the damage: fixed size gives 12 chunks with 12 cut and 11 mixed, sentences give 0 cut but 9 mixed, and headings give 13 clean chunks that know their source.
What you will learn
- Cut a document three ways: fixed size with overlap, whole sentences, and by heading
- Measure each cut with two checks: does it cut a sentence, does it mix topics
- See what overlap buys and what it costs
- Store the source and heading with every chunk so answers can be traced
Before you start
- Basic Python strings and regular expressions
- Why RAG Exists
Chunking is how you cut a document into pieces before search can use it. It sounds like housekeeping, but it decides what can be found: every later stage of a RAG system only ever sees those pieces. Search can only find what a chunk holds.
We'll try three ways to cut the same document, measure each one with two simple checks, and see which one keeps the answer whole. Everything here is standard-library Python, with no API key.
Where does the knife go?
Think of cutting a layered cake for a party. Slices too big, and nobody can eat one; in search, that's one chunk holding many topics. Slices too small, and the topping falls off; a fact loses what it was about. The best way is to cut along the layers, so each slice is one whole piece. Same cake, same knife. What changes is where you cut.
One handbook, one question
Brightfield's employee handbook, handbook.md, has 13 sections and 5,806 characters. An employee asks: How many days of annual leave do I get? The answer sits in one section.
Keep the whole handbook as one block and that's one chunk of 5,806 characters, where leave, expenses and security all blur together. The cut decides the answer.
load_sections reads the file and turns every ## heading into a (heading, text) pair:
import re
from pathlib import Path
HANDBOOK = Path(__file__).with_name("handbook.md")
def load_sections(path=HANDBOOK):
sections = []
for block in path.read_text(encoding="utf-8").split("\n## ")[1:]:
heading, _, body = block.partition("\n")
sections.append((heading.strip(), " ".join(body.split())))
return sections
Way 1: fixed size, the knife does not read
def fixed_chunks(text, size=600, overlap=100):
chunks, start = [], 0
while start < len(text):
chunks.append(text[start:start + size])
if start + size >= len(text):
break
start += size - overlap
return chunks
Take 600 characters, then move forward by size - overlap, so from 0 to 500, and repeat. With an overlap of 0, the first cut lands here:
chunk 1 ends: ...you choose your own schedule, a
chunk 2 starts: s long as you complete your ag...
The word "as" is cut in half. One piece has no ending, the other has no beginning, and search only finds half of the sentence.
Overlap: a safety margin between chunks
With an overlap, each chunk starts a little before the last one ended, so those characters sit in both chunks:
| Overlap | Chunks | Sentences kept whole (of 66) |
|---|---|---|
| 0 | 10 | 57 |
| 100 | 12 | 64 |
| 200 | 15 | 66 |
More overlap saves more sentences, but you store (and embed) more chunks.
Way 2: whole sentences
def sentence_chunks(text, max_chars=600):
chunks, current = [], ""
for sentence in re.split(r"(?<=[.!?])\s+", text):
if current and len(current) + len(sentence) + 1 > max_chars:
chunks.append(current)
current = sentence
else:
current = (current + " " + sentence).strip()
if current:
chunks.append(current)
return chunks
The regex splits the text after every ., ! or ?, giving 66 sentences. Then sentences drop into the current chunk until the next one would push it past 600 characters. The whole welcome section fits (391 characters), and there's still room, so two sentences from Working Hours drop in too. The next sentence would make 685, over the limit, so the chunk closes and that sentence starts chunk two.
No sentence is cut any more. But look at chunk one: it holds two topics, the welcome and working hours.
Way 3: cut along the section lines
The handbook already has structure. Cutting by heading takes one line:
def heading_chunks(sections):
return [{"source": "handbook.md", "heading": h, "text": b} for h, b in sections]
Thirteen chunks, one per section, and each one stores three things: the source file, the heading, and the text. The Annual Leave chunk holds the answer, twenty-five days, and it knows exactly where it came from, so an answer built on it can name its source.
Is it cut? Is it mixed?
Two small checks turn "looks fine" into numbers:
def cuts_a_sentence(chunk):
starts_clean = chunk[0].isupper() or chunk[0].isdigit()
ends_clean = chunk.rstrip()[-1] in ".!?"
return not (starts_clean and ends_clean)
def topics_touched(chunk, text, sections):
start = text.find(chunk)
end, offset, touched = start + len(chunk), 0, 0
for _, body in sections:
if offset < end and start < offset + len(body):
touched += 1
offset += len(body) + 1
return touched
cuts_a_sentence looks at both edges: a chunk that starts with a small letter or ends mid-word is cut. topics_touched counts how many sections a chunk reaches into; more than one means it's mixed. Running chunkers.py prints one line per strategy (fixed uses the default overlap of 100):
python chunkers.py
fixed chunks=12 avg=575 cut=12 mixed=11
sentence chunks=11 avg=526 cut=0 mixed=9
heading chunks=13 avg=445 cut=0 mixed=0
| Strategy | Chunks | Cut | Mixed | Knows its heading |
|---|---|---|---|---|
| Fixed size + overlap 100 | 12 | 12 | 11 | No |
| Sentences, max 600 | 11 | 0 | 9 | No |
| By heading | 13 | 0 | 0 | Yes |
Only the heading cut keeps every sentence and every topic whole.
You will hear these too
- Recursive chunking tries a big split first, then paragraphs, then sentences, until the pieces fit.
- Semantic chunking cuts where the topic shifts.
- Parent document chunking searches small pieces, then gives the model the whole section they came from.
Each one has the same goal: keep one idea together.
Common mistakes
- Cutting by size when the document already has headings, paragraphs or sections.
- Using zero overlap with a fixed-size cut. Sentences break at every boundary.
- Throwing away the source and heading. Without them, nobody can check where an answer came from.
- Judging a chunker by eye. Count cut sentences and mixed topics, like the two checks above.
- Assuming one size suits every document. A handbook section and a long contract clause need different cuts.
Quick recap
- Start with the structure the document already has.
- If you must cut by size, keep some overlap, and accept you'll store more chunks.
- Store the source and heading with every chunk.
Try it yourself
Call fixed_chunks with a size of 300 and an overlap of 50 (the project's python demo.py fixed "300 50" does exactly that). The run gives:
fixed chunks=24 avg=289 cut=23 mixed=13
Smaller pieces, twice as many chunks, and still almost all of them cut. Now try 600 and 200, and compare with the overlap table above.
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (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".
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.
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.