Recursive Text Splitting Explained (With a Python Implementation)
Recursive splitting cuts text using a ranked list of separators. It first tries to split on the largest natural boundary (blank lines between paragraphs). If a piece is still too long, it splits that piece on the next boundary (single newlines), then sentences, then words, and as a last resort characters. The result is chunks under your size limit that break at the most natural place available.
The idea
Fixed-size windows cut blindly. Structure splitting needs headings that may not exist. Recursive splitting sits between them. It needs no markup and respects natural breaks as far as the size limit allows. This is why it is the default splitter in many frameworks and a good general-purpose choice.
The algorithm has four steps.
- Take the first separator in the list, for example a blank line.
- Split the text on it. Pieces that already fit the limit are kept.
- For any piece that is too long, repeat with the next separator in the list.
- Merge neighbouring small pieces back together, up to the limit, so you do not end up with many tiny chunks.
A compact implementation
This version measures size in characters to keep the code short. The next post replaces that with tokens. It does not add overlap, to keep the idea clear.
SEPARATORS = ["\n\n", "\n", ". ", " ", ""]
def recursive_split(text: str, max_chars: int = 800, seps=SEPARATORS) -> list[str]:
if len(text) <= max_chars:
return [text]
sep, rest = seps[0], seps[1:]
if sep == "":
# last resort: hard cut
return [text[i:i + max_chars] for i in range(0, len(text), max_chars)]
parts = text.split(sep)
pieces = []
for i, part in enumerate(parts):
piece = part + (sep if i < len(parts) - 1 else "")
if len(piece) > max_chars:
pieces.extend(recursive_split(piece, max_chars, rest))
else:
pieces.append(piece)
# merge small neighbours
chunks, current = [], ""
for p in pieces:
if len(current) + len(p) <= max_chars:
current += p
else:
if current:
chunks.append(current.strip())
current = p
if current:
chunks.append(current.strip())
return [c for c in chunks if c]
sample = ("Paragraph one is short.\n\n" +
"Paragraph two is much longer. " * 40)
for chunk in recursive_split(sample, max_chars=300):
print(len(chunk), chunk[:40].replace("\n", " "))
The first paragraph stays whole because it fits. The long second paragraph cannot be split on blank lines, so the function falls to the next separators and ends up splitting between sentences. Each chunk stays at or under 300 characters.
Using LangChain's splitter
You do not have to maintain this yourself. The langchain-text-splitters package provides RecursiveCharacterTextSplitter, which adds overlap and several options. Install it with pip install langchain-text-splitters.
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=800,
chunk_overlap=100,
separators=["\n\n", "\n", ". ", " ", ""],
)
chunks = splitter.split_text(long_text)
print(len(chunks), "chunks")
By default chunk_size counts characters. The class also has helper constructors that count tokens with a tokenizer, so you can size chunks to match an embedding model. Check the package documentation for the current options before relying on a specific helper.
Customize the separators
The separator list is the main tuning knob. Adapt it to your content.
- Markdown: start with heading markers such as a newline followed by
##, then blank lines, then lines. - Code: use class and function keywords as separators so you split between definitions rather than in the middle of them.
- Chinese or Japanese: include full-width sentence marks as separators since spaces are not word boundaries.
- Legal text: use section markers such as "Article" or numbered clause patterns first.
Strengths and weaknesses
Recursive splitting is simple, fast and works on any text, which makes it an excellent baseline. Its weakness is that it does not understand meaning. It will split between two sentences that belong together if they happen to exceed the limit, and it can keep two unrelated paragraphs in one chunk if both are short. For documents with clear headings, a structure-first approach followed by recursive splitting only for oversized sections gives better results than recursion alone.
Practical advice
- Pick the chunk size after reading your embedding model's input limit.
- Use overlap of 10 to 15 percent as a starting value, and test whether removing it hurts.
- Print a dozen chunks and read them, particularly the ones near the size limit.
- Keep the heading or title next to each chunk as metadata so it is not lost when the splitter ignores structure.
Start with recursive splitting if you do not know your content well. Move to structure-aware or semantic strategies when evaluation shows that boundaries are costing you answers.
Comments
No comments yet. Have a question or a tip? Be the first to share it.