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. Here you will learn how to split a document that is too long for one prompt into pieces the model can summarise one at a time.
Why chunking comes first
A chunk is a piece of the source text that is small enough to send to the model in one call. When a document does not fit in the context window, or fits but is long enough to degrade quality, you split it. Map-reduce and refine both start from the same list of chunks, so how you split affects every later step.
Good chunks have two properties:
- They stay under a token budget, so each call fits with room left for the instructions and the model's reply.
- They break at natural boundaries, so no sentence or idea is cut in half.
Why not split by characters?
The simplest approach is to slice the string every N characters. This is fast, but it often cuts a sentence in two. The model then sees a fragment at the end of one chunk and another fragment at the start of the next. Summaries of such chunks tend to be vague or wrong about the cut sentence.
Characters are also a poor proxy for tokens. The same number of characters can be a different number of tokens depending on language, code, numbers and punctuation. Measure the budget in tokens, using the tokenizer that matches your model.
Splitting on paragraphs
Paragraphs are a good unit for most prose. The function below adds whole paragraphs to a chunk until the next one would exceed the budget, then starts a new chunk. You supply count_tokens, a function that takes a string and returns its token count.
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 chunksYou can try it with a rough stand-in for a tokenizer. Counting words is only an approximation, so use a real tokenizer in practice.
text = "First paragraph here.\n\nSecond paragraph is a bit longer.\n\nThird one."
chunks = chunk_paragraphs(text, max_tokens=8, count_tokens=lambda s: len(s.split()))
for i, c in enumerate(chunks):
print(i, repr(c))With a budget of 8 words, the first two paragraphs (3 and 6 words) do not fit together, so you get three chunks.
Choosing the budget
The chunk budget is not the full context window. Subtract the following from the window:
- The tokens in your instruction prompt.
- The tokens you reserve for the model's output.
- A safety margin, because token counts can differ slightly between tokenizers.
Smaller chunks give more calls and more partial summaries to combine. Larger chunks give fewer calls, but each one is more exposed to the quality problems of long inputs. A budget well below the window limit is usually a sensible starting point.
Common errors
- Oversized paragraphs. The function above does not split a paragraph. If one paragraph exceeds the budget, it becomes its own oversized chunk. Add a fallback that splits such paragraphs by sentence, and check that no chunk exceeds the limit before you send it.
- Documents without blank lines. Text extracted from PDFs often has single newlines or none at all, so
split('\n\n')returns one huge paragraph. Inspect the extracted text and normalise it first. - Lost structure. Headings and lists carry meaning. If your source has headings, split on them first and then pack the paragraphs inside each section.
- Wrong token counter. Counting with one tokenizer and sending to a model that uses another can push a chunk over the limit.
Overlap
Some pipelines repeat the last paragraph of one chunk at the start of the next, so context is not lost at the boundary. This helps when ideas span paragraphs, but it increases token use and can make the same fact appear twice in the partial summaries. For summarisation, splitting at natural boundaries is often enough, and overlap is optional.
Exercise
A document contains one paragraph of 5,000 tokens, and your chunk budget is 3,000 tokens. What does chunk_paragraphs return for that paragraph, and how would you fix it?
Show answer
It returns the paragraph as its own chunk of 5,000 tokens, which exceeds the budget. To fix it, add a step that splits any paragraph over the budget into sentences and packs those sentences into chunks the same way, then verify that every chunk is within the limit.
Exercise
Why should the chunk budget be smaller than the model's context window?
Show answer
The window must also hold the instruction prompt and the model's output, and token counts can differ slightly between tokenizers, so a margin is needed.