Sub topic 5
Splitting Documents into Chunks
This chapter assumes you know basic Python and have a cleaned document from the ingestion step. Chunking is the step that turns that document into the units your RAG system will embed, retrieve, and show to the model.
Why chunk at all
An embedding model maps a piece of text to one vector. If you embed a whole 40-page manual, that vector averages every topic in it, and a query about one topic matches poorly. Chunks that are too large also waste prompt space and bury the relevant sentence.
Chunks that are too small have the opposite problem. A sentence like "It expires after 30 days" loses its meaning when the sentence naming the subject lands in a different chunk.
So chunk size trades precision against context. A common starting point is 200 to 500 tokens per chunk. Tune it against your own questions.
Fixed-size chunks with overlap
The simplest strategy cuts the text into windows of a set length. Overlap repeats the end of one chunk at the start of the next, so a sentence cut at a boundary still appears whole in a neighboring chunk.
def chunk_text(text, size=500, overlap=50):
if not 0 <= overlap < size:
raise ValueError("overlap must be in [0, size)")
step = size - overlap
chunks = []
for start in range(0, len(text), step):
chunks.append(text[start:start + size])
if start + size >= len(text):
break
return chunksEach window starts size - overlap characters after the previous one. The break stops the loop once a window reaches the end of the text. Without it, the loop would add a tiny trailing chunk that only repeats the overlap.
Try it on a short string:
sample = "abcdefghijklmnopqrstuvwxyz"
for chunk in chunk_text(sample, size=10, overlap=3):
print(chunk)This prints abcdefghij, hijklmnopq, opqrstuvwx, and vwxyz. Each chunk shares three characters with the one before it.
Structure-aware chunking
Fixed windows ignore meaning. They can split a word, a sentence, or a code block. Structure-aware strategies cut at natural boundaries instead.
| Strategy | Splits on | Strength | Weakness |
|---|---|---|---|
| Fixed-size | Character or token count | Simple, predictable size | Cuts mid-sentence |
| Recursive | Paragraphs, then sentences, then words | Keeps units whole where possible | Sizes vary |
| Document-based | Headings, sections, code blocks | Chunks match the author's topics | Needs reliable structure |
Recursive splitting tries the largest separator first, such as a blank line. If a piece is still too long, it falls back to a smaller separator, such as a sentence end. Many libraries implement this, but the idea fits in a few lines.
Keep metadata with each chunk
Store the source file, section heading, and position with every chunk. You will need them later for metadata filtering and citations. A heading prepended to the chunk text also helps the embedding capture the topic.
Common errors
- No overlap, or too much. With no overlap, facts on a boundary get cut. With overlap near the chunk size, you store near-duplicates and they crowd the top results.
- Ignoring structure. Splitting tables or code blocks in half produces chunks that make no sense alone.
- Never testing. Read a sample of your chunks. If a chunk does not make sense by itself, a model will not be able to use it either.
Exercise
You call chunk_text on a 1,000-character string with size=400 and overlap=100. What are the start positions of the chunks, and how many chunks result?
Show answer
The step is 400 - 100 = 300, so windows start at 0, 300, 600, and 900. The window at 600 covers 600 to 1000, which reaches the end of the text, so the loop breaks there. Three chunks result, starting at 0, 300, and 600. The last chunk is 400 characters long.
Exercise
Users ask about a policy, but retrieved chunks often contain the answer's second half without the subject. Name two chunking changes that could help.
Show answer
Increase the overlap or the chunk size so the subject and the detail stay together. Alternatively, switch to structure-aware splitting by section and prepend the section heading to each chunk.