Sub topic 7
Sentence-based chunking
What this chapter covers
This chapter assumes you know basic Python, what an embedding is, and how a retrieval-augmented generation (RAG) pipeline retrieves chunks and then generates an answer. It also assumes you have read the chapters on chunk size and overlap and on fixed-size chunking.
Sentence-based chunking treats the sentence as the smallest unit that is never cut. You split the text into sentences first. Then you pack whole sentences into chunks until a size limit is reached. The chunk boundaries always fall between sentences.
Why sentence boundaries help
A fixed-size chunker counts words or characters and cuts wherever the count runs out. That often splits a sentence in half. Take the sentence "The refund window is 30 days, but only for unopened items." If a chunk ends after "30 days," the first chunk says refunds last 30 days and the second chunk starts with a fragment about unopened items. A query about refunds on opened items may retrieve the first chunk, and the exception is lost.
Sentence packing removes that failure for single sentences. Each chunk reads as complete text, which has two effects:
- The embedding of a chunk represents whole statements, not a statement cut in the middle.
- When you show the chunk to a language model or a user, it starts and ends cleanly.
Sentence boundaries do not fix every problem. A claim often spans several sentences, such as a rule followed by its exception. Sentence packing keeps each sentence intact but can still put a rule and its exception in different chunks. Overlap in whole sentences reduces that risk without removing it.
Step 1: splitting text into sentences
The obvious approach is to split on ., !, and ?. It fails on text that contains periods that do not end a sentence:
- Abbreviations: "Dr. Lee", "e.g.", "vs."
- Decimals and versions: "3.5 mm", "v2.1.0"
- File names and URLs: "config.yaml", "example.com"
- Initials: "J. R. R. Tolkien"
A small rule-based splitter can handle the common cases. It looks for sentence-ending punctuation, optional closing quotes or brackets, whitespace, and then a character that can start a sentence. It skips a boundary when the word before the period is a known abbreviation.
import re
ABBREVIATIONS = {
"mr", "mrs", "ms", "dr", "prof", "sr", "jr", "vs", "etc",
"e.g", "i.e", "fig", "inc", "approx",
}
BOUNDARY = re.compile(r'([.!?]+)(["\')\]]*)\s+(?=[A-Z0-9"\'(\[])')
def split_sentences(text):
text = re.sub(r"\s+", " ", text).strip()
if not text:
return []
sentences = []
start = 0
for m in BOUNDARY.finditer(text):
piece = text[start:m.end(2)]
last_word = piece.split()[-1].rstrip(".!?\"')]").lower()
if m.group(1) == "." and last_word in ABBREVIATIONS:
continue
sentences.append(piece)
start = m.end()
tail = text[start:]
if tail:
sentences.append(tail)
return sentencesThe splitter first collapses all whitespace, including newlines, into single spaces. That is convenient for prose and harmful for text where line breaks carry meaning, such as lists and code. The gotchas section below returns to this.
The decimal "3.5" never matches the boundary pattern because no whitespace follows the period. "Dr. Lee" matches the pattern, but the abbreviation check skips it.
When to use a library instead
A hand-written splitter is fine for clean English prose, and it is easy to read and debug. For messier or multilingual text, use a tested library. NLTK's punkt tokenizer learns abbreviations from data. spaCy's sentence segmenter uses a parser or a rule-based component. pysbd is a rule-based segmenter that covers many languages. Whichever you choose, run it on a sample of your own documents and read the output. Sentence splitters are tuned on news-like text, and domain text such as legal citations, medical notes, or chat logs often breaks them.
Step 2: packing sentences into chunks
Once you have sentences, the chunker is a loop. It adds sentences to the current chunk while the chunk stays within the limit. When the next sentence would exceed the limit, it emits the chunk and starts a new one. For overlap, the new chunk begins with the last few sentences of the previous chunk.
def chunk_sentences(text, max_chars=500, overlap_sentences=1):
sentences = split_sentences(text)
chunks = []
current = []
length = 0
for s in sentences:
added = len(s) + (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))
if current and length + 1 + len(s) > max_chars:
current = []
length = 0
added = len(s) + (1 if current else 0)
current.append(s)
length += added
if current:
chunks.append(" ".join(current))
return chunks
sample = (
"Dr. Lee ran the test. It passed on the first try! "
"Why did it pass? The cache was warm. Cold runs failed twice."
)
for i, chunk in enumerate(chunk_sentences(sample, max_chars=60)):
print(i, chunk)Running this prints:
0 Dr. Lee ran the test. It passed on the first try!
1 It passed on the first try! Why did it pass?
2 Why did it pass? The cache was warm. Cold runs failed twice.Three details in the code matter:
current[-overlap_sentences:]would return the whole list ifoverlap_sentenceswere 0, so the code guards that case explicitly.- If the carried-over sentences plus the new sentence exceed the limit, the code drops the overlap. Without this check, a long sentence could produce an oversized chunk made mostly of repeated text.
- A single sentence longer than
max_charsbecomes its own chunk. The function does not cut it. That keeps the "never split a sentence" promise, but the chunk may exceed the limit.
Counting tokens instead of characters
The example counts characters because that keeps it short. Embedding models limit input in tokens, not characters. In production, replace len(...) with a token counter from the tokenizer that matches your embedding model, and set max_chars to a token budget below the model's input limit. The chapter on tokens and input limits explains why the counts differ.
Sentence overlap versus word overlap
The fixed-size chunker repeats a fixed number of words. Sentence-based chunking repeats whole sentences, so the overlap is always readable.
| Property | Word overlap (fixed-size) | Sentence overlap |
|---|---|---|
| Unit repeated | A set number of words | A set number of sentences |
| Repeated text starts mid-sentence | Often | Never |
| Size of overlap | Predictable | Varies with sentence length |
| Chunk size | Nearly constant | Varies, within the limit |
| Risk with long sentences | None | Overlap may be dropped or chunk may exceed the limit |
Because sentence lengths vary, the overlap in characters is not constant. One short sentence of overlap may be 30 characters, and one long sentence may be 400. If you need a stable overlap size, set the overlap as a character or token budget and carry over as many whole sentences as fit within it.
Edge cases and gotchas
- Text without punctuation. Subtitles, chat logs, and OCR output often lack terminal punctuation. The splitter returns one huge "sentence". Add a fallback that splits on newlines or on a size limit, as the recursive splitter does.
- Very long sentences. Legal and academic text can have sentences of several hundred words. A hard limit on chunk size needs a fallback that splits such a sentence at commas, semicolons, or spaces.
- Very short sentences. Headings, labels, and one-word replies produce tiny chunks that embed poorly. Packing several sentences per chunk avoids this, which is one reason to pack toward a target size instead of using one sentence per chunk.
- Abbreviation lists are language-specific. The set above works for English. A word like "no." can end a sentence ("The answer is no.") or be an abbreviation for "number", so it is left out of the list on purpose.
- Quotes and brackets. A period inside closing quotes ends the sentence only if the quote closes after it. The pattern above handles the common case and misses nested or unusual quoting.
- Lowercase starts. The pattern requires the next sentence to start with an uppercase letter, digit, quote, or bracket. Text that begins sentences in lowercase, or languages without capitalisation, needs a different splitter.
When sentence-based chunking is a good choice
Use it when your documents are mostly clean prose: articles, support answers, reports, book chapters, and transcripts that have been punctuated. It is cheap, deterministic, and easy to inspect. It also improves the readability of retrieved chunks, which matters when users see the source passages.
It is a weaker choice when structure carries meaning. For Markdown, HTML, code, and tables, split on structure first and apply sentence packing only inside prose sections. For documents where topics shift without clear signals, semantic chunking may find better boundaries, at the cost of extra embedding calls.
Sentence packing can also feed other strategies. The recursive splitter's last separator before single words is often ". ", which is a rough sentence split. A parent-child setup can use single sentences or small groups as the searchable child chunks and return the surrounding section as the parent.
Checking that it helps
Do not assume sentence boundaries improve retrieval for your data. Build a small set of test questions with known source passages, run each chunker with comparable chunk sizes, and compare recall@k. Compare chunkers at the same average chunk size, because a change in size alone can explain a difference in results. Also read a sample of the chunks. A splitter that wrongly breaks on "Fig." or on a citation such as "Smith et al. (2020)" shows up in a few minutes of reading.
Exercise
The chunk_sentences function is called with max_chars=100 and overlap_sentences=2 on text whose sentences are each about 80 characters long. What chunks do you get, and what does this show about overlap measured in sentences?
Show answer
Each chunk holds one sentence. Two 80-character sentences already exceed 100 characters, so a chunk can never contain more than one. When a chunk is emitted, the carried-over sentences plus the next sentence would exceed the limit, so the code drops the overlap. The result is no overlap at all, even though overlap_sentences=2 was requested. This shows that sentence overlap is a request that the size limit can override. If you need overlap, raise max_chars to hold at least three sentences, or measure overlap as a budget in characters or tokens.
Exercise
Give one input where split_sentences returns a wrong boundary, and describe a change to the code that would fix it.
Show answer
One example is "See Fig. 3 for details. The next step follows." The word "fig" is in the abbreviation set, so this case works. A failing example is "Smith et al. Wrote the report." The word "al" is not in the set, so the splitter ends a sentence after "et al." and starts a new one at "Wrote". The fix is to add "al" to ABBREVIATIONS. A more general fix is to use a trained segmenter such as NLTK's punkt or pysbd, then check its output on a sample of your documents.