Sub topic 5
Splitting Documents into Chunks
This chapter assumes you know basic Python, how embeddings represent text as vectors, and what a RAG pipeline does at a high level. You have already loaded and cleaned your documents. Now you split them into the units that the rest of the pipeline will embed, index, and retrieve.
Why chunking exists
A RAG system retrieves passages, not whole documents. Chunking decides what a "passage" is. Three constraints push you to split documents:
- Embedding model limits. Each model accepts a maximum number of tokens. Text beyond that limit is truncated, so the end of a long document would never be represented.
- Retrieval precision. One vector for a 40-page manual blurs many topics into one point. A query about a single setting matches it weakly.
- Prompt budget. Retrieved text goes into the model's context window. Smaller, focused chunks let you fit several relevant passages and little else.
Splitting too small has its own cost. A chunk that says "It must be renewed every 90 days" has lost the noun that "It" refers to. Chunk size is a trade-off between precision and context.
| Chunk size | Retrieval precision | Self-contained meaning | Index size |
|---|---|---|---|
| Small (100-200 tokens) | High | Often lost | Large |
| Medium (200-500 tokens) | Balanced | Usually kept | Moderate |
| Large (800+ tokens) | Diluted | Kept | Small |
These ranges are starting points. The right value depends on your documents and your embedding model, and you should confirm it with the evaluation methods in a later chapter.
Fixed-size chunking with overlap
The simplest strategy cuts text into windows of a fixed length. A hard cut can land in the middle of a sentence, so consecutive windows share an overlap. A sentence cut at one boundary then appears whole in the 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 chunksThe window advances by step = size - overlap characters. With size=500 and overlap=50, chunk 1 covers characters 0 to 499 and chunk 2 covers 450 to 949. The check on overlap matters. If overlap equaled size, step would be zero and range would raise an error. A negative step would produce no chunks at all.
The early break prevents a final chunk made only of text that the previous chunk already contained. Without it, a 500-character text would yield the full chunk plus a redundant 50-character tail.
Try it:
text = "word " * 400 # 2000 characters
pieces = chunk_text(text, size=500, overlap=50)
print(len(pieces))
print([len(p) for p in pieces])This prints 5 and then [500, 500, 500, 500, 200]. The windows start at 0, 450, 900, 1350, and 1800. The last one holds the remaining 200 characters.
Characters versus tokens
The function counts characters because that needs no library. Embedding models count tokens, and the ratio varies by language and content. English prose averages roughly four characters per token, but code, numbers, and non-Latin scripts often produce more tokens per character. If a limit is 512 tokens, 500 characters is safe for English but can overflow for dense text. For a hard guarantee, count with the tokenizer that belongs to your embedding model and size chunks in tokens.
Structure-aware chunking
Fixed windows ignore the document's shape. Documents already contain boundaries that authors chose: headings, paragraphs, list items, code blocks, table rows. Splitting on those boundaries keeps ideas together.
A common approach is recursive splitting. You try the largest separator first, then fall back to smaller ones only for pieces that are still too long.
- Split on section headings.
- If a section exceeds the size limit, split it on blank lines (paragraphs).
- If a paragraph is still too long, split on sentence endings.
- As a last resort, split on a fixed character count.
Small pieces are then merged back together until they approach the size limit, so you do not end up with many tiny chunks.
Structure-aware splitting needs structure to exist. It works well on Markdown, HTML, and well-formatted reports. It works poorly on text extracted from PDFs, where line breaks may reflect page layout and not meaning. Check your cleaning step first.
Special content
- Code. Split on function or class boundaries. A function cut in half is rarely useful to retrieve.
- Tables. Keep a header row with the rows it describes. Rows without headers are just numbers.
- Lists. Keep a list introduction ("The following steps are required:") with its items.
Metadata and context for each chunk
A chunk should carry information about where it came from. Store at least the source document, its position, and the nearest heading.
def chunk_with_metadata(doc_id, title, text, size=500, overlap=50):
records = []
for i, piece in enumerate(chunk_text(text, size, overlap)):
records.append({
"id": f"{doc_id}-{i}",
"doc_id": doc_id,
"title": title,
"position": i,
"text": piece,
})
return recordsThis metadata supports three later needs: citations in the answer, filtering at retrieval time (for example, by document or date), and deleting or re-indexing all chunks of a document that changed. A deterministic id built from the document and position lets you replace chunks on update instead of duplicating them.
You can also prepend context to the text that gets embedded, such as "Title: Refund policy\n" before the chunk body. The vector then reflects the topic even when the chunk itself never names it. This often helps for chunks like "It must be renewed every 90 days".
Choosing parameters
There is no universal setting. Use this procedure:
- Start with structure-aware splitting at around 300 tokens and 10 to 15 percent overlap.
- Build a small set of real questions with known relevant passages.
- Change one parameter at a time and measure retrieval quality.
- Keep the setting that retrieves the right passages most often.
Overlap has costs. At 10 percent it adds about 10 percent more chunks to embed and store. It also makes near-duplicate chunks likely to appear together in the top results, which wastes prompt space. Deduplicate or diversify results if you see this.
Common errors
- Chunks longer than the model limit. The embedding is computed from truncated text and the tail is silently lost. Measure in tokens.
- Splitting before cleaning. Headers, footers, and page numbers repeated on every page end up inside chunks and pollute embeddings.
- Overlap too large. With
overlapclose tosize, almost every chunk repeats the previous one. - Empty or tiny chunks. Filter out chunks that are whitespace or only a few words.
- No metadata. Without it you cannot cite, filter, or update cleanly.
- Changing chunking without re-embedding. Chunk boundaries define what each vector represents. If you change settings, rebuild the whole index.
Exercise
You call chunk_text on a 1,200-character string with size=400 and overlap=100. At which character positions does each chunk start, and how many chunks are produced?
Show answer
The step is 400 - 100 = 300, so starts are 0, 300, 600, and 900. The chunk at 0 covers 0 to 399, at 300 covers 300 to 699, at 600 covers 600 to 999, and at 900 covers 900 to 1199 (300 characters). Because 900 + 400 >= 1200, the loop breaks after that chunk. Four chunks are produced.
Exercise
A team splits a PDF-extracted report into 200-character windows. Retrieval often returns chunks that start mid-sentence and answers miss key details. Name two changes you would try and explain why each helps.
Show answer
First, switch to structure-aware or sentence-based splitting with a larger size (for example 300 tokens), so chunks end at natural boundaries and hold enough context to be understood alone. Second, add overlap and prepend the section title to each chunk before embedding, so ideas cut at a boundary still appear whole in a neighbor and each vector reflects its topic. Cleaning out repeated headers and page numbers first also helps.