Sub topic 6
Recursive splitting on natural separators
Fixed-size chunking cuts text wherever the counter runs out, even in the middle of a sentence. Recursive splitting tries to cut at natural boundaries first. It prefers paragraph breaks, then line breaks, then sentence ends, then spaces, and it falls back to a finer boundary only when a piece is still too large. This chapter assumes you know basic Python, what an embedding is, and how chunk size and overlap trade off. You will read a working splitter, trace its behavior, and learn its failure modes.
The idea
Writers group related ideas into paragraphs, and paragraphs into sections. A paragraph break is therefore a better place to cut than a random word boundary. Recursive splitting ranks separators from coarse to fine:
"\n\n"(paragraph break)"\n"(line break)". "(sentence end)" "(word boundary)- Nothing left: cut by raw character count
The algorithm splits the text on the coarsest separator that appears in it. It then packs adjacent pieces together until adding one more would exceed the size limit. Any single piece that is still too big is split again with the next finer separator. That second step is the recursion.
The implementation
This is a simplified version of the approach used by common libraries.
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)]Here is how it works, step by step:
- Early exit. Text that already fits is returned unchanged. This is also the base case of the recursion.
- Pick a separator. The loop skips separators that do not occur in the text, so the first separator it uses is the coarsest one present.
- Pack.
currentaccumulates parts, re-joined with the same separator, until the next part would push it overmax_chars. Thencurrentis emitted and a new chunk starts. Packing is what keeps chunks from becoming tiny, one-line fragments. - Recurse. If a single part is larger than the limit, it is split again with
rest, the finer separators only. The coarser separator is not tried again, because it has already been used on this text. - Last resort. If no separator applies, the final line cuts by characters.
A traced example
text = (
"Intro paragraph about cats.\n\n"
"Second paragraph. It has two sentences.\n\n"
"Third paragraph is short."
)
chunks = recursive_split(text, max_chars=70)
for c in chunks:
print(len(c), repr(c))The three paragraphs have lengths 27, 39, and 25. The splitter divides on "\n\n" and packs:
currentbecomes the first paragraph (27 characters).- Adding the second gives 27 + 2 (separator) + 39 = 68, which is at most 70. They merge.
- Adding the third would give 68 + 2 + 25 = 95, which is over the limit. The merged chunk is emitted and the third paragraph starts a new chunk.
The output has two chunks, of lengths 68 and 25. No sentence was cut. With max_chars=50, the first two paragraphs no longer fit together (68 > 50), so each paragraph becomes its own chunk, giving lengths 27, 39, and 25.
Now a harder case: one long paragraph with no blank lines.
para = "Embeddings map text to vectors. Similar text lands nearby. " * 4
chunks = recursive_split(para.strip(), max_chars=100)
print([len(c) for c in chunks])There is no "\n\n" or "\n" in this text, so the loop falls through to ". ". The splitter packs whole sentences up to 100 characters. This is the main advantage over fixed-size chunking. The cut falls on a sentence boundary whenever the text allows it.
Behaviors to know before you rely on it
The separator is dropped between chunks
text.split(sep) removes the separator. Inside a chunk, pieces are re-joined with it, so nothing is lost. At a chunk boundary, the separator disappears. When the separator is ". ", the period at the end of a chunk goes missing. A chunk may then end with "...land nearby" instead of "...land nearby.". For embeddings this is usually harmless. If you display chunks to users or need exact text reconstruction, keep the separator by re-attaching it to the preceding piece. Libraries usually offer a keep_separator option for this.
There is no overlap
This version emits non-overlapping chunks. Overlap can be added afterward, for example by prepending the last sentence of the previous chunk. Because recursive splitting already cuts at natural boundaries, many pipelines need less overlap than with fixed-size chunking. Measure this rather than assuming it (see the evaluation chapter).
Chunks can be well under the limit
Packing is greedy and never looks ahead. If a 60-character paragraph is followed by a 480-character paragraph and the limit is 500, the first becomes its own 60-character chunk. Very short chunks embed poorly because they carry little context. Some pipelines merge chunks below a minimum size or discard them.
Length is measured in characters
max_chars is a proxy for the real limit, which is tokens. English text averages roughly four characters per token, but code, non-English text, and numbers tokenize differently. If your embedding model has a strict input limit, pass a length function that counts tokens. Libraries typically accept one. A character limit with a safety margin also works. You can replace len(...) in the function with a token counter and the logic stays the same, except for the final hard cut, which must then slice by tokens.
Separator choice must match the content
The default list suits prose. Other content needs a different list:
| Content | Useful separators, coarse to fine |
|---|---|
| Plain prose | paragraph break, line break, sentence end, space |
| Markdown | heading markers, blank line, line break, sentence end, space |
| Python source | `"\nclass "`, `"\ndef "`, `"\n\n"`, `"\n"`, space |
| Chinese or Japanese text | `"\n\n"`, `"\n"`, `"。"`, `","`, empty (character) |
For languages without spaces, the " " fallback never matches. The splitter then drops to the character cut, so add the language's own punctuation to the list.
Plain text separators are not real structure
A blank line inside a code block, a table row, or a numbered list can look like a paragraph break. The splitter has no idea that a table header and its rows belong together. For documents with meaningful structure, use a structure-aware splitter (covered in a later chapter). You can also use recursive splitting only to subdivide oversized sections that the structural pass produced.
Inspecting your output
Never trust a splitter you have not looked at. A quick check prints the size distribution and a few chunk edges:
def describe(chunks):
sizes = sorted(len(c) for c in chunks)
print("count:", len(chunks))
print("min / median / max:", sizes[0], sizes[len(sizes) // 2], sizes[-1])
for c in chunks[:3]:
print("START:", repr(c[:40]), "| END:", repr(c[-40:]))
describe(recursive_split(text, max_chars=70))Look for these signs:
- Many chunks far below the limit suggest greedy packing leaving gaps. Raise the limit or merge small chunks.
- Chunks that end mid-sentence suggest the separator list does not match the text.
- A max size that equals the limit exactly, repeated many times, suggests the character cut is firing too often.
When to choose recursive splitting
Recursive splitting is a strong default for mixed or unknown prose. It is cheap, deterministic, and needs no model calls, and it costs little more than fixed-size chunking while avoiding most mid-sentence cuts. It is less suitable when documents have strong structure that should define the chunks (use headings or HTML tags), or when topic shifts do not align with paragraph breaks (consider semantic chunking). Whichever you pick, compare it against a baseline on your own questions, as described in the evaluation chapter.
Exercise
Using the recursivesplit function above with maxchars=40, you pass a text made of one paragraph with no newlines: "Cats sleep a lot. Dogs bark at night. Birds sing early." (55 characters). Which separator does the splitter end up using, and what are the resulting chunks?
Show answer
The text is over 40 characters, and "\n\n" and "\n" do not appear, so they are skipped. ". " appears, so the text is split into "Cats sleep a lot", "Dogs bark at night", and "Birds sing early." (the periods that were part of ". " are dropped, but the final period stays because it is not followed by a space). Packing: "Cats sleep a lot" (16) plus ". " plus "Dogs bark at night" (18) is 16 + 2 + 18 = 36, which fits. Adding "Birds sing early." (17) would give 36 + 2 + 17 = 55, over 40. The result is two chunks: "Cats sleep a lot. Dogs bark at night" and "Birds sing early.". The first chunk lost its final period, which shows the dropped-separator behavior.
Exercise
Why does the function recurse with rest (the finer separators only) rather than with the full separator list when a single part is too large?
Show answer
The part was produced by splitting on a separator that is already in use, so it no longer contains that separator, and retrying the coarser ones would find nothing or repeat work. Passing only the finer separators makes each recursion level strictly finer. This guarantees the recursion ends, because the list shrinks until the final character cut handles whatever remains.