Search Tutorials
--Ads--Fixed-Size, Recursive and Token-Based Chunking
The three baseline chunking methods every RAG system starts with.
Fixed-size chunking splits text into pieces of roughly equal length. It is simple, fast and predictable, and it is the baseline that every other strategy is compared against. This lesson implements three variants: character-based, recursive and token-based.
Overlap
All three variants usually use overlap: each chunk repeats the last part of the previous one. If an important sentence falls on a boundary, overlap makes sure it appears complete in at least one chunk. An overlap of 10 to 20% of the chunk size is a common default.
1. Character-based chunking
The simplest approach: take a window of N characters, then move forward by N minus the overlap.
def char_chunks(text: str, size: int = 1000, overlap: int = 150) -> list[str]:
if overlap >= size:
raise ValueError("overlap must be smaller than size")
step = size - overlap
return [text[i:i + size] for i in range(0, len(text), step) if text[i:i + size].strip()]
Its weakness is obvious: it cuts through words and sentences. Use it only for quick experiments.
2. Recursive chunking
Recursive chunking keeps natural units together. It tries to split on the "largest" separator first (blank lines between paragraphs), and only falls back to smaller separators (line breaks, sentence ends, spaces) for pieces that are still too long. This is the strategy behind LangChain's popular RecursiveCharacterTextSplitter, and it is a strong default.
SEPARATORS = ("\n\n", "\n", ". ", " ")
def recursive_split(text: str, max_chars: int = 1000, separators=SEPARATORS) -> list[str]:
"""Split on the largest separator that keeps pieces under max_chars."""
if len(text) <= max_chars:
return [text]
for i, sep in enumerate(separators):
if sep in text:
break
else: # no separator left: hard cut
return [text[j:j + max_chars] for j in range(0, len(text), max_chars)]
smaller = separators[i + 1:]
chunks, current = [], ""
for piece in text.split(sep):
candidate = f"{current}{sep}{piece}" if current else piece
if len(candidate) <= max_chars:
current = candidate # keep growing the current chunk
continue
if current:
chunks.append(current)
if len(piece) > max_chars: # piece itself too long: split it further
chunks.extend(recursive_split(piece, max_chars, smaller))
current = ""
else:
current = piece
if current:
chunks.append(current)
return chunks
def add_overlap(chunks: list[str], overlap: int = 150) -> list[str]:
"""Prefix each chunk with the tail of the previous one, starting at a word boundary."""
result = chunks[:1]
for prev, chunk in zip(chunks, chunks[1:]):
tail = prev[-overlap:]
tail = tail[tail.find(" ") + 1:] if " " in tail else tail
result.append(f"{tail} {chunk}")
return result
text = open("docs/leave-policy.txt", encoding="utf-8").read()
for i, chunk in enumerate(add_overlap(recursive_split(text, max_chars=300), overlap=60)):
print(f"--- chunk {i} ({len(chunk)} chars)\n{chunk}\n")
3. Token-based chunking
Characters are only a proxy for what really matters: tokens. Embedding models have token limits (512 tokens for bge-small-en-v1.5), so it is safer to measure chunk size with the embedding model's own tokenizer.
from rag_helpers import get_embedder
tokenizer = get_embedder().tokenizer # the tokenizer of the embedding model
def token_chunks(text: str, max_tokens: int = 256, overlap: int = 32) -> list[str]:
ids = tokenizer.encode(text, add_special_tokens=False)
step = max_tokens - overlap
return [tokenizer.decode(ids[i:i + max_tokens]) for i in range(0, len(ids), step)]
def count_tokens(text: str) -> int:
return len(tokenizer.encode(text, add_special_tokens=False))
Pure token windows cut mid-sentence just like character windows. The best of both is to split recursively and measure length in tokens: pass a length function to your splitter instead of using len().
def recursive_split_tokens(text: str, max_tokens: int = 256) -> list[str]:
# Approximate: recursive split by characters, then check token counts and re-split
chunks = []
for chunk in recursive_split(text, max_chars=max_tokens * 4):
if count_tokens(chunk) <= max_tokens:
chunks.append(chunk)
else:
chunks.extend(recursive_split(chunk, max_chars=max_tokens * 2))
return chunks
If a chunk is longer than the embedding model's maximum sequence length, the extra text is dropped without an error. Check get_embedder().max_seq_length and make sure your chunks fit.
Using a library instead
If you already use LangChain, its splitter does the same job:
# pip install langchain-text-splitters
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
chunks = splitter.split_text(text)
Choosing the parameters
| Parameter | Starting value | Increase when | Decrease when |
|---|---|---|---|
| Chunk size | 800–1,200 characters (~200–300 tokens) | Answers need more surrounding context | Retrieved chunks contain lots of irrelevant text |
| Overlap | 10–20% of chunk size | Facts are often split across boundaries | Duplicated text crowds the top results |
Use the method in Evaluating Chunking Strategies to pick values with data rather than guesswork.
Key takeaways
- Overlap protects information that falls on chunk boundaries.
- Recursive splitting keeps paragraphs and sentences intact and is a strong default.
- Measure chunk length in the embedding model's tokens to avoid silent truncation.
- Start around 200–300 tokens with 10–20% overlap, then tune with an evaluation.