05.6 Chunking Strategies
A retrieval system can only return what it can find, and it can only find what was cut into pieces small enough to embed, match and fit in a prompt. Chunking — the step that decides where those pieces begin and end — is the single highest-leverage decision in a RAG pipeline: the same documents, embedded with the same model, can produce a system that answers accurately or one that confidently misses the mark, purely because of how the text was split. This lesson covers why chunking exists, the units and sizes that matter, every major splitting strategy with working code, the boundary rules that separate a good chunker from a naive one, how to represent chunks for embedding and citation, how to choose a strategy for your corpus, and how to measure whether your chunking is actually helping — all with code you can run on your own documents with no API keys.
What you'll learn
- Why documents must be chunked: embedding input limits, retrieval granularity, context-window cost, and the precision–context trade-off at the heart of every chunking decision
- Characters vs words vs tokens: which unit to measure in, how to count tokens for your embedding model, and why "4 characters per token" is a rule of thumb, not a law
- Chunk overlap: what it fixes, what it costs, and how to choose it
- Every major strategy, each with full pure-Python code you can run: fixed-size, sentence-based, paragraph-based, recursive splitting, structure-aware (Markdown/HTML/Office), semantic chunking, LLM-based chunking, sliding windows, and token-aware splitting, plus the chunkers that ship with Docling and Unstructured and when to prefer them
- Boundary rules: never split mid-sentence, code fence, table or list item; keep headings, captions and list introductions with their content; enforce minimum and maximum sizes
- Chunk representation: the text you embed vs the text you show vs the text the LLM sees; breadcrumbs; deterministic chunk IDs; the
Chunkdata model - How to choose: a decision table by document type and query type, what the published evidence actually says (and doesn't), and how to evaluate chunking on your own data with a small retrieval harness
- Chunk-size experiments: sweeping size and overlap against recall@k, reading noisy results, and costing a re-chunk
- Anti-patterns and a failure gallery of the ways chunking goes wrong in production
What you don't need
- API keys, embedding models or a vector database. Every runnable sample in this lesson is pure Python standard library. Library equivalents (LangChain, LlamaIndex, Haystack, tiktoken) are shown for when you adopt them — their outputs are marked illustrative.
- How embeddings or vector search work. Lesson 02.3 covers embeddings; Module 06 covers vector stores and BM25; Module 07 covers the retrieval pipeline this feeds.
Setup
The runnable code needs only Python 3.11+ and the standard library. If you don't have a project yet:
uv init chunking --bare --python 3.13 && cd chunking(Or follow the fuller setup in lesson 03.1.) Save each code block as a .py file; the corpus block (4.0) defines the shared toy documents the later blocks import. For the library snippets in Part 3 you would add:
uv add langchain-text-splitters llama-index-core tiktoken
# optional, for the sentence-splitter comparison:
# uv add nltk pysbd "wtpsplit[onnx-cpu]" spacyThe library snippets were checked against langchain-text-splitters 1.1.3, llama-index-core 0.14.25 and tiktoken 0.14.0 as of November 2026. A newer major version may change class names, defaults or token counts, so check the library's changelog if a snippet does not match. No keys are needed anywhere in this lesson.
What you must be able to do after this lesson#
- Explain why documents are chunked and the size trade-off
- Count chunk size in tokens for your embedding model
- Write fixed-size, sentence, recursive and structure-aware chunkers
- Apply boundary rules so chunks never split mid-sentence or code
- Compare chunk sizes against recall at k
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Why can't we just embed whole documents?" | 1.1 The three walls |
| "The answer was in the doc but the bot missed it." | 1.2 The fundamental tension and Part 7 |
| "What chunk size should we use?" | 2.4 Size: starting points, not laws and Part 8 |
| "Should we overlap the chunks?" | Part 3: Overlap |
| "Recursive character splitting is the default — why?" | 4.4 Recursive splitting |
| "Can an LLM decide where to split?" | 4.7 LLM-based chunking |
| "Semantic chunking is state of the art." | 4.6 Semantic chunking and the evidence in 7.3 |
| "The chunk lost its section heading." | 5.1 Never split context from content |
| "How do we cite the source of an answer?" | Part 6: Chunk representation |
| "Changing the chunker means re-embedding everything?" | 8.3 The cost of re-chunking and 05.9 |
Part 1: Why chunk at all#
1.1 The three walls#
Chunking exists because three independent limits push in the same direction — smaller pieces:
- The embedding model's input limit. Embedding models have a maximum input length in tokens, and over-long input is truncated — often silently.
all-MiniLM-L6-v2reads 256 tokens; OpenAI'stext-embedding-3-*models accept 8,192; Gemini'sgemini-embedding-001accepts 2,048 andgemini-embedding-28,192; Voyage's current models accept around 32,000 (all as of November 2026 — lesson 02.3, 5.7 has the full table and the demo of silent truncation; Module 06 goes deeper on model choice). A 40-page contract fed whole would be silently cut to its first few thousand tokens: everything after the cut is invisible to search forever. - The dilution problem. Even when a model can embed a long document, one vector must average every topic in it. A vector that is "30% warranty, 30% shipping, 40% pricing" sits near the middle of all three topics and matches none of them precisely. Lesson 02.3, 10.6 shows embeddings preserve gist but lose detail — negation, numbers, exact IDs — and a long multi-topic text loses even the gist. Chunking gives each topic its own vector.
- The retrieval and prompt budget. Retrieval returns the top-k chunks for a query. If chunks are huge, the top-3 results may be 15,000 tokens of mostly-irrelevant text — expensive to embed-match downstream, expensive to put in the prompt (lesson 02.7 covers what context costs), and it buries the answer under distractors (lost in the middle).
There is a fourth, softer reason: granularity of citation and debugging. When the model answers "within 30 days for unopened products", you want to point at the exact chunk that said it, log it, and check it. A whole-document index gives you "somewhere in the 80-page handbook".
1.2 The fundamental tension#
Every chunking decision trades two failure modes against each other:
| Chunk too small | Chunk too large |
|---|---|
| Precise match, but the chunk lacks context: "The company's revenue grew by 3%" doesn't say which company or which quarter (this is Anthropic's own example in their Contextual Retrieval post, September 2024) | Full context, but the embedding averages many topics and the match is diluted; the prompt pays for irrelevant text |
| A pronoun or reference ("it", "the above clause", "this model") points at content in a different chunk | One bad boundary can separate a table from its header or a question from its answer |
| Expensive: more chunks → more embeddings → more storage, and more near-duplicate results crowding the top-k | Cheap per chunk, but each retrieval returns a wall of text the model must wade through |
A good chunk is self-contained (it makes sense alone), coherent (one topic or one structural unit), and answerable (a realistic question's evidence fits inside it). Everything in this lesson is in service of that definition.
flowchart LR
subgraph ingest ["This module (05)"]
P["Parse → clean"] --> C["CHUNK<br/>this lesson"]
C --> E["Enrich: metadata,<br/>breadcrumbs, IDs"]
end
subgraph serve ["Module 06 / 07"]
E --> V["Embed + index"]
V --> R["Retrieve top-k"]
R --> G["Generate answer"]
end
Q["User query"] --> R1.3 Where chunking sits#
Chunking is one stage in the ingestion pipeline (05.1 maps the whole thing). It runs after parsing and cleaning — you want to split clean text, not noise — and before embedding, because the embedder's input limit and the chunk's coherence both depend on the split. The output of this lesson is a list of Chunk records (Part 6) that 05.8 enriches and 05.9 stores incrementally.
Part 2: Units, sizes and overlap#
2.1 Characters, words, tokens#
Chunkers measure size in one of three units, and the choice matters:
| Unit | What it is | Pros | Cons |
|---|---|---|---|
Characters (len) |
Raw text length | Free, instant, language-agnostic | Says nothing about meaning; "400 chars" is ~100 words of English but ~50 of German or ~15 of Japanese |
Words (split()) |
Whitespace-separated tokens | Cheap, roughly tracks meaning | Breaks on CJK (no spaces), hyphenated words, code; still not what models count |
| Tokens | The embedder's actual unit | Matches the model's real limit and cost | Requires the right tokenizer; slightly slower |
The unit that matters is the one your embedding model uses, because its input limit, its cost and its "dilution" threshold are all denominated in its tokens. A chunk sized in characters for English prose can be 3× over the limit for the same text in Hindi or Vietnamese — the token tax lesson 02.2, Part 8 measures. Rule of thumb: size in tokens whenever the corpus is multilingual or the embedder has a hard limit.
2.2 Counting tokens#
Three ways, cheapest first:
- A local tokenizer.
tiktoken(uv add tiktoken) covers OpenAI's encodings (o200k_basefor current OpenAI models,cl100k_basefor older ones — 02.2, Part 5 shows the differences). For other providers' models, Hugging Face tokenizers (transformers) cover most open-weight embedder families. LlamaIndex's splitters use a tokenizer callable you supply; LangChain'sTokenTextSplitteracceptsencoding_name/model_nameorfrom_tiktoken_encoder(...)/from_huggingface_tokenizer(...). - The provider's count endpoint. OpenAI
responses.input_tokens.count, Anthropicmessages.count_tokens, Geminimodels.count_tokens— lesson 03.7, Part 2 covers all four providers and their quirks (Gemini can't count system instructions or tools; OpenRouter has no endpoint). These are for spot-checking and budgeting, not per-chunk hot paths — a network call per chunk is too slow for ingestion. - A learned ratio. Measure tokens-per-word (or per-char) on a sample of your corpus with method 1 or 2, then estimate. 03.7, 2.7 shows the pattern: English prose is ~4 chars/token on OpenAI-style tokenizers but nearer ~2.5 on Anthropic's — learn your own ratio from logs rather than trusting a constant.
2.3 Overlap belongs here too#
Overlap is the number of tokens/characters repeated at the end of one chunk and the start of the next. It exists for one reason: a sentence or table row that straddles a boundary would otherwise be severed — half its context in each chunk, retrievable by neither. Overlap is the cheapest insurance against bad luck. Its cost is real: duplicated content means duplicate embeddings, ~overlap% more storage and embedding spend, and — the subtle one — the same passage can be retrieved twice in one top-k, wasting a slot. Part 3 covers how much to use and Part 7 shows it in the sweep.
2.4 Size: starting points, not laws#
There is no universal optimum — it depends on the embedder, the document type, the query type and the evaluator. Honest anchors:
- Anthropic's RAG primer describes chunks "usually no more than a few hundred tokens" (Contextual Retrieval).
- Common practitioner ranges: ~200–500 tokens for Q&A/FAQ-style retrieval, ~500–1,000 for technical docs and narrative text. Treat these as starting points to sweep around, not targets.
- The hard ceiling is your embedder's max input (Part 2.2), minus headroom for the breadcrumb/context prefix you prepend (Part 6).
- The soft ceiling is coherence: if a "section" is 4,000 tokens of one argument, splitting it at 500 loses the argument; if a "section" is one table, splitting at all loses the table.
The only way to know your optimum is to measure it — Part 7 builds the harness.
Part 3: Overlap#
Overlap repeats the last o units of a chunk at the start of the next. Its mechanics are simple; its trade-offs are not.
What it fixes. Without overlap, a boundary lands wherever the counter says — mid-sentence, mid-table-row, mid-argument — and the evidence for a question can be split so neither side retrieves well. With overlap, the straddling text appears whole in at least one chunk. Sentence-level overlap (repeat the last sentence) is usually better than character-level overlap for the same reason the boundary rules in Part 5 exist: it repeats at a natural seam.
What it costs.
- ~
o / chunk_sizemore chunks → proportionally more embeddings, storage and ingest cost (Part 8.3 puts numbers on it). - Duplicate retrievals: the same passage can occupy two top-k slots, crowding out a second relevant chunk. Deduplicate by
chunk_idor by content hash after retrieval, or by storing overlap only in the displayed/prompt text and not in a separately-embedded unit — designs differ; pick one deliberately. - Overlap can create boundary artefacts: our recursive demo in 4.4 shows char-level overlap duplicating whole headings into the next chunk — and pushing those chunks past
max_size.
How to choose. 10–20% of chunk size is the common starting range (overlap of ~50–150 tokens on 500–1,000-token chunks). Lower it toward 0–5% when you see duplicate results dominating top-k; raise it toward 25% when answers keep landing on boundaries. Structure-aware chunking (Part 4.5) reduces the need for overlap because boundaries fall on headings and section edges rather than arbitrary offsets.
flowchart LR
A["chunk N<br/>... end of section A"] -->|"overlap: last sentence<br/>repeated at start"| B["chunk N+1<br/>end of section A + start of B"]
B --> C["chunk N+2"]Part 4: The strategies#
Each strategy below gets: the mechanism, full working code (pure stdlib — run it), pros/cons, and when to use it. They compose: production chunkers are usually "structure-aware boundaries + recursive fallback + size post-pass".
4.0 The toy corpus#
All runnable samples share one small corpus — slices of the module's running Acme document set (handbook, help centre, contract, ticket, meeting notes). Save this as corpus.py:
# corpus.py — toy corpus for lesson 05.6
HANDBOOK = """# Acme Product Handbook
## Warranty
Every Acme Drill carries a two-year warranty covering manufacturing defects.
The warranty starts on the date of purchase and requires a valid receipt.
Damage caused by misuse, freezing temperatures or unauthorised repairs is not covered.
## Returns
Customers may return an unopened product within 30 days for a full refund.
Opened products can be returned within 14 days if they are unused and in original packaging.
Refunds are issued to the original payment method within 5 business days.
"""
HELP = """# Acme Help: Shipping and delivery
## Shipping times
Standard shipping within the country takes 3 to 5 business days.
Express shipping takes 1 to 2 business days and costs a flat 12.00 per order.
International orders are shipped by courier and typically arrive in 7 to 14 days,
depending on customs processing at the destination.
## Tracking
Every order receives a tracking number by email within 24 hours of dispatch.
You can follow the parcel on the carrier's website using that number.
"""
CONTRACT = """# Vendor agreement, clause 8
## Liability
Neither party is liable for indirect or consequential damages.
The supplier's total liability under this agreement is capped at the fees
paid by the customer in the twelve months preceding the claim.
## Termination
Either party may terminate this agreement for convenience on 90 days written notice.
Either party may terminate immediately for material breach that remains uncured
for 30 days after written notice.
"""
TICKET = """Customer: Dana Whitfield
Order: AC-2026-0417
My Acme Drill arrived this morning and the housing is cracked.
The box looked fine but the drill will not turn on. I need a replacement
or a refund as soon as possible.
Agent: We are sorry for the trouble. I have issued a replacement drill
under warranty and waived the return shipping. You will receive tracking
within 24 hours.
"""
MEETING = """Transcript excerpt, product sync, 14 October 2026
Priya: The warranty extension question came up again. Legal wants 24 months
for the industrial line but support says 18 is enough.
Tom: We should decide this quarter. The returns data shows most claims
land in the first six months anyway.
Priya: Agreed. I'll put a proposal on the agenda for next week's sync.
"""4.1 Fixed-size chunking#
The baseline: cut every size units with overlap shared. Nothing smarter exists — which is exactly why it's the benchmark every other strategy must beat.
# s4_1_fixed.py
def fixed_size_chunks(text: str, size: int, overlap: int = 0) -> list[str]:
"""Cut text into pieces of at most `size` chars, `overlap` chars shared
between neighbours. Blind to sentences, words and structure."""
if not 0 <= overlap < size:
raise ValueError("overlap must be >= 0 and smaller than size")
chunks, start = [], 0
while start < len(text):
end = min(start + size, len(text))
chunks.append(text[start:end])
if end == len(text):
break
start += size - overlap
return chunks
if __name__ == "__main__":
from corpus import HANDBOOK
for c in fixed_size_chunks(HANDBOOK, size=120, overlap=0):
print(f"--- {len(c)} chars ---")
print(c)--- 120 chars ---
# Acme Product Handbook
## Warranty
Every Acme Drill carries a two-year warranty covering manufacturing defects.
The w
--- 120 chars ---
arranty starts on the date of purchase and requires a valid receipt.
Damage caused by misuse, freezing temperatures or u
--- 120 chars ---
nauthorised repairs is not covered.
## Returns
Customers may return an unopened product within 30 days for a full refu
--- 120 chars ---
nd.
Opened products can be returned within 14 days if they are unused and in original packaging.
Refunds are issued to t
--- 51 chars ---
he original payment method within 5 business days.Read that output like a reviewer: "manufacturing def | ects", "freezing temper | atures", "Refunds are | issued". Every chunk boundary is mid-word. Pros: trivial, deterministic, uniform cost. Cons: destroys every structure the document had; boundaries ignore meaning entirely. Use when: prototyping, uniform logs/metrics where structure doesn't exist, or as the control group in your own chunking eval. Never as the final answer for prose.
Token-aware variant. The same idea measured in the embedder's unit needs a count: str -> int function. Binary-search the cut so count(chunk) <= max_tokens, then rewind overlap_tokens for the next start:
# s4_1b_tokens.py — companion to s4_1_fixed.py
def token_fixed_chunks(text: str, count, max_tokens: int,
overlap_tokens: int = 0) -> list[str]:
"""Fixed-size chunking measured in tokens. `count` is any callable
str -> int (tiktoken encode length, a provider count endpoint, ...)."""
if overlap_tokens >= max_tokens:
raise ValueError("overlap must be smaller than max_tokens")
chunks, start = [], 0
while start < len(text):
lo, hi = start + 1, len(text)
while lo < hi: # largest end fitting the budget
mid = (lo + hi + 1) // 2
if count(text[start:mid]) <= max_tokens:
lo = mid
else:
hi = mid - 1
chunks.append(text[start:lo])
if lo == len(text):
break
start = _rewind(text, start, lo, count, overlap_tokens)
return chunks
def _rewind(text, start, end, count, overlap_tokens) -> int:
"""Largest offset < end whose trailing token count fits the overlap."""
if overlap_tokens == 0:
return end
lo, hi = start, end
while lo < hi:
mid = (lo + hi) // 2
if count(text[mid:end]) <= overlap_tokens:
hi = mid
else:
lo = mid + 1
return max(start, lo)
if __name__ == "__main__":
from corpus import HANDBOOK
words = lambda t: len(t.split()) # stand-in counter for the demo
for c in token_fixed_chunks(HANDBOOK, words, max_tokens=25, overlap_tokens=5):
print(f"[{words(c)} words] {c[:80]!r}...")[25 words] '# Acme Product Handbook\n\n## Warranty\n\nEvery Acme Drill carries a two-year warran'...
[25 words] ' the date of purchase and requires a valid receipt.\nDamage caused by misuse, fre'...
[25 words] ' covered.\n\n## Returns\n\nCustomers may return an unopened product within 30 days f'...
[24 words] ' returned within 14 days if they are unused and in original packaging.\nRefunds a'...Library equivalent (illustrative): LangChain's TokenTextSplitter does this with a real tokenizer — TokenTextSplitter.from_tiktoken_encoder(encoding_name="o200k_base", chunk_size=..., chunk_overlap=...) in langchain-text-splitters 1.1.x; check the current signature on the package's reference page.
4.2 Sentence-based chunking#
Split into sentences, then pack whole sentences up to the size budget. Boundaries now fall on ./!/? instead of arbitrary offsets — the single biggest quality jump over fixed-size for almost no cost.
# s4_2_sentences.py
import re
SENTENCE_RE = re.compile(r"(?<=[.!?])\s+")
def split_sentences(text: str) -> list[str]:
return [s for s in SENTENCE_RE.split(text.strip()) if s]
def pack_sentences(sentences: list[str], max_chars: int,
overlap_sentences: int = 0) -> list[str]:
"""Greedily pack whole sentences into chunks of at most max_chars.
`overlap_sentences` repeats that many trailing sentences in the next chunk."""
chunks: list[str] = []
current: list[str] = []
size = 0
def flush():
nonlocal current, size
if current:
chunks.append(" ".join(current))
# carry trailing sentences as overlap — but never more than
# max_chars of them, or the next chunk starts oversized
tail: list[str] = []
tsize = 0
for s in reversed(current[-overlap_sentences:]
if overlap_sentences else []):
add = len(s) + (1 if tail else 0)
if tsize + add > max_chars:
break
tail.insert(0, s)
tsize += add
current, size = tail, tsize
for sent in sentences:
add = len(sent) + (1 if current else 0)
if current and size + add > max_chars:
flush()
add = len(sent) + (1 if current else 0)
if current and size + add > max_chars:
current, size = [], 0 # even the overlap tail won't fit
add = len(sent)
current.append(sent)
size += add
flush()
return chunks
if __name__ == "__main__":
from corpus import TICKET
sents = split_sentences(TICKET)
print(f"{len(sents)} sentences:")
for i, s in enumerate(sents):
print(f" {i}: {s!r}")
print("\n=== packed at 140 chars, no overlap ===")
for c in pack_sentences(sents, max_chars=140):
print(f"[{len(c)} chars] {c!r}")
print("\n=== packed at 140 chars, 1-sentence overlap ===")
for c in pack_sentences(sents, max_chars=140, overlap_sentences=1):
print(f"[{len(c)} chars] {c!r}")6 sentences:
0: 'Customer: Dana Whitfield\nOrder: AC-2026-0417\n\nMy Acme Drill arrived this morning and the housing is cracked.'
1: 'The box looked fine but the drill will not turn on.'
2: 'I need a replacement\nor a refund as soon as possible.'
3: 'Agent: We are sorry for the trouble.'
4: 'I have issued a replacement drill\nunder warranty and waived the return shipping.'
5: 'You will receive tracking\nwithin 24 hours.'
=== packed at 140 chars, no overlap ===
[108 chars] 'Customer: Dana Whitfield\nOrder: AC-2026-0417\n\nMy Acme Drill arrived this morning and the housing is cracked.'
[105 chars] 'The box looked fine but the drill will not turn on. I need a replacement\nor a refund as soon as possible.'
[117 chars] 'Agent: We are sorry for the trouble. I have issued a replacement drill\nunder warranty and waived the return shipping.'
[42 chars] 'You will receive tracking\nwithin 24 hours.'
=== packed at 140 chars, 1-sentence overlap ===
[108 chars] 'Customer: Dana Whitfield\nOrder: AC-2026-0417\n\nMy Acme Drill arrived this morning and the housing is cracked.'
[105 chars] 'The box looked fine but the drill will not turn on. I need a replacement\nor a refund as soon as possible.'
[90 chars] 'I need a replacement\nor a refund as soon as possible. Agent: We are sorry for the trouble.'
[117 chars] 'Agent: We are sorry for the trouble. I have issued a replacement drill\nunder warranty and waived the return shipping.'
[123 chars] 'I have issued a replacement drill\nunder warranty and waived the return shipping. You will receive tracking\nwithin 24 hours.'Two things to notice in the real output. First, the regex glued the ticket's header lines ("Customer: Dana Whitfield\nOrder: AC-2026-0417") onto the first "sentence" — there is no ., ! or ? after them, so the heuristic can't tell where the header ends. Second, sentence-level overlap repeats a whole sentence at each boundary: "I need a replacement…" ends chunk 2 and opens chunk 3, "Agent: We are sorry…" ends chunk 3 and opens chunk 4 — the same evidence is retrievable from two chunks, at the cost of roughly one extra sentence per boundary.
Sentence splitters. The regex above is the floor. Serious options, all verified on PyPI as of November 2026:
| Splitter | Package (version) | Approach | Notes |
|---|---|---|---|
| Regex | stdlib | punctuation + whitespace | English-ish, brittle on abbreviations ("e.g.", "Mr."), decimals, CJK |
NLTK sent_tokenize |
nltk 3.10.4 |
Punkt unsupervised model | Needs nltk.download('punkt_tab') data (punkt is the pre-3.9 name — the pickled package was retired for security reasons); used inside LlamaIndex's SentenceSplitter and Haystack's "sentence" separator |
spaCy sentencizer/parser |
spacy 3.8.18 |
statistical/learned | Heavy install (models per language); overkill if you only need sentences |
| pysbd | pysbd 0.3.4 |
rule-based port of Pragmatic Segmenter | Last release 2021, English-focused — fine for simple cases, don't build new pipelines on it |
| wtpsplit (SaT) | wtpsplit 2.2.2 |
neural segmenter, 85 languages | SaT model; min_length/max_length constraints added in 2.2.0 make it usable as a chunker; ONNX extras for CPU |
LlamaIndex's SentenceSplitter (below) is the most common "sentence-based + size budget" implementation; it uses NLTK's Punkt tokenizer for sentence boundaries and a token counter for the budget.
Pros: natural boundaries, cheap, works on any text. Cons: still ignores section structure (a heading can be separated from its section); regex splitting fails on abbreviations and some languages. Use when: general prose without reliable markup — the default for plain-text corpora.
4.3 Paragraph-based chunking#
When the document has real paragraph breaks (\n\n), each paragraph is a natural semantic unit — often exactly the size you want. Split on blank lines, merge undersized paragraphs, split oversized ones.
# s4_3_paragraphs.py
import re
def paragraph_chunks(text: str, max_chars: int = 600,
min_chars: int = 80) -> list[str]:
"""One chunk per paragraph; tiny paragraphs merge forward, oversized
ones are emitted whole (hand them to the post-pass in Part 5)."""
paras = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
chunks, cur = [], ""
for p in paras:
if cur and len(cur) + len(p) + 2 > max_chars:
chunks.append(cur)
cur = p
else:
cur = f"{cur}\n\n{p}" if cur else p
if cur:
chunks.append(cur)
return [c for c in chunks if len(c) >= min_chars] or chunks
if __name__ == "__main__":
from corpus import HANDBOOK
for c in paragraph_chunks(HANDBOOK, max_chars=300, min_chars=40):
print(f"--- {len(c)} chars ---\n{c}\n")--- 287 chars ---
# Acme Product Handbook
## Warranty
Every Acme Drill carries a two-year warranty covering manufacturing defects.
The warranty starts on the date of purchase and requires a valid receipt.
Damage caused by misuse, freezing temperatures or unauthorised repairs is not covered.
## Returns
--- 241 chars ---
Customers may return an unopened product within 30 days for a full refund.
Opened products can be returned within 14 days if they are unused and in original packaging.
Refunds are issued to the original payment method within 5 business days.Read that output like a reviewer — it demonstrates this lesson's central argument better than the clean version would have. The first "chunk" is 287 chars of title, two headings and the warranty body, and it ends with the orphaned ## Returns heading, severed from the section it introduces (the Returns body landed in chunk 2). Paragraph boundaries are semantic-ish but they don't know a heading belongs to what follows — which is exactly the failure 4.5's structure-aware splitter fixes.
Pros: respects the author's own units; near-zero cost. Cons: paragraph sizes vary wildly (a one-line "Notes." or a 5,000-word wall); PDFs and HTML often lose paragraph structure in parsing (05.2/05.3); headings become orphaned just like in fixed-size. Use when: Markdown, clean text exports, transcripts with blank-line turns — and always with the structure-aware upgrade below when headings exist.
4.4 Recursive splitting: the workhorse#
Recursive character splitting is the default in every major framework for a reason: it tries a hierarchy of separators — paragraph, line, sentence-ish, word, character — and uses the coarsest one that fits the budget, recursing only into pieces still too big. Paragraphs stay whole where possible, sentences break only when needed, words only as a last resort before characters.
Here is the algorithm reimplemented in ~60 lines of stdlib, so you can see exactly what LangChain's RecursiveCharacterTextSplitter does under the hood:
# s4_4_recursive.py
def _split_keep(text: str, sep: str) -> list[str]:
"""Split on `sep`, keeping the separator at the end of each piece."""
if sep == "":
return list(text)
parts = text.split(sep)
return [p + sep for p in parts[:-1]] + ([parts[-1]] if parts[-1] else [])
def _merge(pieces: list[str], size_fn, max_size: int,
overlap: int) -> list[str]:
"""Pack pieces into chunks of at most max_size, repeating up to `overlap`
units of trailing content in the next chunk. Pieces already carry their
separators, so they are joined with "" — joining with `sep` again would
duplicate every separator (this is LangChain's keep_separator trick)."""
docs, cur, total = [], [], 0
for p in pieces:
plen = size_fn(p)
if cur and total + plen > max_size:
docs.append("".join(cur))
while cur and total > overlap:
total -= size_fn(cur[0])
cur = cur[1:]
cur.append(p)
total += plen
if cur:
docs.append("".join(cur))
return docs
def recursive_split(text: str, separators: list[str], size_fn,
max_size: int, overlap: int = 0) -> list[str]:
"""Split `text` into chunks of at most max_size (measured by size_fn).
separators is a priority list, e.g. ["\\n\\n", "\\n", ". ", " ", ""].
The first separator found in the text is used; pieces still too big are
split recursively by the remaining separators. "" means single characters.
"""
chunks: list[str] = []
def walk(t: str, seps: list[str]) -> None:
sep, rest = "", []
for i, s in enumerate(seps):
if s == "" or s in t:
sep, rest = s, seps[i + 1:]
break
pieces = _split_keep(t, sep)
good: list[str] = []
for piece in pieces:
if size_fn(piece) <= max_size:
good.append(piece)
else:
if good:
chunks.extend(_merge(good, size_fn, max_size, overlap))
good = []
if rest:
walk(piece, rest)
else:
chunks.append(piece) # cannot split further: stays oversized
if good:
chunks.extend(_merge(good, size_fn, max_size, overlap))
walk(text, separators)
return [c for c in chunks if c.strip()]
if __name__ == "__main__":
from corpus import HANDBOOK, HELP
doc = HANDBOOK + "\n\n" + HELP
seps = ["\n\n", "\n", ". ", " ", ""]
for c in recursive_split(doc, seps, len, max_size=250, overlap=50):
print(f"--- {len(c)} chars ---")
print(c)
print()--- 38 chars ---
# Acme Product Handbook
## Warranty
--- 277 chars ---
# Acme Product Handbook
## Warranty
Every Acme Drill carries a two-year warranty covering manufacturing defects.
The warranty starts on the date of purchase and requires a valid receipt.
Damage caused by misuse, freezing temperatures or unauthorised repairs is not covered.
--- 12 chars ---
## Returns
--- 255 chars ---
## Returns
Customers may return an unopened product within 30 days for a full refund.
Opened products can be returned within 14 days if they are unused and in original packaging.
Refunds are issued to the original payment method within 5 business days.
--- 56 chars ---
# Acme Help: Shipping and delivery
## Shipping times
--- 225 chars ---
Standard shipping within the country takes 3 to 5 business days.
Express shipping takes 1 to 2 business days and costs a flat 12.00 per order.
International orders are shipped by courier and typically arrive in 7 to 14 days,
--- 53 chars ---
depending on customs processing at the destination.
--- 160 chars ---
## Tracking
Every order receives a tracking number by email within 24 hours of dispatch.
You can follow the parcel on the carrier's website using that number.
Read the failure modes carefully — they are the best argument for Part 4.5:
- Orphan headings. "## Returns" became its own 12-char chunk, severed from the section it introduces — the oversized Returns body forced a flush before the heading could merge with it. ("## Tracking" got lucky: its heading and body happened to fit inside one piece.)
- Overlap duplicated the headings. With
overlap=50, chunks 2 and 4 open by repeating the "# Acme Product Handbook › ## Warranty" prefix and "## Returns" that chunks 1 and 3 already contained — and both grew pastmax_size(277 > 250, 255 > 250), because retained overlap is added on top of the budget. That is overlap's real cost made visible: duplicated embeddings, and occasionally an oversized chunk — LangChain logs a warning for exactly this case. - Verbatim substrings. Every chunk is an exact substring of the source: separators stay inside their pieces instead of being re-inserted at join time. That property is what lets 8.1 locate each chunk's span in the document when it builds the gold labels — corrupt the text and the spans can't be found.
Pros: the best general-purpose default; respects paragraph > line > word hierarchy; deterministic; cheap. Cons: still blind to semantic structure — it doesn't know "## Warranty" introduces a section; it splits on characters, not meaning. Use when: the default for unstructured prose; always pair with the post-pass (Part 5) and, when headings/markup exist, the structure-aware layer (4.5).
Library equivalents (all langchain-text-splitters 1.1.3, import from langchain_text_splitters import ...):
# illustrative — library API, not run here
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
separators=["\n\n", "\n", ". ", " ", ""], # default is ["\n\n", "\n", " ", ""]
chunk_size=1000, # measured by length_function (default len = chars)
chunk_overlap=200,
length_function=len, # or a token counter
keep_separator=True,
)
chunks = splitter.split_text(document_text)LlamaIndex's equivalents (llama-index-core 0.14.25, from llama_index.core.node_parser import ...): SentenceSplitter(chunk_size=1024, chunk_overlap=200) — the recommended default, sentence-aware with a token budget and NLTK Punkt boundaries; TokenTextSplitter(chunk_size=1024, chunk_overlap=20, separator=" ") — word-token packing; RecursiveCharacterTextSplitter-style splitting is what SentenceSplitter approximates with better sentence handling. Haystack's RecursiveDocumentSplitter (haystack-ai 3.4.1) takes split_unit="word"|"char"|"token", a regex separators list, and a "sentence" separator backed by an NLTK tokenizer — it also stamps page_number metadata from form feeds, handy for PDFs.
4.5 Structure-aware chunking#
When the document has structure — Markdown headings, HTML header tags, docx styles, a PDF outline — use it. Boundaries fall on the author's own section edges, headings travel with their content, and you get breadcrumbs for free.
The pattern: parse the structure into (heading_path, body) sections, emit one chunk per section, hard-split only oversized sections, and prepend the heading path to the embedded text (Part 6 covers why).
# s4_5_markdown.py
import re
HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)$")
FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})")
def markdown_chunks(text: str, max_chars: int = 600) -> list[dict]:
"""Split on heading boundaries. A chunk never starts mid-section: each
chunk carries the heading path of the section it came from. Fenced code
blocks are tracked so a '#'-style line inside them stays body text."""
lines = text.split("\n")
sections: list[tuple[list[str], str]] = []
path: list[str] = []
body: list[str] = []
in_fence = False
def flush():
nonlocal body
if body:
sections.append((list(path), "\n".join(body).strip()))
body = []
for line in lines:
if FENCE_RE.match(line):
in_fence = not in_fence
body.append(line)
continue
m = None if in_fence else HEADING_RE.match(line)
if m:
flush()
level, title = len(m.group(1)), m.group(2).strip()
path = path[: level - 1] + [title]
body = []
else:
body.append(line)
flush()
chunks: list[dict] = []
for section_path, body_text in sections:
crumb = " > ".join(section_path)
if len(body_text) <= max_chars:
chunks.append({"text": body_text, "section": crumb,
"section_path": section_path})
continue
parts, cur, size = [], [], 0
for para in body_text.split("\n\n"):
if cur and size + len(para) + 2 > max_chars:
parts.append("\n\n".join(cur))
cur, size = [para], len(para)
else:
cur.append(para)
size += len(para) + 2
if cur:
parts.append("\n\n".join(cur))
for p in parts:
chunks.append({"text": p.strip(), "section": crumb,
"section_path": section_path})
return [c for c in chunks if c["text"]]
if __name__ == "__main__":
from corpus import HANDBOOK, HELP, CONTRACT
doc = HANDBOOK + "\n\n" + HELP + "\n\n" + CONTRACT
for i, c in enumerate(markdown_chunks(doc, max_chars=400)):
print(f"=== chunk {i} | section: {c['section']} ({len(c['text'])} chars) ===")
print(c["text"][:200].replace("\n", " / "))
print()=== chunk 0 | section: Acme Product Handbook > Warranty (237 chars) ===
Every Acme Drill carries a two-year warranty covering manufacturing defects. / The warranty starts on the date of purchase and requires a valid receipt. / Damage caused by misuse, freezing temperatures or
=== chunk 1 | section: Acme Product Handbook > Returns (241 chars) ===
Customers may return an unopened product within 30 days for a full refund. / Opened products can be returned within 14 days if they are unused and in original packaging. / Refunds are issued to the origin
=== chunk 2 | section: Acme Help: Shipping and delivery > Shipping times (276 chars) ===
Standard shipping within the country takes 3 to 5 business days. / Express shipping takes 1 to 2 business days and costs a flat 12.00 per order. / International orders are shipped by courier and typically
=== chunk 3 | section: Acme Help: Shipping and delivery > Tracking (146 chars) ===
Every order receives a tracking number by email within 24 hours of dispatch. / You can follow the parcel on the carrier's website using that number.
=== chunk 4 | section: Vendor agreement, clause 8 > Liability (199 chars) ===
Neither party is liable for indirect or consequential damages. / The supplier's total liability under this agreement is capped at the fees / paid by the customer in the twelve months preceding the claim.
=== chunk 5 | section: Vendor agreement, clause 8 > Termination (198 chars) ===
Either party may terminate this agreement for convenience on 90 days written notice. / Either party may terminate immediately for material breach that remains uncured / for 30 days after written notice.Every failure mode from 4.4 is gone: no orphan headings, no duplicated heading, sections are self-describing. Compare with the recursive output on the same text — this is what "structure-aware" buys. One boundary rule is built in: fenced code blocks are tracked while scanning, so a #-style comment line inside a triple-backtick fence stays body text instead of becoming a bogus heading — documentation full of code examples would otherwise shatter into fake sections.
The same idea in other formats — the ParsedDocument model from 05.2 and 05.3 is built for exactly this: its heading tree, section IDs and page/bbox provenance become chunk boundaries and metadata:
| Source structure | Boundary signal | Library equivalent |
|---|---|---|
| Markdown | #–###### heading lines, code fences |
LangChain MarkdownHeaderTextSplitter / MarkdownTextSplitter (headers→metadata) |
| HTML | h1–h6, section, article tags |
LangChain HTMLSectionSplitter / HTMLHeaderTextSplitter (BeautifulSoup + lxml) |
| docx | paragraph styles Heading 1–3 | your 05.3 parser emits the section tree; chunk per style-run |
| outline/bookmarks, font-size heading heuristics | the section tree from 05.2's ParsedDocument |
|
| Code | AST function/class boundaries | preview of 05.7 — tree-sitter/ast splitters |
Pros: best boundary quality per unit of effort; breadcrumbs nearly free; deterministic. Cons: only as good as the parser's structure recovery (a PDF with no outline falls back to 4.4); very large sections still need a size fallback. Use when: any document with real structure — Markdown docs, HTML pages, styled Office files, outlined PDFs. This is the recommended default for the module's running corpus.
4.5.1 Chunkers that read parsed structure: Docling and Unstructured#
If your parser already produced a typed document tree (05.2 and 05.3), the cheapest structure-aware chunker is the one that ships with that parser, because it reads elements (headings, paragraphs, list items, tables) instead of re-guessing them from flattened text. Two matter in practice. Everything below was read from the projects' documentation in November 2026 and is illustrative: this lesson did not run the libraries.
Docling (HierarchicalChunker, HybridChunker) |
Unstructured (basic, by_title) |
|
|---|---|---|
| Input | A DoclingDocument from DocumentConverter().convert(...).document |
A list of elements from partition(...) |
| Boundary rule | Hierarchical: one chunk per document element (list items merged by default), with headings and captions attached as metadata. Hybrid: starts from that, splits chunks that exceed a token limit measured with a tokenizer you supply, then merges undersized neighbours that share the same headings (merge_peers, default on) |
basic packs consecutive elements up to a size limit and isolates tables; by_title additionally starts a new chunk at every Title element and never spans two sections |
| Size unit | Tokens (the hybrid chunker takes the tokenizer, so it can match your embedder, see 2.2) | Characters (max_characters default 500, soft limit new_after_n_chars, combine_text_under_n_chars merges small sections, overlap applies to oversized elements unless overlap_all is set) |
| Tables | Split by rows; the table header is repeated in each piece (repeat_table_header, default on) |
Tables are always isolated; oversized ones become TableChunks |
| Provenance | Chunk metadata links back to the document items (headings, items with page and box information) | Each chunk keeps the elements it came from in .metadata.orig_elements |
# s4_5b_docling_unstructured_chunking.py — illustrative; needs docling and unstructured installed (05.2 / 05.3 Setup)
from docling.chunking import HybridChunker
from docling.document_converter import DocumentConverter
from unstructured.chunking.title import chunk_by_title
from unstructured.partition.auto import partition
# --- Docling: convert once, then chunk the DoclingDocument ---
doc = DocumentConverter().convert("data/handbook.pdf").document
chunker = HybridChunker() # pass your embedder's tokenizer here in production
for chunk in chunker.chunk(dl_doc=doc):
# contextualize() returns the text WITH its heading path: that is what you embed
embed_text = chunker.contextualize(chunk=chunk)
shown_text = chunk.text # the chunk body on its own: what you display and cite
print(len(embed_text), "|", shown_text[:60].replace("\n", " "))
# --- Unstructured: partition, then chunk the elements ---
elements = partition(filename="data/report.pdf")
for c in chunk_by_title(elements, max_characters=1000, combine_text_under_n_chars=200):
print(type(c).__name__, len(c.text), "|", c.text[:60].replace("\n", " "))412 | Getting started Install the CLI and run acme init.
388 | Plans Pro 10 seats $200/yr, Team 50 seats $800/yr.
CompositeElement 342 | Q3 Data Pipeline Report Parsing coverage: PDF, HTML, Office, email, structured.How to choose between a library chunker and the hand-rolled ones above:
- Use the library chunker when the same library already did your parsing, you want provenance kept for free, and its defaults pass your retrieval harness (7.4).
- Keep your own chunker when you need identical behaviour across parsers (a Markdown route, a DOCX route and a PDF route), deterministic chunk IDs that you control (6.4), or a size unit the library does not offer.
- Either way, check three things on a sample: the chunk size distribution against your embedder's limit (2.2), that a table's header travels with its rows, and that
by_title-style grouping did not collapse because the parser found no headings (a corpus of flat documents yields one giant section).
4.6 Semantic chunking#
Semantic chunking ignores character counts and asks: where does the meaning change? Split the text into sentences, embed each (or small windows of) sentence(s), measure the distance between consecutive embeddings, and break where the distance spikes — a topic boundary produces a bigger jump than a sentence boundary inside a topic.
The canonical recipe is Greg Kamradt's "5 levels of text splitting" (the video LlamaIndex's docs credit), implemented in LangChain's SemanticChunker and LlamaIndex's SemanticSplitterNodeParser: group sentences into windows of buffer_size, embed each window, compute cosine distance (1 − similarity) between consecutive windows, and split where the distance exceeds a threshold — typically a percentile of all distances in that document (95th by default), or mean + k·std, or mean + k·IQR.
Here is the whole algorithm in pure Python with a toy embedding (a hashed bag-of-words stand-in — deliberately crude, so you can see the mechanics without an embedder):
# s4_6_semantic.py
import hashlib
import math
import re
from s4_2_sentences import split_sentences
STOP = {"the", "a", "an", "and", "or", "of", "to", "in", "is", "are", "for",
"on", "with", "it", "its", "that", "this", "be", "as", "at", "by"}
def toy_vector(text: str, dim: int = 64) -> list[float]:
"""Deterministic stand-in for an embedding model: hashed content-word counts."""
vec = [0.0] * dim
for tok in re.findall(r"[a-z0-9]+", text.lower()):
if tok in STOP:
continue
h = int(hashlib.blake2b(tok.encode(), digest_size=8).hexdigest(), 16)
vec[h % dim] += 1.0
norm = math.sqrt(sum(x * x for x in vec)) or 1.0
return [x / norm for x in vec]
def cosine(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def percentile(values: list[float], p: float) -> float:
"""Nearest-rank percentile, p in [0, 100]. (numpy's `percentile`, which
libraries like LangChain's SemanticChunker use, interpolates between
ranks instead — thresholds on short distance lists will differ
slightly; the choice here is ours, not theirs.)"""
s = sorted(values)
k = max(0, min(len(s) - 1, math.ceil(p / 100 * len(s)) - 1))
return s[k]
def semantic_split(sentences: list[str], embed, buffer_size: int = 1,
pct: float = 95) -> list[str]:
"""Embed windows of `buffer_size` sentences, measure cosine distance
between consecutive windows, and break where the distance exceeds the
p-th percentile of all distances. A spike at index i marks the boundary
*between* window i and window i+1, so the break lands before sentence
(i + 1) * buffer_size."""
groups = [" ".join(sentences[i:i + buffer_size])
for i in range(0, len(sentences), buffer_size)]
vecs = [embed(g) for g in groups]
dists = [1.0 - cosine(vecs[i], vecs[i + 1])
for i in range(len(vecs) - 1)]
threshold = percentile(dists, pct) if dists else 1.0
breaks = {(i + 1) * buffer_size for i, d in enumerate(dists)
if d > threshold}
chunks, cur = [], []
for i, s in enumerate(sentences):
if i in breaks and cur:
chunks.append(" ".join(cur))
cur = []
cur.append(s)
if cur:
chunks.append(" ".join(cur))
return chunks
if __name__ == "__main__":
text = ("The warranty covers manufacturing defects for two full years. "
"Warranty claims require a valid purchase receipt. "
"Warranty repairs for defects are free during the warranty period. "
"Standard shipping takes three to five business days. "
"Express shipping arrives within one to two business days. "
"Shipping confirmation and tracking arrive by email. "
"Returns are accepted within thirty days of delivery. "
"Opened products may be returned if unused and still sealed. "
"Refunds return to the original payment method.")
sents = split_sentences(text)
print(f"{len(sents)} sentences")
vecs = [toy_vector(s) for s in sents]
dists = [round(1.0 - cosine(vecs[i], vecs[i + 1]), 3)
for i in range(len(vecs) - 1)]
print("distances:", dists, " p65 threshold:", round(percentile(dists, 65), 3))
for i, c in enumerate(semantic_split(sents, toy_vector, pct=65)):
print(f"\n--- chunk {i} ---\n{c}")9 sentences
distances: [0.864, 0.728, 1.0, 0.473, 0.859, 1.0, 0.856, 0.842] p65 threshold: 0.864
--- chunk 0 ---
The warranty covers manufacturing defects for two full years. Warranty claims require a valid purchase receipt. Warranty repairs for defects are free during the warranty period.
--- chunk 1 ---
Standard shipping takes three to five business days. Express shipping arrives within one to two business days. Shipping confirmation and tracking arrive by email.
--- chunk 2 ---
Returns are accepted within thirty days of delivery. Opened products may be returned if unused and still sealed. Refunds return to the original payment method.Study this output honestly — it teaches two things at once. The two 1.0 distances are the real topic boundaries (warranty→shipping, shipping→returns), and the break lands between the two windows whose distance spiked — so each chunk is exactly one topic. Even the crude bag-of-words embedder found them, but only because the three topics use disjoint vocabularies: "warranty/defects/receipt" never appears in the shipping or returns sentences. A real embedder also catches paraphrase and partial overlap that word-counting misses — semantic chunking quality is embedder quality, which is why you measure before adopting it (7.3–7.4).
Cost. Every sentence (or window) needs an embedding call at ingest: a 500-sentence document costs ~500 embed calls before you store a single chunk. At embedding prices that's usually small money but real latency, and it must be redone whenever the embedder or the threshold changes. Evidence is genuinely mixed — see 7.3: Qu, Tu & Bao's evaluation (arXiv:2410.13070, October 2024) found semantic chunking's costs "not justified by consistent performance gains" over fixed-size on their tasks, while practitioner reports (Kamradt's recipe, LangChain/LlamaIndex adoption, AWS Bedrock's managed semantic chunking) show wins on prose with clear topic drift. Treat it as a candidate for your hard documents, not a default.
Library equivalents:
- LlamaIndex
SemanticSplitterNodeParser(llama-index-core0.14.25):SemanticSplitterNodeParser(buffer_size=1, breakpoint_percentile_threshold=95, embed_model=embed_model)— requires anembed_model(e.g.OpenAIEmbedding()); uses NLTK Punkt for sentences. Active, maintained. - LangChain
SemanticChunker: historicallyfrom langchain_experimental.text_splitter import SemanticChunkerwithbreakpoint_threshold_type="percentile"|"standard_deviation"|"interquartile"|"gradient",breakpoint_threshold_amount,buffer_size,min_chunk_size,sentence_split_regex. ⚠️langchain-experimental0.4.2 is sunset (the package announced deprecation in May 2026); a migration PR tolangchain-text-splitterswas proposed but closed unmerged, so as of November 2026 the import still lives in the unmaintained package — prefer LlamaIndex's version or roll your own 60 lines like the code above. - Managed: AWS Bedrock Knowledge Bases offers a
SEMANTICchunking strategy in itsChunkingConfiguration(alongsideFIXED_SIZE,HIERARCHICALandNONE— verify current options in the Bedrock docs), and document-parsing platforms sell semantic splitting as a feature. Verify current offerings before citing.
Pros: finds topic boundaries no character rule can; variable chunk sizes match content. Cons: embedder cost + latency at ingest; threshold is per-document and finicky (percentile is relative — a document with no topic shifts still gets split at its "least similar" gaps); output is non-deterministic across embedder versions; still needs a max-size post-pass. Use when: high-value prose corpora (articles, reports, papers) where topic drift is real and retrieval quality is proven to matter — after cheaper strategies have been measured and found wanting.
4.7 LLM-based chunking (agentic chunking)#
The most expensive option: hand the document to a language model and let it choose the boundaries — sometimes also writing a per-chunk summary or likely questions. Variants include "agentic chunking" (the model proposes and refines splits, possibly with tools), proposition-level chunking (split into atomic facts), and LLM-assisted structure recovery for documents whose markup failed.
- Quality ceiling. On messy documents — scanned contracts, transcripts, mixed-format dumps — an LLM reads meaning the way no regex can. Boundary quality is typically the best of any strategy.
- Cost. One LLM pass over the whole corpus at ingest, plus re-chunking on every document change (05.9's incremental updates make this painful: one changed paragraph can re-trigger the whole document's LLM pass unless you scope it). Output tokens dominate the bill.
- Non-determinism. Two runs can produce different boundaries → different chunk IDs → different embeddings → an index that silently drifts. Pin a model version and temperature where the provider allows, and version the chunking config.
- Hallucination risk is low but real: the model chooses boundaries, it shouldn't rewrite content — enforce that by construction (it returns split points, you slice the original text), never let it emit the chunk text.
Anthropic's Contextual Retrieval work (September 2024) is the famous adjacent technique: an LLM writes a 50–100-token context sentence per chunk at ingest, which is prepended before embedding — they reported up to 49% fewer retrieval failures (67% with reranking). That's contextualised chunking rather than boundary selection, and 05.7 covers it properly; the ingest-time LLM cost (~$1.02 per million document tokens in their worked example) is the same order as agentic chunking.
Use when: a small, high-value, slow-changing corpus where retrieval failures are expensive (contracts, medical-style FAQs, legal discovery) — and only after measuring that cheaper strategies actually fail on it. For bulk corpora the cost is prohibitive; for structured documents it's wasted (the structure already tells you where to cut).
4.8 Sliding windows#
A sliding window is fixed-size chunking with mandatory overlap: window of size, stride of size − overlap. It's what token_fixed_chunks in 4.1 implements and what time-series/log tooling calls a window. It exists for streams where every position matters (sensor readings, logs, transcripts with timestamps) and as the mental model for overlap generally. For documents, prefer sentence-aware packing (4.2) or recursive (4.4) — same overlap benefit without mid-word cuts.
4.9 Token-aware splitting#
Whatever strategy you pick, the budget should be enforced in the embedder's tokens, not characters. The pattern: a count: str -> int function injected into the splitter (my size_fn/length_function parameters throughout are exactly this seam). For OpenAI-style tokenizers:
# illustrative — needs `uv add tiktoken`
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # current OpenAI encoding
count = lambda text: len(enc.encode(text))
# then pass `count` as size_fn / length_function to any splitter aboveFor other embedding families, use the model's own HF tokenizer (tokenizer(text)["input_ids"] via transformers) — 02.2, 12.6 covers where tokenizers live in the stack, including the all-MiniLM-L6-v2 example whose max_seq_length is 256. For provider-hosted embedder models you can't run locally, estimate with the learned-ratio pattern from 03.7, 2.7 and verify against the provider's count endpoint on samples.
4.10 Two strategies that live on the retrieval side (preview of 05.7)#
Two families sit slightly outside the splitter frame — they decide what gets stored and returned, not just where text is cut — so 05.7 builds them in full:
- Sentence-window retrieval embeds each sentence (or small window) separately for precise matching, but at query time expands a hit to its neighbouring sentences — small units for recall, larger context for the prompt, at the cost of a bigger index.
- Parent-child (small-to-big) chunking indexes small chunks but returns the parent section to the LLM — the same precision/context trade-off resolved by storing two granularities and looking up the parent on a hit.
Both are indexing-structure strategies rather than boundary strategies; the boundary rules in Part 5 still apply to the small units.
Part 5: Boundary rules and edge cases#
Deep-dive
Every strategy above is a proposal; these rules are the review. Apply them as a post-pass on whatever the splitter produced.
5.1 Never split context from content#
A boundary is bad when it separates meaning from its referent:
| Don't split | Why | How to avoid |
|---|---|---|
| A sentence | half a thought in each chunk | sentence-aware packing or recursive ". "/" " levels |
| A code fence | unbalanced fences break rendering and meaning | track fence state; treat the whole block as atomic (05.7 covers code properly) |
| A table | header in chunk A, rows in chunk B — values lose their columns | detect tables in 05.2/05.3 parsing; emit table-level chunks with the header repeated |
| A list item | bullet 3 orphaned from bullets 1–2 | keep list blocks atomic; split at blank lines between lists |
| A heading from its section | "## Returns" alone tells a retriever nothing | structure-aware chunking (4.5) or a "keep heading with first N chars" rule |
| A caption from its figure/table | "Figure 3:" with no figure | captions are metadata-attached units (05.2 stores them) |
| A question from its answer | FAQ pairs must stay together | pair-level chunks for Q&A corpora |
| A defined term from its definition | legal "X means..." clauses | clause-level chunking for contracts (05.7) |
| A pronoun/reference from its antecedent | "it", "the above", "this model" | prefer larger context or breadcrumbs (Part 6) |
5.2 Enforce min and max sizes#
Splitters produce fragments: a 3-char chunk ("## "), a 4,000-char wall. The post-pass fixes both:
# s5_postpass.py
def _hard_split(text: str, size_fn, max_size: int) -> list[str]:
"""Split oversized text on the last space before max_size; fall back to
a hard cut when a single 'word' is longer than max_size."""
out, rest = [], text
while size_fn(rest) > max_size:
cut = rest.rfind(" ", 0, _char_budget(rest, size_fn, max_size))
if cut <= 0:
cut = _char_budget(rest, size_fn, max_size)
out.append(rest[:cut].strip())
rest = rest[cut:].strip()
if rest:
out.append(rest)
return out
def _char_budget(text: str, size_fn, max_size: int) -> int:
"""Largest char index whose prefix fits max_size (binary search)."""
lo, hi = 0, len(text)
while lo < hi:
mid = (lo + hi + 1) // 2
if size_fn(text[:mid]) <= max_size:
lo = mid
else:
hi = mid - 1
return lo
def enforce_sizes(chunks: list[str], size_fn, min_size: int,
max_size: int) -> list[str]:
"""1) split anything > max_size; 2) merge anything < min_size into a
neighbour — a small chunk absorbs what follows it, or is absorbed by
what precedes it. max_size always wins: a merge that would push a chunk
back over the limit is refused, and the fragment stays small."""
flat: list[str] = []
for c in chunks:
flat.extend(_hard_split(c, size_fn, max_size)
if size_fn(c) > max_size else [c])
def fits(a: str, b: str) -> bool:
return size_fn(a) + size_fn(b) + 2 <= max_size # + the "\n\n" join
merged: list[str] = []
for c in flat:
if merged and fits(merged[-1], c) and (
size_fn(merged[-1]) < min_size or size_fn(c) < min_size):
merged[-1] = merged[-1] + "\n\n" + c
else:
merged.append(c)
if len(merged) > 1 and size_fn(merged[-1]) < min_size \
and fits(merged[-2], merged[-1]):
merged[-2] += "\n\n" + merged[-1]
merged.pop()
return merged
if __name__ == "__main__":
messy = ["Short.", "A slightly longer fragment that is still under the minimum.",
"x" * 700, "y" * 199, "z" * 17, "Another tiny one."]
for c in enforce_sizes(messy, len, min_size=60, max_size=200):
print(f"[{len(c)} chars] {c[:70]!r}")[67 chars] 'Short.\n\nA slightly longer fragment that is still under the minimum.'
[200 chars] 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
[200 chars] 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
[200 chars] 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
[100 chars] 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
[199 chars] 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
[36 chars] 'zzzzzzzzzzzzzzzzz\n\nAnother tiny one.'(The x-run splits into 200-char pieces at the last space — there is none, so it hard-cuts; the last 100-char piece stays whole. "Another tiny one." merged forward into the 17-char z-fragment — but neither could merge into the 199-char y-chunk: 199 + 17 + 2 > max_size=200, so the merge was refused and a 36-char sliver survives. max_size is the hard constraint — it protects the embedder's limit — while min_size is a preference; when no merge fits, a small chunk is cheaper than an oversized one.) Minimum size matters as much as maximum: a 5-token fragment carries almost no context and mostly adds noise and cost. Set min_size to roughly half your target chunk size — fragments below it merge forward. Edge cases: a document shorter than one chunk passes through untouched (emit it whole — don't pad); an empty or whitespace-only document yields zero chunks and should be flagged upstream by 05.10's quality checks, not silently dropped here.
5.3 Edge cases checklist#
| Case | What goes wrong | Handling |
|---|---|---|
| Multilingual / CJK | No whitespace → word/char splitters shatter words; char budgets don't track tokens | size in the embedder's tokens; sentence splitters that support the script (wtpsplit covers 85 languages); never assume split() works |
| Very long tables | exceed embedder limit; header far from rows | split by row-groups with the header repeated in each chunk (05.7's table recipe) |
| Code | mid-function cuts destroy meaning | AST/brace-aware boundaries (05.7); keep imports/docstrings with their function |
| Legal numbering ("3.2.1", "Clause 8(a)(ii)") | naive sentence split breaks on the periods in numbers | protect enumerations with a regex pre-pass or a real sentence tokenizer |
| Repeated templates (boilerplate headers on every page) | every chunk starts with identical noise | remove in 05.5 cleaning before chunking; or strip per-chunk in post |
| Mixed media (text + image captions) | caption orphaned | keep caption with its figure's description; images themselves are 03.6/Module 09 territory |
| Transcripts/chat | speaker turns and timestamps matter | chunk by turn/time-window, keep speaker labels (05.7 has the recipes) |
Part 6: Chunk representation#
A chunk is more than its text. What you store and what you send can differ — and usually should.
6.1 Three texts per chunk#
| Text | Used for | Contains |
|---|---|---|
text (display) |
showing the user the cited source | the raw chunk, clean |
embed_text |
the embedding model | optionally breadcrumb + body (see 6.2) |
prompt_text |
the LLM's context at generation | chunk + neighbours' summaries or the parent section (05.7's expansion) |
Conflating them is a classic bug: embedding raw text loses the section context; embedding breadcrumb-prefixed text but displaying it shows users ugly "Handbook > Warranty\n\n..." prefixes; stuffing whole sections into the prompt wastes context. Keep all three fields.
6.2 Breadcrumbs and context prefixes#
The cheapest context fix in RAG: prepend the section path to the embedded text. "The warranty starts on the date of purchase" embedded alone is ambiguous; "Acme Product Handbook > Warranty\n\nThe warranty starts..." embeds with its topic attached. Anthropic's contextual retrieval (an LLM-written 50–100-token context per chunk) is the expensive generalisation — 05.7 covers it. Deterministic breadcrumbs cost nothing and fix the most common "chunk lost its heading" failure.
6.3 The Chunk model#
This is the minimal record every downstream stage needs. 05.8 grows it into the full ChunkMeta — document fields, ACLs, lineage, quality flags — deliberately reusing the same field names and the same ID scheme, so nothing gets renamed downstream. Stdlib version (the module's production models are Pydantic — same fields):
# s6_3_chunk_model.py
import hashlib
from dataclasses import dataclass, field
@dataclass
class Chunk:
doc_id: str
chunk_index: int # position within the document — ordering
# and display only, NEVER part of the ID
text: str # the text you embed and show
chunker_version: str # e.g. "markdown-v1", "recursive-v1"
section_path: list[str] = field(default_factory=list) # breadcrumb
char_start: int | None = None # offsets into the source document text
char_end: int | None = None
token_count: int | None = None
embed_text: str | None = None # what actually goes to the embedder
prev_chunk_id: str | None = None
next_chunk_id: str | None = None
occurrence: int = 0 # nth identical chunk text in this doc
meta: dict = field(default_factory=dict)
@property
def text_hash(self) -> str:
return hashlib.sha256(self.text.encode("utf-8")).hexdigest()
@property
def chunk_id(self) -> str:
"""Content-addressed ID: doc + chunker version + text hash +
occurrence. Position is deliberately absent — see 6.4."""
payload = "|".join([
self.doc_id, self.chunker_version,
self.text_hash, str(self.occurrence),
])
return f"chk_{hashlib.sha256(payload.encode()).hexdigest()[:24]}"
def embed_input(self) -> str:
"""Text sent to the embedding model: breadcrumb + body when present."""
if self.embed_text:
return self.embed_text
crumb = " > ".join(self.section_path)
return f"{crumb}\n\n{self.text}" if crumb else self.text
def to_chunks(doc_id: str, pieces: list[dict], chunker_version: str) -> list[Chunk]:
"""Attach deterministic content-addressed IDs and neighbour pointers
to raw splitter output."""
chunks = [Chunk(doc_id=doc_id, chunk_index=i,
chunker_version=chunker_version, **p)
for i, p in enumerate(pieces)]
seen: dict[str, int] = {}
for c in chunks:
c.occurrence = seen.get(c.text_hash, 0)
seen[c.text_hash] = c.occurrence + 1
ids = [c.chunk_id for c in chunks]
for i, c in enumerate(chunks):
c.prev_chunk_id = ids[i - 1] if i else None
c.next_chunk_id = ids[i + 1] if i + 1 < len(ids) else None
return chunks
if __name__ == "__main__":
from corpus import HANDBOOK
from s4_5_markdown import markdown_chunks
pieces = [{"text": c["text"], "section_path": c["section_path"],
# toy offsets — compute real ones with locate/search like 8.1
"char_start": 0, "char_end": len(c["text"])}
for c in markdown_chunks(HANDBOOK, max_chars=300)]
chunks = to_chunks("handbook", pieces, "markdown-v1")
for c in chunks:
print(f"{c.chunk_id} (index {c.chunk_index})\n"
f" section={' > '.join(c.section_path)!r} "
f"prev={c.prev_chunk_id} next={c.next_chunk_id}")
print(f" embed> {c.embed_input()[:90]!r}")chk_0e542917ad2f615b99dc46d7 (index 0)
section='Acme Product Handbook > Warranty' prev=None next=chk_f79457ca7f6f01354927a361
embed> 'Acme Product Handbook > Warranty\n\nEvery Acme Drill carries a two-year warranty covering ma'
chk_f79457ca7f6f01354927a361 (index 1)
section='Acme Product Handbook > Returns' prev=chk_0e542917ad2f615b99dc46d7 next=None
embed> 'Acme Product Handbook > Returns\n\nCustomers may return an unopened product within 30 days f'6.4 IDs, neighbours and offsets#
- Content-addressed IDs.
chunk_id = chk_+ 24 hex chars ofsha256(doc_id | chunker_version | text_hash | occurrence)— the same scheme 05.8, 3.3 specifies forChunkMeta. Two deliberate choices: position is excluded (chunk_indexis stored as metadata for ordering, but inserting a paragraph re-IDs only the chunks whose text changed — which is what lets 05.9 reuse the embeddings of unchanged chunks instead of re-embedding the whole tail of a document); andchunker_versionis included, so changing the chunker changes every ID and forces a clean re-index rather than silently mixing two chunkings.occurrencedisambiguates identical chunk texts inside one document (repeated boilerplate). One caveat 05.9 spells out: the ID coverstext, but the embedder seesembed_input(breadcrumb + body) — if a breadcrumb changes without the body changing, the embedded text changed under a stable ID; either hashembed_inputinto the ID material or treat breadcrumb changes as chunk changes, and write the choice down. prev_chunk_id/next_chunk_idenable neighbour expansion at query time (fetch the chunk before a hit when the hit starts mid-thought) — cheap context without stuffing whole sections.char_start/char_endare your citation offsets: "show me where in the source this came from" and deep links back into the document. For PDFs prefer page+bbox from 05.2'sParsedDocument; char offsets are the fallback.token_countlets you budget prompt assembly later without recounting.
Metadata design — ACLs, dates, lineage, what's filterable vs embedded — is 05.8; this lesson only fixes the chunk-level fields every downstream stage needs.
Part 7: Choosing a strategy#
7.1 The decision table#
| Document type | Query type | Recommended | Why |
|---|---|---|---|
| Markdown/docs site | factual lookup | structure-aware (4.5) + recursive fallback | headings = natural sections; breadcrumbs free |
| PDF handbook/report | factual + "summarise section X" | structure-aware on outline, else recursive | outline gives sections; else paragraph/sentence hierarchy |
| HTML help centre | factual lookup | structure-aware on h1–h3/article |
DOM has the structure; boilerplate already removed in 05.3 |
| Contract/legal | clause lookup, obligations | structure-aware on clause numbering → 05.7 recipes | "Clause 8.2" must stay whole; definitions cross-reference |
| Support tickets (JSON) | similar-ticket retrieval | one ticket per chunk (or ticket+thread) | record boundary is the semantic unit |
| Meeting transcripts/chat | "what was decided about X" | turn/time-window chunks keeping speaker labels | speaker turns are the unit; 05.7 recipes |
| Tables/spreadsheets | "what's the price of SKU-7" | row-group chunks with repeated header | never split header from rows |
| Code | "where is function X" | AST-aware (05.7) | function/class boundaries |
| Long-form articles/papers | topical Q&A | sentence-packed or recursive; semantic if measured better | prose has no markup; semantic helps if embedder is good |
| Logs/metrics/JSONL | anomaly/aggregation | fixed-size windows or record-per-line | uniform structure; no semantics to respect |
| Mixed/unstructured mess | anything | recursive + post-pass as baseline; escalate hard docs | baseline first, then measure |
Rule of thumb: structure first, semantics second, size last. Use the document's own boundaries where they exist; reach for embedding-similarity boundaries only where they don't and quality demands it.
7.2 What chunking changes downstream#
| Downstream stage | Effect of bad chunking |
|---|---|
| Retrieval recall@k | answer-bearing text split across chunks → neither retrieves → miss |
| Retrieval precision | huge chunks → top-k filled with one topic's wall-of-text |
| Citation quality | chunk without its heading/section → citation points at context-free text |
| Generation | LLM sees fragment without antecedent → hallucinated or hedged answer |
| Cost | small chunks → more embeddings + more top-k slots used per answer; large chunks → more prompt tokens per answer |
| Incremental updates | unstable boundaries → changed paragraph re-chunks neighbours → more re-embedding (05.9) |
7.3 What the evidence actually says#
Be honest about the state of knowledge — it's thinner than the hype:
- Anthropic's Contextual Retrieval (Sept 2024) reported up to 49% fewer retrieval failures (67% with reranking) — but that's contextualised embeddings (LLM-written context per chunk), not boundary selection, and it's one company's benchmark on their data.
- Semantic chunking: practitioner recipe (Kamradt) widely adopted; but Qu, Tu & Bao (arXiv:2410.13070, Oct 2024, Vectara) evaluated it on document retrieval, evidence retrieval and answer generation and found the extra embedding cost "not justified by consistent performance gains" over fixed-size. Other evaluations and vendor benchmarks disagree — the honest summary is it depends on the corpus and embedder, measure it.
- Surveys: "Beyond Chunk-Then-Embed" (arXiv:2602.16974, Feb 2026) taxonomises the whole space — structure-based, semantic, LLM-guided, contextualised — and confirms there's no dominant winner across settings.
- RAPTOR (arXiv:2401.18059, ICLR 2024) and late chunking (arXiv:2409.04701) are embedding-time strategies (cluster+summarise trees; embed-then-chunk) — powerful but Module 06/07 territory; 05.7 previews them.
The meta-lesson the literature agrees on: evaluate on your own questions. The next two parts build that evaluation.
7.4 Evaluating chunking on your own data#
The test that matters: does the chunk containing the answer get retrieved? Build a small question set where you know which text answers each question, split your corpus with strategy A, retrieve top-k with a stand-in retriever, and measure recall@k — the fraction of questions whose answer-bearing chunk appears in the top-k.
A tiny BM25 (the lexical ranker behind hybrid search — Module 06 covers it properly) runs with zero dependencies:
# s7_bm25_eval.py
import math
import re
from collections import Counter
TOKEN_RE = re.compile(r"[a-z0-9]+")
def tokenize(text: str) -> list[str]:
return TOKEN_RE.findall(text.lower())
class TinyBM25:
"""Okapi BM25 over a list of texts. k1=1.5, b=0.75 are the usual defaults."""
def __init__(self, docs: list[str], k1: float = 1.5, b: float = 0.75):
self.k1, self.b = k1, b
self.docs = [tokenize(d) for d in docs]
self.n = len(self.docs)
self.avgdl = sum(len(d) for d in self.docs) / max(1, self.n)
df: Counter = Counter()
for d in self.docs:
df.update(set(d))
self.idf = {t: math.log(1 + (self.n - f + 0.5) / (f + 0.5))
for t, f in df.items()}
def score(self, query: str, i: int) -> float:
tf = Counter(self.docs[i])
dl = len(self.docs[i])
s = 0.0
for t in set(tokenize(query)):
f = tf.get(t, 0)
if not f:
continue
idf = self.idf.get(t, 0.0)
s += idf * f * (self.k1 + 1) / (
f + self.k1 * (1 - self.b + self.b * dl / self.avgdl))
return s
def rank(self, query: str, k: int) -> list[int]:
return sorted(range(self.n), key=lambda i: -self.score(query, i))[:k]
def recall_at_k(questions: list[tuple[str, set[int]]], chunks: list[str],
k: int = 3) -> tuple[float, list[bool]]:
"""questions: (query, gold chunk indices). Hit = any gold chunk in top-k."""
index = TinyBM25(chunks)
hits = []
for q, gold in questions:
top = set(index.rank(q, k))
hits.append(bool(top & gold))
return sum(hits) / len(hits), hits
if __name__ == "__main__":
chunks = [
"Acme sells drills and power tools online.",
"Every Acme Drill carries a two-year warranty covering manufacturing defects.",
"The warranty starts on the date of purchase and requires a valid receipt.",
"Damage caused by misuse, freezing temperatures or unauthorised repairs is excluded.",
"Customers may return an unopened product within 30 days for a full refund.",
"Standard shipping within the country takes 3 to 5 business days.",
"Express shipping takes 1 to 2 business days and costs a flat 12.00 per order.",
"International orders arrive in 7 to 14 days depending on customs.",
"The supplier's total liability is capped at fees paid in the preceding twelve months.",
"Either party may terminate this agreement for convenience on 90 days written notice.",
"A replacement drill was issued under warranty and return shipping was waived.",
]
questions = [
("how long is the warranty on a drill", {1, 2}),
("can I return a product for a refund", {4}),
("what does express shipping cost", {6}),
("how much notice to end the contract", {9}),
("what is the liability cap", {8}),
("customer drill arrived cracked what happened", {10}),
("how long does international delivery take", {7}),
("is water damage covered", {3}),
]
for k in (1, 3, 5):
r, hits = recall_at_k(questions, chunks, k=k)
print(f"recall@{k}: {r:.0%} hits={''.join('1' if h else '0' for h in hits)}")recall@1: 75% hits=11101011
recall@3: 100% hits=11111111
recall@5: 100% hits=11111111On this toy set BM25 is nearly perfect at k≥3 — expected: questions share vocabulary with their answers. Real evals need harder questions (paraphrases, questions whose words don't appear in the chunk — "broken on arrival" for a "housing is cracked" ticket — which BM25 misses and embeddings catch). That's exactly why production uses hybrid retrieval; Module 06/07 build it. For chunking evaluation the harness matters more than the retriever: keep the retriever fixed, vary only the chunking.
Part 8: Chunk-size experiments#
8.1 The sweep harness#
Fix the retriever and the question set; vary chunk_size and overlap; measure recall@k. Gold labels come from character spans: each question names a unique marker phrase inside its answer-bearing text; after splitting, a chunk is "relevant" iff its span overlaps the marker's span. This is answer-bearing-chunk coverage — the standard proxy for "could retrieval have found the evidence".
# s8_sweep.py
from s4_4_recursive import recursive_split
from s7_bm25_eval import TinyBM25
from corpus import HANDBOOK, HELP, CONTRACT, TICKET, MEETING
DOC = HANDBOOK + "\n\n" + HELP + "\n\n" + CONTRACT + "\n\n" + TICKET + "\n\n" + MEETING
QUESTIONS = [
("how long is the warranty on a drill", "two-year warranty"),
("can I return an opened product", "Opened products can be returned"),
("what does express shipping cost", "flat 12.00"),
("how much notice to terminate", "90 days written notice"),
("what is the liability cap", "capped at the fees"),
("customer drill arrived cracked resolution", "issued a replacement drill"),
("how long does international shipping take", "7 to 14 days"),
("is freezing damage covered by warranty", "freezing temperatures"),
("when was the warranty decision deferred to", "next week's sync"),
]
def locate_chunks(doc: str, pieces: list[str]) -> list[tuple[int, int]]:
"""Find each chunk's char span by sequential search (toy-scale only)."""
spans, pos = [], 0
for p in pieces:
i = doc.find(p, pos)
if i < 0:
i = doc.find(p)
spans.append((i, i + len(p)))
pos = max(0, i + 1)
return spans
def recall(pieces: list[str], spans: list[tuple[int, int]], k: int) -> float:
index = TinyBM25(pieces)
hits = 0
for q, marker in QUESTIONS:
ms = DOC.find(marker)
me = ms + len(marker)
gold = {i for i, (s, e) in enumerate(spans) if s < me and e > ms}
top = set(index.rank(q, k))
hits += bool(top & gold)
return hits / len(QUESTIONS)
if __name__ == "__main__":
seps = ["\n\n", "\n", ". ", " ", ""]
print(f"doc: {len(DOC)} chars, {len(QUESTIONS)} questions\n")
print(f"{'size':>6} {'overlap':>8} {'chunks':>7} {'recall@3':>9}")
for size in (150, 300, 600, 1200):
for ov in (0, size // 10):
pieces = recursive_split(DOC, seps, len, max_size=size, overlap=ov)
spans = locate_chunks(DOC, pieces)
r = recall(pieces, spans, k=3)
print(f"{size:>6} {ov:>8} {len(pieces):>7} {r:>8.0%}")doc: 2230 chars, 9 questions
size overlap chunks recall@3
150 0 28 78%
150 15 28 78%
300 0 10 78%
300 30 10 78%
600 0 5 100%
600 60 5 100%
1200 0 2 100%
1200 120 3 100%8.2 Reading noisy results — what this table actually says#
Don't read "bigger wins" naively. Three artefacts are at work:
- Recall@k conflates chunk size with quality. Bigger chunks mechanically score higher: they carry more context words for BM25 to match, and at 1200 chars the whole 2,230-char document fits in 2–3 chunks — with k=3, every chunk is retrieved and recall is trivially saturated. Recall alone can't see precision: those giant chunks also fill the prompt with irrelevant text. Always measure recall and a size/precision proxy (mean chunk size, or answer-token density).
- Tiny question sets are noisy. 9 questions → each is 11% of the score; one boundary fluke swings the result. Real evals use 50–500+ questions (Module 10A builds proper eval sets; 10A.2 generates synthetic ones).
- The retriever is lexical. BM25 can't reward semantic boundaries — it rewards word overlap. The two questions that miss at 150/300 chars are exactly the vocabulary-mismatch cases ("customer drill arrived cracked resolution" vs the ticket's wording, "warranty decision deferred" vs the meeting notes) — the failures embeddings and hybrid retrieval exist to fix (Module 06/07). An embedding retriever may rank differently; re-run the sweep with your real retriever before trusting the ranking.
The honest read of this run: recall climbs 78% → 100% as chunks grow — partly real (bigger chunks give BM25 more matching surface and keep the ticket/meeting evidence whole) and partly the saturation artefact at 1200. The overlap column shows almost no effect here — overlap matters at boundaries, and with only 9 questions and marker-based gold spans, few land exactly on one (the 4.4 demo shows what overlap costs when it does fire). That's the correct lesson: the sweep tells you where your corpus's sensitivity is, not a universal answer.
8.3 The cost of re-chunking#
# s8_cost.py
from s8_sweep import DOC
from s4_4_recursive import recursive_split
def ingestion_cost(num_chunks: int, avg_tokens_per_chunk: float,
price_per_1m_tokens: float) -> float:
"""One-off embedding cost for a corpus, in USD."""
return num_chunks * avg_tokens_per_chunk / 1_000_000 * price_per_1m_tokens
def corpus_stats(chunks: list[str], count_tokens) -> tuple[int, float]:
"""(chunk count, mean tokens per chunk) for a list of chunk texts."""
if not chunks:
return 0, 0.0
return len(chunks), sum(count_tokens(c) for c in chunks) / len(chunks)
def reindex_cost(num_chunks: int, avg_tokens: float, price: float,
times_per_year: int = 1) -> float:
return ingestion_cost(num_chunks, avg_tokens, price) * times_per_year
if __name__ == "__main__":
# corpus_stats on real sweep output: the toy doc split at max_size=600,
# word count as a stand-in token counter
pieces = recursive_split(DOC, ["\n\n", "\n", ". ", " ", ""], len,
max_size=600)
n_toy, avg_words = corpus_stats(pieces, lambda t: len(t.split()))
print(f"toy doc @600 chars: {n_toy} chunks, "
f"{avg_words:.0f} words/chunk (word proxy for tokens)\n")
# a real corpus: ~5,000 docs x ~40 chunks x ~380 tokens each
n_chunks, avg_tokens = 200_000, 380.0
for label, price in [("cheap (example $0.02/1M)", 0.02),
("mid (example $0.13/1M)", 0.13),
("large (example $0.22/1M)", 0.22)]:
once = ingestion_cost(n_chunks, avg_tokens, price)
yearly = reindex_cost(n_chunks, avg_tokens, price, times_per_year=4)
print(f"{label}: ${once:,.2f} once; ${yearly:,.2f}/yr at 4 reindexes")toy doc @600 chars: 5 chunks, 73 words/chunk (word proxy for tokens)
cheap (example $0.02/1M): $1.52 once; $6.08/yr at 4 reindexes
mid (example $0.13/1M): $9.88 once; $39.52/yr at 4 reindexes
large (example $0.22/1M): $16.72 once; $66.88/yr at 4 reindexesPrices are parameters, never constants — check your embedder's current price per 1M input tokens (Module 06 covers the models; 03.7 covers cost tracking). The point isn't the dollars — it's that every chunking change is a re-embed bill, which is why chunking config is versioned (Part 6's chunker_version field) and why 05.9 reuses unchanged-chunk embeddings by content hash.
Part 9: Anti-patterns and failure gallery#
Reference
9.1 Anti-patterns#
| Anti-pattern | Why it fails | Fix |
|---|---|---|
| Chunking before cleaning | splits on boilerplate, mojibake, repeated headers — noise becomes chunks | clean first (05.5), chunk the clean text |
Splitting on "\n\n" blindly |
paragraph ≠ semantic unit; headings orphan; huge walls survive | structure-aware + post-pass |
| Characters as a token proxy for non-English | CJK has no spaces; char budgets misfire badly | count in the embedder's tokens |
| One-size-fits-all | FAQ pairs ≠ contract clauses ≠ logs | per-doc-type strategy (7.1) |
| No min size | 3-token fragments pollute index and top-k | enforce_sizes merge pass |
| Overlap everywhere "just in case" | duplicates crowd top-k; +20% embed cost for nothing | measure; 10–20% start, dedupe after retrieval |
| Embedding text ≠ displayed text conflated | users see breadcrumbs; model sees raw | three text fields (6.1) |
| Unversioned chunker | silent index drift on config change | chunker_version in chunk ID |
| Evaluating once on 5 questions | noise reads as signal | sweep + bigger question set (Part 7–8) |
9.2 Failure gallery#
| # | What you see | Root cause | Fix |
|---|---|---|---|
| 1 | "manufacturing def" / "ects" | fixed-size mid-word cut | sentence-aware or recursive |
| 2 | "## Returns" as its own chunk | heading severed from section | structure-aware (4.5) |
| 3 | "## Returns" heading repeated at next chunk start | char-overlap retained a heading-sized piece | structure-aware, or overlap below the smallest unit |
| 4 | table header in chunk A, rows in B | table split mid-unit | table-level chunks, repeat header |
| 5 | "it"/"this clause" with no antecedent | pronoun's referent in previous chunk | bigger context or breadcrumbs |
| 6 | answer exists but retrieval misses | evidence split across two chunks, neither complete | overlap or question-aware eval to find it |
| 7 | top-3 all from same section | giant chunks saturate top-k | smaller chunks + dedupe |
| 8 | Hindi query finds nothing | chunks sized in chars = token-tax overflow/truncation | token-aware sizing in embedder's units |
| 9 | re-ingest re-embeds everything | chunk IDs unstable across runs | deterministic IDs (6.4) |
| 10 | "semantic chunking didn't help" | embedder too weak / corpus has no topic drift / eval too small | measure on your data (7.3–7.4) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "There's an optimal chunk size for RAG." | It depends on embedder, doc type, query type and evaluator. 200–800 tokens is a starting range, not a law — measure it (Part 8). |
| "Bigger chunks are always safer — more context." | Bigger chunks dilute the embedding and flood the prompt; the "context" often hurts more than it helps (1.2). |
| "Semantic chunking is strictly better than recursive." | Mixed evidence: Qu et al. (arXiv:2410.13070) found costs not justified by consistent gains; it wins on topic-drifting prose with a good embedder. Measure (7.3). |
| "Overlap is free insurance." | It costs embeddings, storage and duplicate top-k slots; 10–20% is a start, not a default (Part 3). |
| "Characters ≈ tokens close enough." | Only for English prose on OpenAI-style tokenizers (~4 chars/token); CJK and code break the rule badly (2.1, token tax). |
| "The chunk text is what you embed, show and prompt." | Three different texts: embed gets breadcrumbs, display gets raw, prompt may get neighbours (6.1). |
| "Chunk once, done." | Chunking config is versioned pipeline state; changing it re-chunks and re-embeds — plan the cost (8.3, 05.9). |
| "An LLM picking boundaries will rewrite the text." | It should only return split points; you slice the original. Enforce by construction (4.7). |
Key takeaways#
- Chunk because three walls push the same way: embedder input limits, embedding dilution, retrieval/prompt budget — plus citation granularity.
- The fundamental tension: small chunks are precise but context-free; large chunks have context but dilute. A good chunk is self-contained, coherent, answerable.
- Size in the embedder's tokens, not characters; learn your corpus's tokens-per-unit ratio; 200–800 tokens is a starting range.
- Overlap fixes boundary-split evidence at ~10–20% cost in duplicates; sentence-level beats char-level.
- Strategy ladder: fixed-size (baseline) → sentence/paragraph packing → recursive (default) → structure-aware (best when markup exists) → semantic (measure first) → LLM-based (small high-value corpora only).
- Boundary rules beat cleverness: never split mid-sentence/table/list/heading-from-content; enforce min and max sizes as a post-pass.
- Store three texts (embed/display/prompt), deterministic versioned IDs, breadcrumbs, neighbours, offsets.
- Choose by document type and query type (7.1); evaluate on your own questions with recall@k (7.4); sweep size×overlap (Part 8) and read results honestly.
- Chunking is versioned pipeline state — changes re-chunk and re-embed; that's 05.9's problem to solve cheaply.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Chunk | A contiguous piece of a document sized for embedding, retrieval and prompting |
| Chunking | The strategy that decides where chunk boundaries fall |
| Overlap | Units repeated at the end of one chunk and start of the next, so boundary-straddling text survives whole |
| Sliding window | Fixed-size chunking with mandatory overlap; window + stride |
| Recursive splitting | Trying separators in priority order (paragraph→line→word→char), recursing only into oversized pieces |
| Structure-aware chunking | Splitting on the document's own structure (headings, sections, styles, outline) |
| Semantic chunking | Splitting where embedding similarity between consecutive sentences drops, i.e. at topic boundaries |
| LLM-based / agentic chunking | Letting a language model choose chunk boundaries at ingest |
| Breadcrumb | A chunk's section path ("Handbook > Warranty") prepended for context |
| recall@k | Fraction of questions whose answer-bearing chunk appears in the top-k retrieved |
| Answer-bearing chunk | The chunk(s) containing the text that answers a question |
| Post-pass | A final size/boundary enforcement step applied after any splitter |
HybridChunker / chunk_by_title |
The structure-reading chunkers of Docling (split over-long element chunks by tokens, merge small neighbours with the same headings) and Unstructured (start a new chunk at each Title, never span sections); see 4.5.1 |
| Chunk ID | A deterministic content-addressed identifier: doc + chunker version + text hash + occurrence; position deliberately excluded |
| embed_text vs display text | The breadcrumb-augmented text sent to the embedder vs the raw text shown to users |
Exercises#
- Fixed vs recursive (4.1, 4.4): run
fixed_size_chunksandrecursive_splitonHANDBOOK + HELPat the samemax_size. Count mid-word cuts in each. Why does recursive still produce an orphan "## Returns" chunk? - Overlap cost (Part 3): modify
token_fixed_chunksto report total embedded characters for overlap 0 vs 20%. At what overlap does cost double? - Post-pass (5.2): feed
enforce_sizesa list containing a 3-char fragment, a 10,000-char wall and normal paragraphs. Verify min-merge and max-split both fire, and check the merged chunk still reads coherently. - Structure-aware (4.5): convert
TICKETfromcorpus.pyinto Markdown with## Problem/## Resolutionheadings and runmarkdown_chunks. What breadcrumb does each chunk get? - Semantic (4.6): run
semantic_spliton the warranty/shipping/returns sentences withpct=95vspct=65. How many chunks does each produce, why does the higher percentile give fewer splits, and do thepct=65boundaries land on the three topics? - Chunk model (6.3): build
Chunks frommarkdown_chunks(HELP)and printembed_input()for each. Which chunk benefits most from its breadcrumb? - BM25 eval (7.4): add a question to the
questionslist whose wording shares no words with its answer chunk (e.g. "my parcel is broken, what now" → the cracked-drill ticket). Does BM25 find it? What does that tell you about lexical vs semantic retrieval? - Sweep (8.1): extend the sweep to
size=2400and add a "mean chunk size" column. Does recall keep rising? Explain the top-k saturation artefact. - Library check:
uv add langchain-text-splittersand runRecursiveCharacterTextSplitter(chunk_size=160, chunk_overlap=24, separators=["\n\n","\n",". "," ",""])on the same doc. Compare its output to yourrecursive_split— where do they differ and why? - Design: for the running corpus's contracts folder with scanned pages, choose a chunking strategy per document subtype and justify each in one sentence using the 7.1 table.
- Library chunkers (4.5.1): convert one PDF with Docling and
partitionit with Unstructured (05.2 Setup), chunk each withHybridChunkerandchunk_by_title, and run all four of your chunkers (fixed, recursive, structure-aware, library) through the 7.4 harness. Which wins on recall@3, which keeps a table's header with its rows, and what does each cost in code and dependencies?
Hints and worked answers
- Count mid-word cuts by checking whether a chunk boundary falls between two alphanumeric characters. Fixed-size produces many; recursive produces none because it cuts on separators. The orphan
## Returnschunk is explained in Check yourself Q5: the oversized body forced a flush before the heading could merge with it. - With chunk size
sand overlapo, each chunk advances bys - o, so the chunk count (and embedded characters) grows by abouts / (s - o). Cost doubles ato = s / 2, that is 50% overlap; 20% overlap costs about 25% more. - Build
["ab", "A normal paragraph of reasonable length.", "x" * 10_000, "Another normal paragraph with a few more words."]and callenforce_sizes(chunks, len, min_size=60, max_size=200). Expectabto merge into the paragraph after it (min rule) and the wall to be cut into pieces of at most 200 characters (max rule; a real wall with spaces is cut at the last space, this one has none, so it is hard-cut). Order matters: withabplaced directly before the wall it stays a 2-character chunk, because merging it into a full-size piece would breakmax_sizeand max always wins. Re-read the merged chunk aloud: if it joins two unrelated topics, your min size is too high. - Rewrite the ticket as
## Problem(customer message) and## Resolution(agent reply) sections under a# Ticket AC-2026-0417title. The breadcrumbs should beTicket AC-2026-0417 > Problemand... > Resolution. - The threshold is the 95th percentile of the consecutive-sentence distances, and a gap splits only when it is larger than the threshold. With eight distances the nearest-rank 95th percentile is the maximum itself, so nothing exceeds it and
pct=95returns one chunk. Atpct=65the threshold is 0.864, so the two gaps of 1.0 split and you get three chunks, one per topic. (With a real embedder the distances are less clean: print them and check the boundaries by eye.) - Print each
embed_input(). The chunks whose bodies use pronouns or say "this order" benefit most from the breadcrumb; the ones that already name the product and topic gain least. - BM25 is lexical, so a question that shares no words with its answer scores zero for the right chunk and will not find it. That is the motivating case for embeddings and for hybrid search (Module 06).
- At
size=2400the corpus becomes a handful of chunks, sok=3returns nearly everything and recall rises to 100% without the system getting better. Report mean chunk size beside recall to expose this artefact (8.2). - Typical differences: LangChain measures length with
lenunless you pass alength_function, strips whitespace by default, treats the separators list as an ordered hierarchy but keeps or drops the separator depending onkeep_separator, and merges small pieces greedily up tochunk_size; your version may handle the heading orphan differently. Diff the two outputs side by side. - Digital text contracts: structure-aware on clause numbering. Scanned contracts after OCR: recursive plus post-pass (OCR output has no reliable structure), with page numbers kept as metadata. Signature pages and stamps: skip or keep as single image-description chunks. Justify each against 7.1.
- Record, per chunker, the number of chunks, the median and maximum size in your embedder's tokens, recall@3, and whether the table header was repeated. Library chunkers usually win on provenance and table handling; yours usually wins on identical behaviour across parsers. Treat any difference smaller than the noise of your question set as a tie (8.2).
Check yourself#
- Name the three hard limits that make chunking necessary.The embedder's max input length (silent truncation), embedding dilution on multi-topic texts, and retrieval/prompt budget — plus citation granularity.
- Why is "400 characters" a bad unit for a multilingual corpus?Characters don't track tokens across languages; CJK has no spaces and the token tax makes char budgets misfire. Size in the embedder's tokens.
- What does chunk overlap fix, and what does it cost?It keeps boundary-straddling text whole in at least one chunk; it costs ~overlap% more embeddings/storage and can duplicate results in top-k.
- Which separator hierarchy does recursive splitting try first, and why that order?Paragraph (
\n\n) → line (\n) → sentence-ish → word → character: coarsest structure that fits, recursing only into oversized pieces. - In the recursive demo, why did "## Returns" end up as its own 12-char chunk, and why did the same heading reappear at the start of the next chunk?The oversized Returns body forced a flush before the heading could merge with it (orphan); then
overlap=50was large enough to retain the 12-char heading piece into the next chunk (duplication — and the retained prefix pushed that chunk pastmax_size). - What does structure-aware chunking give you that recursive splitting can't?Boundaries on the author's own section edges, headings kept with content, and breadcrumbs for free.
- How does semantic chunking decide where to break, and what does it cost at ingest?It embeds sentence windows and breaks where cosine distance between consecutive windows exceeds a percentile threshold; it costs one embedding call per sentence/window at ingest.
- Why is
langchain-experimental'sSemanticChunkera risky dependency in 2026?The package is sunset (deprecated May 2026, last feature release Dec 2025); the migration to langchain-text-splitters was proposed but closed unmerged. - What's the difference between
text,embed_textandprompt_textfor a chunk?textis shown to users;embed_text(breadcrumb+body) goes to the embedder;prompt_textis what the LLM sees at generation — they can differ. - Why should a chunk ID include the chunker version?So a chunking change produces new IDs and forces a clean re-index instead of silently mixing two chunkings.
- What is recall@k measuring in a chunking eval, and what's its blind spot?Whether the answer-bearing chunk is retrieved in top-k; its blind spot is it can't see precision/context bloat — huge chunks game it via top-k saturation.
- Why did the 1200-char sweep "win" — and why is that misleading?With 2–3 chunks and k=3 everything is retrieved, inflating recall while flooding prompts — an artefact, not a quality signal.
- When is LLM-based chunking worth its cost?Small, high-value, slow-changing corpora where cheaper strategies measurably fail and boundary quality matters.
- What's the post-pass for, and what are min and max sizes for?It enforces min (merge fragments) and max (hard-split walls) sizes after any splitter; min prevents context-free slivers, max respects the embedder limit.
- You parsed with Docling. Why might its
HybridChunkerbeat your own recursive splitter, and what would make you keep your own?It reads typed elements (headings, list items, tables) instead of guessing them from flat text, measures size in your embedder's tokens, repeats table headers, merges small neighbours under the same headings and keeps provenance. Keep your own chunker when you need identical behaviour across parsers, controlled deterministic chunk IDs or a size unit the library lacks; either way compare on your own questions (4.5.1).
Further resources#
- Greg Kamradt, "5 Levels Of Text Splitting" (YouTube): the practitioner recipe behind semantic chunking; LlamaIndex's docs credit it directly.
- Anthropic, "Contextual Retrieval" (engineering blog, Sept 2024): chunk-context prepending, the 49%/67% retrieval-failure claims, and the worked ingest-cost example.
- Qu, Tu & Bao, "Is Semantic Chunking Worth the Computational Cost?" (arXiv, Oct 2024): the skeptical counterweight — semantic chunking's costs vs consistent gains.
- Sarthi et al., "RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval" (ICLR 2024): hierarchical summary-tree retrieval — previewed in 05.7.
- Günther et al., "Late Chunking" (arXiv, Sept 2024): embed-then-chunk with long-context embedders — previewed in 05.7.
- "Beyond Chunk-Then-Embed" (arXiv, Feb 2026): a taxonomy and evaluation of chunking strategies — the survey to cite when someone asks "which is best".
- LangChain
langchain-text-splitters(docs, reference): the canonical splitter implementations. - LlamaIndex node parsers (docs):
SentenceSplitter,TokenTextSplitter,SemanticSplitterNodeParser. - Docling chunking concepts (docs) and Unstructured chunking (docs): the structure-reading chunkers of 4.5.1.
- Haystack preprocessors (docs):
DocumentSplitter,RecursiveDocumentSplitter. wtpsplit(PyPI, repo): multilingual neural sentence segmentation with length constraints.
← 05.5 — Cleaning and Normalization | Module 05 overview | 05.7 — Advanced and Document-Specific Chunking →