How to chunk documents
9 min read
Why documents are split
A retriever cannot return a whole 40-page manual for every question. The manual would fill the model's context, and most of it would be unrelated. So the manual is split into ChunkingSplitting a document into passages that a retriever can return one at a time. Chunk size and boundaries decide what the model can read, so a bad cut can separate a rule from its condition. in advance, and the search ranks the chunks.
The chunk is the unit of everything that follows. Search compares a question with chunks. The model reads chunks. A citation points to a chunk. If a chunk is cut in the wrong place, no later step can repair it.
The size trade-off
| Small chunks | Large chunks | |
|---|---|---|
| Match a question | Closely, because they hold one idea | Loosely, because they hold several |
| Keep the surrounding detail | Often not | Usually |
| Cost in the prompt | Low for each chunk, so you can return more | High for each chunk |
| Typical failure | A rule is separated from its condition | The answer is buried among other text |
Size is easiest to think about in TokenA small piece of text that a model reads or writes as one unit, such as a short word, part of a longer word or a punctuation mark. In English, one token is about four characters., because the model's context is measured in tokens. A few hundred tokens is a common starting point, and the right size for your documents comes from testing, not from a rule. Questions that need one fact favour small chunks. Questions that need an explanation favour larger ones.
Fixed windows and overlap
The simplest method cuts the text every size words. It is easy to write and it ignores meaning, which is its weakness. The program below cuts a short policy into 12-word windows, first with no overlap and then with an overlap of 4 words.
text = "You can return an unused bike within 30 days. The bike must still have its original tyres. A refund goes to the original payment method within 5 business days."
words = text.split()
def windows(words, size, overlap):
step = size - overlap
return [" ".join(words[start:start + size]) for start in range(0, len(words) - overlap, step)]
for overlap in (0, 4):
print(f"overlap {overlap}")
for chunk in windows(words, 12, overlap):
print(" ", chunk)It prints:
overlap 0
You can return an unused bike within 30 days. The bike must
still have its original tyres. A refund goes to the original payment
method within 5 business days.
overlap 4
You can return an unused bike within 30 days. The bike must
days. The bike must still have its original tyres. A refund goes
tyres. A refund goes to the original payment method within 5 business
method within 5 business days.With no overlap, the first cut falls inside a sentence: "The bike must" ends one chunk, and "still have its original tyres" starts the next. A question about the condition for a return finds half of it. With an overlap of 4 words, the second chunk repeats the end of the first, so one chunk holds the whole sentence "The bike must still have its original tyres."
Overlap costs storage and creates repeats, so keep it modest. Between 10 and 20 per cent of the chunk size is a usual choice, and you can test it like any other setting.
Split on the structure instead
A document already has natural joints: headings, paragraphs, list items. Cutting there keeps related sentences together. This is why the previous Lesson kept the headings.
document = """# Returns
You can return an unused bike within 30 days.
The bike must still have its original tyres.
# Refunds
A refund goes to the original payment method within 5 business days.
# Shipping
Standard shipping takes 3 to 5 business days."""
def by_heading(document):
chunks = []
for section in document.split("\n# "):
heading, *body = section.lstrip("# ").split("\n")
chunks.append({"heading": heading, "text": " ".join(line for line in body if line)})
return chunks
for chunk in by_heading(document):
print(chunk["heading"], "|", len(chunk["text"].split()), "words |", chunk["text"])It prints:
Returns | 17 words | You can return an unused bike within 30 days. The bike must still have its original tyres.
Refunds | 12 words | A refund goes to the original payment method within 5 business days.
Shipping | 8 words | Standard shipping takes 3 to 5 business days.Each chunk is one topic, and the heading travels with it. Keeping the heading matters: a chunk that says only "30 days" is hard to match, and one that says "Returns: 30 days" is easy. Many systems add the heading to the start of the chunk's text for this reason.
Splitting by structure has its own limit. A section can be one line or ten pages. When a section is too long, split it again by paragraph or sentence, with a size limit as the fallback.
Return the neighbours
One more idea removes much of the size dilemma. Search small chunks, because they match well, and then return the larger section around the best one. This is often called parent-child retrieval: the small chunk finds the place, and its parent supplies the context.
Choosing a method
- Start with the document's structure: headings, then paragraphs.
- Add a size limit, and split anything longer by sentence.
- Add a small overlap where chunks are cut inside a section.
- Read twenty chunks yourself. Each should make sense alone.
- Test the settings against real questions, as the Lesson Measuring retrieval quality shows.
What goes wrong with a cut in the middle of a sentence?
A 12-word window ends with 'The bike must' and the next begins 'still have its original tyres'.
A chunk is the unit of search and reading. A bad boundary cannot be repaired by later steps.
What does overlap fix?
Fixed windows keep splitting rules from their conditions.
Overlap costs storage and repeats, so keep it modest, often 10 to 20 per cent of the chunk size.
Why keep the heading with the chunk?
One chunk says only '30 days'.
The heading tells the search and the reader what the chunk is about.
Your reading position is saved
0 of 15 complete
Lesson complete
How to chunk documents
Up next