Sub topic 2
Fixed-Size Chunking with Overlap
Assume you know basic Python, embeddings, vector similarity search, RAG, and tokens. This chapter compares practical ways to split source documents before embedding them.
Fixed-Size Chunking with Overlap
Fixed-size chunking divides text into groups containing a fixed number of words or tokens. Overlap repeats the last part of one chunk at the start of the next. This reduces the chance that a useful sentence is separated from its context.
def chunk_words(text, size=200, overlap=40):
if overlap >= size:
raise ValueError("overlap must be smaller than size")
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunksLarger chunks preserve more context but may retrieve irrelevant text. Smaller chunks improve precision but can lose meaning. Overlap improves recall while increasing storage and embedding cost.
Recursive Splitting on Natural Separators
Recursive splitting tries paragraph breaks first, then line breaks, sentence endings, and spaces. It keeps natural boundaries when possible and falls back to finer boundaries only when a piece is too large.
def recursive_split(text, max_chars=500):
if len(text) <= max_chars:
return [text]
for separator in ("\n\n", "\n", ". ", " "):
if separator not in text:
continue
parts, current = [], ""
for part in text.split(separator):
candidate = part if not current else current + separator + part
if len(candidate) <= max_chars:
current = candidate
else:
if current:
parts.append(current)
current = part
if current:
parts.append(current)
return parts
return [text[i:i + max_chars] for i in range(0, len(text), max_chars)]Sentence-Based Chunking
Sentence-based chunking groups complete sentences until a token or character limit is reached. It avoids cutting sentences in half, but sentence detection can fail with abbreviations, lists, or unusual punctuation.
Respecting Document Structure
Structure-aware chunking uses headings, HTML elements, code blocks, and table boundaries. Store the heading path as metadata so a retrieved chunk remains understandable.
Keep code blocks intact when possible. Keep tables with their headers. A parser should recognize fenced code blocks before treating lines beginning with # as headings.
Exercise
When should you prefer recursive splitting over fixed-size splitting?
Show answer
Prefer it when preserving paragraph, sentence, or line boundaries is more important than producing identical chunk sizes.