Sub topic 7
Splitting a document into chunks
This chapter assumes you can write basic Python, have sent prompts to an LLM through an API, and know that models read text as tokens. It covers how to split a document that does not fit in one prompt, so that each piece can be summarised on its own. The next chapters use these chunks for map-reduce and refine.
Why chunking is needed
A model can only read as many tokens as its context window allows. That limit covers your instructions, the document, and the space reserved for the answer. When a document is larger than the budget you can spend, you have to cut it into pieces and summarise them separately.
A chunk is one piece of the document that you send in a single call. Good chunks have three properties:
- Size: each chunk, plus your prompt and the expected output, fits in the context window.
- Coherence: each chunk covers a complete unit of thought, so the model is not asked to summarise half a sentence.
- Order: chunks keep their position in the document, so later steps can combine them in the right sequence.
Cutting at arbitrary positions breaks the second property. A sentence that starts in one chunk and ends in the next is summarised badly in both.
Measure size in tokens, not characters
Context windows are measured in tokens, so your budget should be too. Characters and words are only rough proxies. A common rule of thumb for English is about four characters per token, but code, numbers, and non-English text often use more tokens per character.
Use the tokenizer that matches your model. Some providers offer a token-counting endpoint. For OpenAI models, the tiktoken library counts locally. The chunking functions in this chapter take a count_tokens function as an argument, so you can plug in whichever counter you use.
import tiktoken
_enc = tiktoken.get_encoding("cl100k_base")
def count_tokens(text):
return len(_enc.encode(text))If you cannot get an exact counter, use a conservative estimate such as len(text) // 3 and leave a larger safety margin. Underestimating tokens causes errors or silent truncation. Overestimating only costs a few extra calls.
Choose a chunk budget
The chunk budget is the maximum number of tokens in one chunk. It is smaller than the context window, because the window also holds the prompt and the output.
A simple calculation:
context_window = 8000 # model limit, in tokens
prompt_overhead = 300 # instructions and formatting
output_reserve = 700 # room for the summary
max_tokens = context_window - prompt_overhead - output_reserve
print(max_tokens)This prints 7000. In practice many people choose a budget well below that limit, such as 2,000 to 4,000 tokens, even when the window is much larger. Smaller chunks produce more focused summaries and avoid the quality loss described in the previous chapter on long inputs. The cost is more calls.
Split along natural boundaries
Prefer boundaries that the author already put there. In rough order of preference:
- Sections: headings, chapters, or numbered clauses.
- Paragraphs: blocks separated by blank lines.
- Sentences: the end of a sentence.
- Fixed token or character counts: a last resort, for text with no structure.
Work from the largest unit down. Try to keep whole sections together. If a section is too big, split it by paragraph. If a paragraph is too big, split it by sentence.
Paragraph-based chunking
The function below groups whole paragraphs into chunks that stay under a token budget.
def chunk_paragraphs(text, max_tokens, count_tokens):
chunks, current, size = [], [], 0
for para in text.split('\n\n'):
n = count_tokens(para)
if current and size + n > max_tokens:
chunks.append('\n\n'.join(current))
current, size = [], 0
current.append(para)
size += n
if current:
chunks.append('\n\n'.join(current))
return chunksIt works like this:
- Split the text on blank lines to get paragraphs.
- Count the tokens in each paragraph.
- If adding the paragraph would push the current chunk over the budget, save the current chunk and start a new one.
- Add the paragraph to the current chunk.
- After the loop, save whatever is left.
The check current and ... prevents saving an empty chunk when the very first paragraph is large.
A worked example
This example uses a word count as a stand-in tokenizer so it runs without any library.
def count_tokens(text):
return len(text.split())
def chunk_paragraphs(text, max_tokens, count_tokens):
chunks, current, size = [], [], 0
for para in text.split('\n\n'):
n = count_tokens(para)
if current and size + n > max_tokens:
chunks.append('\n\n'.join(current))
current, size = [], 0
current.append(para)
size += n
if current:
chunks.append('\n\n'.join(current))
return chunks
doc = "\n\n".join([
"one two three four five",
"six seven eight",
"nine ten eleven twelve",
"thirteen fourteen",
])
for i, c in enumerate(chunk_paragraphs(doc, 8, count_tokens)):
print(i, count_tokens(c), repr(c))With a budget of 8 words, the first two paragraphs (5 + 3 = 8) fit together. The third paragraph would make 12, so it starts a new chunk with the fourth (4 + 2 = 6). The output is two chunks.
Edge cases
A paragraph larger than the budget
The function above does not split a paragraph. If one paragraph exceeds max_tokens, it becomes its own oversized chunk. That chunk may overflow the window. Handle this case explicitly.
A common fix is to split oversized paragraphs into sentences and then group the sentences with the same logic:
import re
def split_sentences(text):
parts = re.split(r'(?<=[.!?])\s+', text)
return [p for p in parts if p]
def chunk_units(units, max_tokens, count_tokens, sep):
chunks, current, size = [], [], 0
for unit in units:
n = count_tokens(unit)
if current and size + n > max_tokens:
chunks.append(sep.join(current))
current, size = [], 0
current.append(unit)
size += n
if current:
chunks.append(sep.join(current))
return chunks
def chunk_text(text, max_tokens, count_tokens):
units = []
for para in text.split('\n\n'):
if count_tokens(para) <= max_tokens:
units.append(para)
else:
units.extend(chunk_units(split_sentences(para), max_tokens, count_tokens, ' '))
return chunk_units(units, max_tokens, count_tokens, '\n\n')The regular expression splits after ., !, or ? followed by whitespace. It will mis-split abbreviations such as "Dr. Smith". For production work, use a sentence splitter from a library such as nltk or spaCy. A single sentence longer than the budget (for example, a long table row or a line of minified code) still becomes an oversized chunk. As a last resort, cut it by token count.
Text with no blank lines
Some sources, such as transcripts or text extracted from PDFs, use single newlines or none at all. Splitting on '\n\n' then returns one huge paragraph. Check the number of paragraphs before trusting the result, and fall back to sentence splitting.
Tables, code, and lists
Splitting a table in the middle separates rows from their header. Splitting a code block can separate a function from its imports. Treat these as single units where possible, or repeat the table header at the top of each chunk that contains rows from it.
Empty and whitespace-only chunks
Text extracted from PDFs often contains many blank paragraphs. An empty paragraph counts as zero tokens and can produce a chunk that is only whitespace. Filter out paragraphs where para.strip() is empty before chunking.
Overlap
Overlap means repeating the end of one chunk at the start of the next. It helps when a point depends on the sentence just before it, such as a pronoun that refers to something in the previous paragraph.
Overlap has costs. You pay for the repeated tokens, and the same fact can show up in two partial summaries, which makes the combined result repetitive. For summarisation, chunks cut at paragraph or section boundaries often need no overlap. Use a small overlap, such as one paragraph or about 10% of the chunk, only when you cut at less natural points or see missing context in the output.
Choosing a chunk size
| Chunk size | Benefits | Drawbacks |
|---|---|---|
| Small (about 500 to 1,500 tokens) | Focused partial summaries, low risk of overflow | Many calls, partial summaries may lose the bigger picture |
| Medium (about 2,000 to 4,000 tokens) | Good balance for most documents | Needs checks for oversized paragraphs |
| Large (near the context limit) | Fewest calls | Quality drops on long inputs, higher risk of overflow |
There is no universal best value. Start in the medium range, read a few partial summaries, and adjust.
How chunking fits into the pipeline
Verify your chunks
Add a few checks before you send chunks to the model:
- Every chunk is at or below the budget. If one is not, log it and split it further.
- Joining the chunks returns all of the original text, apart from the separators and any whitespace you deliberately removed. A quick test is to compare word counts before and after.
- The number of chunks is reasonable. A 50-page report producing 400 chunks suggests the budget is too small or the splitting is wrong.
def check_chunks(chunks, max_tokens, count_tokens):
for i, c in enumerate(chunks):
n = count_tokens(c)
if n > max_tokens:
print(f"chunk {i} is oversized: {n} tokens")
return all(count_tokens(c) <= max_tokens for c in chunks)Common mistakes
- Counting words instead of tokens. Word counts can be off by 30% or more, and by more on code and non-English text.
- Forgetting the prompt and output. The chunk budget must leave room for both.
- Splitting mid-sentence. Fixed-size character splits do this by design.
- Ignoring document structure. Headings are free information about where topics change.
- Losing order. Summaries of chunks make sense only when combined in the original sequence.
Exercise
A model has a 16,000-token context window. Your prompt template uses 400 tokens and you want to reserve 1,000 tokens for the output. What is the largest chunk budget that fits? Why might you still choose a much smaller one, and what does a paragraph longer than your budget do to chunk_paragraphs?
Show answer
16,000 - 400 - 1,000 = 14,600 tokens is the maximum. You might choose a smaller budget, such as 2,000 to 4,000 tokens, because quality tends to fall on long inputs and smaller chunks give more focused partial summaries, at the price of more calls. A paragraph longer than the budget is not split. It becomes its own oversized chunk, which could exceed the window, so you need to split such paragraphs by sentence first.
Exercise
Using the word-count count_tokens from the worked example, what chunks does chunk_paragraphs return for the paragraphs "a b c" (3 words), "d e f g" (4 words), and "h i" (2 words) with max_tokens of 6?
Show answer
Two chunks. The first paragraph (3) and the second (4) would total 7, which is over 6, so the first paragraph is saved alone. The second (4) and third (2) total 6, which is not over 6, so they stay together. The result is "a b c" and "d e f g\n\nh i".