Lesson 6 of 16 · Ingestion
Chunking Strategies
Split documents into chunks for RAG: fixed-size chunks with overlap, sentence and heading-aware chunking, added context and choosing a size, in Python.
- 7 min read
- Intermediate
- Reviewed
- Explain why documents are split into chunks, and what goes wrong with bad chunks
- Build fixed-size chunks with overlap
- Split by sentences and by headings, keeping each chunk meaningful
- Choose a starting chunk size and test it
Why split at all?
You could embed each whole document as one vector. But a 40-page handbook covers dozens of topics, and one vector can't represent them all well: it becomes a blurry average. And when it is retrieved, the whole document would be pasted into the prompt.
Chunk size is a balance:
| Chunks that are too small | Chunks that are too large |
|---|---|
| Lose context (“It must be approved by your manager.” What must?) | Mix several topics, so the embedding is vague |
| Split answers across chunks | Waste tokens on irrelevant text in the prompt |
| Need many chunks per answer | Fewer distinct results fit in the prompt |
Fixed-size chunks and overlap
The simplest method cuts every N words (or tokens). Its weakness is that cuts land anywhere, even mid-sentence. Overlap repeats a few words from the end of each chunk at the start of the next, so a fact near a boundary appears whole in at least one chunk:
text = ("Full-time employees get 25 days of paid annual leave per year. "
"Book holiday in the HR portal at least two weeks ahead. "
"Up to 5 unused days can be carried over to next year. "
"Carried-over days must be used by the end of March.")
def fixed_size_chunks(text, size, overlap):
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
print("12 words, no overlap:")
for c in fixed_size_chunks(text, size=12, overlap=0):
print(" |", c)
print("12 words, 4 overlapping:")
for c in fixed_size_chunks(text, size=12, overlap=4):
print(" |", c)Without overlap, “Up to” ends one chunk and “5 unused days can be carried over” starts the next, so neither chunk fully answers “How many days can I carry over?”. With 4 words of overlap, the third chunk contains the whole fact.
Splitting along the document's structure
Better chunks follow the boundaries the author already made: headings, paragraphs and sentences. A recursive splitter tries the biggest boundaries first (sections, then paragraphs), and only splits further (sentences, then words) when a piece is still too long.
Headings carry meaning that individual paragraphs lack. Adding them to each chunk makes it understandable on its own:
handbook = """# Time off
## Annual leave
Full-time employees get 25 days of paid annual leave per year.
Up to 5 unused days can be carried over to next year.
## Sick leave
Tell your manager before 10am on your first day off.
You can self-certify for up to 7 days.
# Equipment
## Laptops
New starters get a laptop. Laptops are replaced every 4 years."""
def chunk_by_headings(markdown, max_words=40):
chunks, section, path = [], [], []
def flush():
body = " ".join(section).strip()
if body:
# Prefix each chunk with its headings, so it still makes sense on its own
words = body.split()
for start in range(0, len(words), max_words):
chunks.append(" > ".join(path) + ": " + " ".join(words[start:start + max_words]))
section.clear()
for line in markdown.split("\n"):
if line.startswith("#"):
flush()
level = len(line) - len(line.lstrip("#"))
path[level - 1:] = [line.lstrip("# ").strip()] # keep parent headings, replace this level
elif line.strip():
section.append(line.strip())
flush()
return chunks
for c in chunk_by_headings(handbook):
print(c)“You can self-certify for up to 7 days” is vague alone. “Time off > Sick leave: … You can self-certify for up to 7 days” tells both the embedding model and the LLM exactly what it's about.
Common mistakes
Write a sentence-based chunker: pack whole sentences into chunks of at most 18 words.
sentences = [
"New starters get a laptop, a monitor and a headset.",
"Report a lost laptop to IT within 24 hours.",
"Laptops are replaced every 4 years.",
"Monitors are not replaced unless broken.",
]
max_words = 18
# Group whole sentences into chunks of at most max_words words.
# Never split a sentence. Print each chunk on its own line.
Why do many chunkers add overlap between neighbouring chunks?
Summary
- Documents are split into chunks so each embedding covers one topic and only relevant text reaches the prompt.
- Fixed-size chunking is simple; overlap protects facts near the cuts.
- Splitting by headings, paragraphs and sentences keeps chunks meaningful; adding headings gives each chunk context.
- Start around 200–500 tokens and test different settings on real questions.
Next: embedding and indexing chunks, and keeping the index up to date.
Finished reading? Tick it off to track your progress.