Sub topic 7
Sentence-based chunking
This chapter assumes you can read basic Python and know how fixed-size chunking works. You should also know that each chunk is embedded as one unit. Here you will build a chunker that never cuts a sentence in half.
Why sentences are a useful unit
Fixed-size chunking cuts at a word or character count, so a boundary often lands in the middle of a sentence. The two halves are then embedded separately. Each half carries only part of the meaning, and neither retrieves well for a question about the whole sentence.
Sentence-based chunking treats the sentence as the smallest unit that can't be split. It splits the text into sentences first. Then it packs whole sentences into a chunk until a size limit is reached.
The working model
The algorithm has three steps:
- Split the text into sentences.
- Add sentences to the current chunk until the next one would exceed the limit.
- Emit the chunk, then start the next one by carrying over the last sentence or two as overlap.
A runnable implementation
The splitter below breaks after ., !, or ? when whitespace and then a capital letter, quote, or bracket follow. The chunker measures size in characters. In production you would measure tokens, as covered in the earlier chapter on token limits.
import re
def split_sentences(text):
parts = re.split(r"(?<=[.!?])\s+(?=[A-Z\"'(])", text.strip())
return [p for p in parts if p]
def chunk_sentences(text, max_chars=500, overlap_sentences=1):
sentences = split_sentences(text)
chunks, current, length = [], [], 0
for sent in sentences:
added = len(sent) + (1 if current else 0)
if current and length + added > max_chars:
chunks.append(" ".join(current))
current = current[-overlap_sentences:] if overlap_sentences else []
length = len(" ".join(current))
added = len(sent) + (1 if current else 0)
current.append(sent)
length += added
if current:
chunks.append(" ".join(current))
return chunks
text = ("Chunking splits documents. Each chunk is embedded. "
"Retrieval finds the closest chunks. The model reads them.")
for i, chunk in enumerate(chunk_sentences(text, max_chars=60), 1):
print(i, chunk)With a 60-character limit, this prints three chunks. Each shares one sentence with its neighbor:
Chunking splits documents. Each chunk is embedded.Each chunk is embedded. Retrieval finds the closest chunks.Retrieval finds the closest chunks. The model reads them.
Every chunk starts and ends on a sentence boundary. Overlap is counted in sentences, not words, so the repeated text is always a complete thought.
Trade-offs against fixed-size chunking
| Property | Fixed-size | Sentence-based |
|---|---|---|
| Chunk length | Uniform | Varies with sentence length |
| Cuts mid-sentence | Often | Never |
| Needs a sentence splitter | No | Yes |
| Risk of an oversized chunk | None | One very long sentence |
Uneven chunk lengths are usually fine for retrieval. They do make cost and latency less predictable, so set a maximum and watch the distribution.
Common errors
The regex splitter fails on text that is not plain prose.
- Abbreviations.
Dr. Smith arrived.splits afterDr.because a capital letter follows. The same happens withU.S. ArmyandFig. 3. - Decimals and versions.
Version 2.5 shipped.is safe here only because a digit follows the period. Adjust the lookahead before you allow digits. - Missing punctuation. Bullet lists, headings, table rows, and code have no sentence endings. The whole block becomes one "sentence" and may exceed your limit.
- Oversized sentences. One sentence longer than
max_charsbecomes its own chunk, and the limit is silently broken. Fall back to word-level splitting for it. - Other languages. Languages such as Chinese and Japanese use different terminators and no spaces after them. Use a language-aware library such as spaCy or NLTK.
When to choose it
Sentence-based chunking suits clean prose such as articles, reports, and transcripts. It is a small step up from fixed-size chunking and needs only a sentence splitter. For documents with headings, code, or tables, use structure-aware splitting instead. You can also combine them by splitting on structure first and packing sentences inside each section.
Exercise
In the code above, why does chunk_sentences reset length with len(" ".join(current)) after emitting a chunk, and what happens to a single sentence longer than max_chars?
Show answer
After a flush, current holds only the carried-over overlap sentences, so length must equal their joined length. Otherwise the next size check would use a stale count. A sentence longer than max_chars is still appended, because the check only triggers a flush when current is non-empty. It ends up in an oversized chunk, so you need a fallback such as splitting it by words.