Sub topic 6
Recursive splitting on natural separators
This chapter assumes you can read basic Python and know what a chunk is, from the earlier chapters on chunk size and fixed-size chunking.
The idea
Fixed-size chunking cuts at a number, whether or not the text is at a sentence or paragraph boundary. Recursive splitting tries to cut at natural boundaries first. It uses a list of separators ordered from coarse to fine:
- Paragraph breaks (
"\n\n") - Line breaks (
"\n") - Sentence ends (
". ") - Spaces (
" ")
The splitter tries the coarsest separator first. It packs the resulting pieces into chunks up to a size limit. Only a piece that is still too large is split again, using the next finer separator. Most chunks end up as whole paragraphs or sentences, and words are cut only as a last resort.
The implementation
def recursive_split(text, max_chars=500, separators=("\n\n", "\n", ". ", " ")):
if len(text) <= max_chars:
return [text]
for i, sep in enumerate(separators):
if sep not in text:
continue
rest = separators[i + 1:]
chunks, current = [], ""
for part in text.split(sep):
candidate = part if not current else current + sep + part
if len(candidate) <= max_chars:
current = candidate
continue
if current:
chunks.append(current)
current = ""
if len(part) > max_chars:
chunks.extend(recursive_split(part, max_chars, rest))
else:
current = part
if current:
chunks.append(current)
return chunks
return [text[i:i + max_chars] for i in range(0, len(text), max_chars)]The function works in four steps:
- Base case. Text that already fits is returned unchanged.
- Separator choice. The loop picks the first separator that actually occurs in the text, so a document with no blank lines falls through to the next one.
- Packing. Neighbouring pieces are joined back together with the same separator while they fit. This avoids a stream of tiny chunks, one per short paragraph.
- Recursion. An oversized piece is split again with only the finer separators in
rest.
If no separator is found, the last line cuts the text at fixed character positions. This is the final fallback, and it matters for strings such as long URLs or minified data.
Running it
text = "Intro paragraph.\n\nSecond paragraph is here.\n\nThird."
for chunk in recursive_split(text, max_chars=30):
print(len(chunk), repr(chunk))With a 30-character limit, the first two paragraphs together would be 43 characters, so they stay apart. The second and third would be 33, so they also stay apart. You get three chunks, each a whole paragraph. Raise max_chars to 50 and the first two paragraphs merge.
Behaviour to know about
- No overlap. This version does not repeat text between chunks. If you need overlap, add it after splitting by prepending the tail of the previous chunk, or use a library splitter that supports it.
- Separators are dropped at chunk edges. The separator is kept inside a chunk when pieces are merged, but it disappears where one chunk ends and the next begins. That is usually fine for prose.
- Chunks vary in size. A short final paragraph produces a short chunk. Very small chunks embed poorly, so consider merging any chunk below a minimum length into its neighbour.
- The sentence separator is crude.
". "misses sentences ending in?or!, and it splits after abbreviations such as "e.g. ". Treat it as a fallback, not a sentence detector. - Separators should fit the content. For source code, use separators such as
"\nclass ","\ndef ", and"\n\n". For Markdown, put heading markers first. Libraries like LangChain ship this asRecursiveCharacterTextSplitter, with language-specific presets.
Exercise
Exercise
A document has no blank lines, but it has single newlines between lines of 80 characters each. You call recursivesplit with maxchars=200 and the default separators. Which separator does the function use for the first split, and roughly how many lines end up in each chunk?
Show answer
The function skips "\n\n" because it does not occur in the text, and splits on "\n". Lines are packed together while the joined length stays at or below 200 characters. Two lines with a newline are 161 characters, and three would be 242, so each chunk holds two lines.