Course contents · Lesson 7 of 16

Chunking Documents for RAG: A Practical Guide

A RAG App · Lesson 7 of 16 · 11 min Hands-on

Someone asks your new handbook assistant "How many days of annual leave do I get?" The app cannot paste the whole handbook into every prompt, so it must first find the passage that answers, and it can only find passages that exist as separate pieces. Chunking documents for RAG is how you make those pieces. In this lesson you split a small handbook by size with overlap, then by headings, and check the result by eye.

Why a RAG app needs chunks

RAG, retrieval-augmented generation, is a way to build an app: before the model answers, your code retrieves (searches for and fetches) the passages most related to the question and puts them in the prompt. What Is RAG? explains the idea; lessons 8 to 10 build it. This lesson prepares the passages.

A model reads only a limited amount at once, its context window: 4,096 tokens by default on a CPU, as you saw in lesson 3. A token is a piece of text, about four characters of English on average. The window must hold the system prompt, the question, the passages and the reply, so you can send a few passages, not a folder.

A chunk is one of those passages: a piece of a document, stored with notes on where it came from. The search compares the question with every chunk and returns the best few. So a chunk must be small enough to be about one thing and large enough to make sense alone.

Load the handbook and cut it by size

The lab folder course-labs/building-llm-apps/07-chunking holds data/handbook/: six short Markdown files from the staff handbook of Kettle and Leaf, the tea shop from lesson 6. Markdown is plain text with light marks, such as # before a heading. chunk.py reads each file into one Python string, so a chunk's position is a character offset in that string, counting from 0.

The simplest method is fixed-size chunking: cut every size characters. The cut lands wherever the count ends, often mid-sentence. Overlap softens that: each window starts size minus overlap characters after the one before, so neighbours share overlap characters. With 800 and 100, windows start at 0, 700, 1400 and so on. The core of chunk.py:

def windows(start, end, size, overlap):
    step = size - overlap
    while start < end:
        stop = min(start + size, end)
        yield start, stop
        if stop == end:
            break
        start += step

text = path.read_text(encoding="utf-8")        # one file, one string
spans = list(windows(0, len(text), 800, 100))   # 01-welcome.md: [(0, 800), (700, 1452)]

The last window of a file is usually shorter, and no window spans two files. The script needs only Python 3.10 or newer, no packages and no model, so Ollama can stay stopped. In the lab folder, run:

python3 chunk.py data/handbook --size 800 --overlap 100

It prints a count per file and the first three chunks in full, each with source file, start offset and length. The output never changes between runs; texts are trimmed here:

Read 6 files from data/handbook (8,132 characters)
Mode: fixed | size: 800 | overlap: 100

Chunks per file:
    2  01-welcome.md
    2  02-working-hours.md
    3  03-leave.md
    2  04-pay-and-expenses.md
    2  05-customer-returns.md
    2  06-leaving-the-company.md
   13  total

First 3 chunks:

--- chunk 1 | 01-welcome.md | start 0 | length 800 ---
# Welcome to Kettle and Leaf
...
- Care for each other: we speak kindly, share what we know and ask for help early.

## Your first

--- chunk 2 | 01-welcome.md | start 700 | length 752 ---
t.
- Care for each other: we speak kindly, share what we know and ask for help early.

## Your first week
...
--- chunk 3 | 02-working-hours.md | start 0 | length 800 ---

It worked if the counts add up to 13 and chunk 2 starts at 700. Now read the cut: chunk 1 ends inside the heading ## Your first week, a broken fragment. Chunk 2 starts 100 characters before that cut, at the stray t. of the line before, and holds the heading whole with its text. chunk.py: error: data/handbook is not a folder means you are not in 07-chunking.

The strip below shows the same idea with tiny numbers. Notice the guarantee: a phrase no longer than the overlap, such as a short sentence, is always whole in at least one chunk. A longer sentence can still be cut everywhere, one reason for the smarter split next.

The sentence Customers can return unopened tea within 30 days of delivery for a full refund, cut into three overlapping chunks drawn as brackets, illustrative with size 36 and overlap 14 characters. Chunk 1 starts at 0, length 36, and ends inside the word within. Chunk 2 starts at 22, length 36. Chunk 3 starts at 44, length 35. Neighbours share 14 characters, highlighted: nopened tea wi and days of delive. The phrase within 30 days is whole in chunk 2.
Chunk 1 cuts "within" in half, but the overlap puts "within 30 days" whole in chunk 2.

Smarter splits: headings, then paragraphs, then size

Documents already mark their own boundaries: headings start topics and blank lines end paragraphs. --mode headings uses them in that order. Each section, a heading plus the text under it, becomes one chunk if it fits in --size. A longer section is cut at blank lines into groups of whole paragraphs, and only a paragraph longer than --size is cut into windows with overlap.

Libraries do the same: LangChain's recursive splitter tries paragraph breaks, then line breaks, then spaces, and counts characters by default.

Every chunk also keeps metadata, data about the data: its source file, section heading, start offset and length. You need it later to show where an answer came from, and to put the heading back in front of a piece whose text lost it. Follow 03-leave.md through the flowchart: only its one long section gets cut, and at a paragraph break.

Flowchart of chunk.py in headings mode. The document 03-leave.md is split by headings into 5 sections. Is a section longer than --size? No: keep it whole as one chunk. Yes: cut the long section at blank lines into whole paragraphs, then by size with overlap. Example: the Annual leave section is 939 characters, more than 800, so it becomes 655 plus 282, cut at a blank line. Both paths end in a chunk list with metadata: Leave, start 0, length 87; Annual leave, start 89, length 655; Annual leave, start 746, length 282; and 3 more for Sick leave, Public holidays and Parental leave. Every chunk remembers its file, its section and where it starts.
Only the section that is too long gets cut, and at a paragraph break, not mid-sentence.

Run the same handbook in headings mode, which keeps --size as the largest chunk:

python3 chunk.py data/handbook --mode headings --size 800

You should see 34 chunks instead of 13: one per section, plus one because Annual leave was cut in two. Each header line now includes its section, such as section: Who we are. Add --out chunks.jsonl to save every chunk as one JSON object per line. A misspelt mode such as heading gets an invalid choice error.

Size is a trade-off, so look at your chunks

Chunk size trades precision against context. A tiny chunk matches a question sharply but may not say what it is about. A huge chunk mixes topics, so it matches many questions weakly and fills the window with text the answer does not need. In the next lesson each chunk becomes an embedding, one list of numbers for its meaning, and four topics blur into one.

Three rows comparing chunk sizes on 03-leave.md, illustrative, with rough tokens at about 4 characters each. Size 100, about 25 tokens: You can carry up to 5 unused days into the next year. They must be used by the end of March, or they. Precise, one rule, but it never says leave. Size 800, about 200 tokens: the title, then Annual leave: 18 days a year, how and when to ask, and the first carry-over sentence. One topic with its context, a good place to start. Size 4000, up to 1,000 tokens: all of 03-leave.md, 1,742 characters, four kinds of leave in one chunk. Context but noise; 4 such chunks are about 4,000 tokens, nearly all of a 4,096 window.
The 100-character piece never says "leave"; the 4000-character one says everything at once.

On this handbook, changing the flags gives these totals:

FlagsTotal chunksWhy
--size 400 --overlap 10028A window every 300 characters
--size 800 --overlap 10013A window every 700 characters
--size 1600 --overlap 1007Only 03-leave.md needs two
--mode headings --size 80034One per section, plus one

Bad chunking is a common hidden cause of poor RAG answers, because nothing reports an error: the model reads the wrong text and still writes a fluent answer. So count your chunks and read a few by eye. Look for chunks that are only a heading, a list cut in half, a rule separated from what it is about, or one chunk that covers half a document.

Check yourself

01-welcome.md has 1,452 characters. Why does --size 800 --overlap 100 give two chunks, and where does the second start?

Windows start every 700 characters (800 minus the overlap), so at 0 and 700. The second reaches the end of the file, so it is shorter, 752 characters, and no third is needed.

Someone sets --overlap 0 to store less text. What can go wrong?

A cut can fall inside a sentence or a heading, and then no chunk holds it whole, so a search for that fact finds only halves. Overlap repeats a little text so that short phrases survive whole somewhere.

Your RAG app says it does not know how many leave days carry over, yet the handbook says 5. What do you check first?

The chunks. The rule may sit in a chunk whose text never says "annual leave", or be cut mid-sentence, so the search misses it. Fix that before you change the prompt or the model.

Go deeper