AI Hints
Home›RAG Tutorial›Smarter Splitting
RAG · Lesson 19 of 120

Recursive Splitting

Paragraphs first.

⏱ 2 min read▶ Video at 18:45🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

A smarter splitter tries to cut in natural places. First between paragraphs. If a piece is still too big, between lines. Then between sentences, then words. That's recursive splitting, and it's the most popular choice.

Recursive Splitting
From the video: Recursive Splitting
  • Paragraphs first
  • Then lines
  • Then words

The recursive splitter

Recursive character text splitter takes a chunk size and an overlap. Split text returns the pieces. We split the returns page with a size of two hundred. Run it. Every chunk ends at a natural break, so no sentence is cut in half.

recursive.pypython
from pathlib import Path
from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=0)
text = Path("data/rag/northwind/returns.md").read_text()

for piece in splitter.split_text(text):
    print(f"{len(piece):3} | {piece[:70]!r}")
Output
 21 | '# Returns and refunds'
178 | '## Change of mind\nYou can return any unused item within 30 days of del'
101 | 'We charge a £25 collection fee to pick up a returned bike. Parts can b'
126 | '## Faulty items\nIf an item is faulty, you can return it at any time wi'
121 | '## Refund timing\nRefunds go back to the original payment method within'
 85 | 'To start a return, log in to your account, open the order, and choose '

How it decides

The splitter has a list of separators. It tries a blank line first, which separates paragraphs. Any piece still too big is split at single new lines. Then at spaces. And only as a last resort, between characters.

  1. Blank line
  2. New line
  3. Space
  4. Character
How it decides
From the video: How it decides

Summary

Recursive splitting cuts at the most natural break that keeps chunks under the size limit. Next, splitting by headings.

Key takeaways
  • Paragraphs first
  • Under the size limit
  • No half sentences
Next up: Splitting by Headings — markdown sections