Most RAG bugs I chase are not in the vector database or the prompt. They start at chunking: a chunk that ends halfway through a sentence, a section heading glued to the wrong paragraph, or a "512-token" chunk that really holds about 105 tokens.
This post shows how to use Chonkie, a small Python chunking library, to split documents for RAG. I cover the four chunkers you will use most, how to choose a tokenizer, and how to hand the chunks to an embedding model and a vector store. Every code block comes from a script I ran. Numbers are either from the Chonkie docs and README (cited) or from my own toy run (labelled).
Install
python -m venv venv && source venv/bin/activate
pip install "chonkie[tiktoken,semantic,hub]"
At the time of writing PyPI has chonkie 1.7.0 (uploaded 7 Jul 2026 UTC, MIT license, Python >= 3.10). The README says Chonkie "follows the rule of minimum installs": pip install chonkie gives you the token, sentence and recursive chunkers. Extras add the rest: [semantic] adds model2vec embeddings for SemanticChunker, [tiktoken] adds OpenAI's tokenizer, and [hub] adds the recipe loader (without it, from_recipe failed for me with No module named 'jsonschema'). The README advises against chonkie[all] in production.
Every chunker returns Chunk objects with text, start_index, end_index and token_count. Keep the indices, because they let you link a retrieved chunk back to its exact place in the source.
Pick the tokenizer first
Before choosing a chunker, decide what counts as a "token". The default tokenizer is character, so a default chunk_size is measured in characters, not model tokens. On my toy 2,134-character markdown doc:
from chonkie import TokenChunker
chunks = TokenChunker(chunk_size=512).chunk(text)
# token_count: [512, 512, 512, 512, 86] <- characters
# real o200k_base tokens: [105, 106, 107, 104, 17]
So "512 tokens" was really about 105. Pass the tokenizer your embedding model or LLM uses. The docs list character, word, byte, Hugging Face tokenizers, tiktoken and transformers, or any function str -> int.
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # pass the Encoding object
I pass the tokenizer object for a reason. With chonkie 1.7.0 and the newest tokie (0.3.0, pulled in automatically), the string form tokenizer="gpt2" failed on my box with TypeError: Tokenizer.encode() got an unexpected keyword argument 'add_special_tokens'. It worked again once I pinned tokie<0.2. Passing a tiktoken or tokenizers object avoids the problem.
The four chunkers
My toy sample is an invented router support handbook (2,134 chars, 435 o200k_base tokens, six ## sections). I used chunk_size=128 throughout so the differences show.
TokenChunker: fixed windows
from chonkie import TokenChunker
chunker = TokenChunker(tokenizer=enc, chunk_size=128, chunk_overlap=16)
chunks = chunker.chunk(text)
My run: 4 chunks, [128, 128, 128, 99] tokens. I re-counted each one with tiktoken and the numbers matched exactly. The first 16 tokens of chunk 2 matched the last 16 of chunk 1, so the overlap works. chunk_overlap also accepts a float (0.1 = 10%). The catch: 3 of 3 boundaries fell mid-sentence. Use it when you need a hard token budget and the text structure doesn't matter.
SentenceChunker: never split a sentence
from chonkie import SentenceChunker
chunker = SentenceChunker(tokenizer=enc, chunk_size=128, chunk_overlap=16)
My run: 4 chunks, [115, 120, 113, 103] tokens, 0 of 3 cut mid-sentence. It packs whole sentences up to the limit. Sentence boundaries come from delim (default ". ", "! ", "? ", "\n"), and min_characters_per_sentence defaults to 12. This is a good default for prose such as FAQs, tickets and emails.
RecursiveChunker: follow the document's structure
RecursiveChunker splits by paragraph first, then sentence, then punctuation, then whitespace, and goes down a level only when a piece is still too big. For markdown, load the recipe:
from chonkie import RecursiveChunker
chunker = RecursiveChunker.from_recipe("markdown", lang="en",
tokenizer=enc, chunk_size=128)
for c in chunker.chunk(text):
print(c.start_index, c.end_index, c.token_count, c.text[:40])
My run: 5 chunks, [82, 81, 79, 70, 123] tokens, each starting at a ## heading. The last chunk merged two short sections that fit under 128 together.
The default rules (without the recipe) also gave 5 chunks and no mid-sentence cuts. But 4 of 5 chunks ended with the next section's heading (...restore it later.\n\n## Firmware updates\n\n). The default rules attach delimiters to the previous piece (include_delim="prev"), and the markdown recipe puts headings with the following text. In a RAG index, that means the heading "Firmware updates" gets embedded with the reset instructions. Use the recipe for markdown.
SemanticChunker: split where the topic changes
from chonkie import SemanticChunker
chunker = SemanticChunker(embedding_model="minishlab/potion-base-32M",
threshold=0.8, chunk_size=128)
This chunker embeds sentences and starts a new chunk where similarity drops. The docs say it is inspired by Greg Kamradt's work, uses Savitzky-Golay filtering to smooth the similarity curve, and has skip_window to merge similar groups that are not next to each other. The defaults are threshold=0.8, similarity_window=3 and the model2vec model potion-base-32M.
My run: 9 chunks ([97, 51, 44, 49, 53, 15, 62, 13, 41]), no mid-sentence cuts, but 3 chunks ended on the next heading. The threshold changed the count a lot: 0.5 gave 7 chunks, 0.7 gave 9, and 0.9 gave 10. Two things to watch:
-
token_counthere comes from the embedding model's tokenizer, not tiktoken. Re-counted with o200k_base, the same chunks were 102, 52, 46... Sochunk_sizeis in a different unit than for the other chunkers. - The model loads on first use. The first run on my box took about 8.7 s (including the download). Later loads took 0.4 to 0.9 s.
Feed the chunks to embeddings and a vector store
Chonkie's EmbeddingsRefinery adds an embedding to each chunk (its default model is minishlab/potion-retrieval-32M):
from chonkie import EmbeddingsRefinery
import numpy as np
refinery = EmbeddingsRefinery(embedding_model="minishlab/potion-retrieval-32M")
chunks = refinery.refine(chunks) # chunk.embedding is now set (dim 512)
records = [{"id": f"routerx-{i}", "text": c.text, "start": c.start_index,
"end": c.end_index, "embedding": c.embedding} for i, c in enumerate(chunks)]
M = np.stack([r["embedding"] for r in records])
M /= np.linalg.norm(M, axis=1, keepdims=True)
v = np.asarray(refinery.embedding_model.embed("how long does a refund take"))
scores = M @ (v / np.linalg.norm(v))
On the 5 markdown-recipe chunks, "how long does a refund take" returned Billing and refunds first (cos 0.640). "my router won't boot after an update" returned Firmware updates (0.504). My toy store is a NumPy matrix. For a real database, the README lists "handshakes" for Chroma, Qdrant, pgvector, Pinecone, Weaviate, Elasticsearch, MongoDB, Milvus, LanceDB and Turbopuffer, each installed as an extra (e.g. chonkie[qdrant]). Store start_index/end_index as metadata so you can cite and highlight the source.
If you prefer chaining steps, the README shows a Pipeline (for example .chunk_with("recursive", ...) followed by .refine_with("overlap", ...) and .refine_with("embeddings", ...)).
Which chunker when
| Your content | Start with |
|---|---|
| Markdown / docs with headings | RecursiveChunker.from_recipe("markdown") |
| Plain prose, FAQs, tickets | SentenceChunker |
| Strict token budget, no structure |
TokenChunker with overlap |
| Long text with topic drift, no headings |
SemanticChunker (tune threshold) |
The README also lists Late, Code, Neural, Slumber (LLM-based), Table and Fast chunkers. I did not test those here.
Speed (toy, not a benchmark)
I ran my sample repeated 200x (426,800 chars) through each chunker on CPU. TokenChunker (512, overlap 64) took 25.7 ms, SentenceChunker 56.7 ms, and SemanticChunker 485 ms. RecursiveChunker took 1.9 ms, which is fast enough that I suspect the repeated text helped. Don't read these as benchmarks. The README's own claims are that token chunking is "33x faster than the slowest alternative", sentence chunking is "almost 2x faster" and semantic chunking is "up to 2.5x faster". BENCHMARKS.md gives the setups (100K Wikipedia articles on a Colab A100, and 500K on a GCP VM).
Gotchas
-
Default tokenizer = characters. Always set
tokenizer=. -
String tokenizer names broke with tokie 0.3.0 on my box. Pass a tokenizer object or pin
tokie<0.2. -
Overlap kwarg name. One docs example uses
OverlapRefinery(overlap_size=50), but in 1.7.0 that raisedTypeError. The parameter iscontext_size(int or float, default 0.25). Withcontext_size=16, token counts grew by 16 (82 → 98) and 4 of 5 chunks got context. - Heading placement. Use the markdown recipe or headings end up at the end of the previous chunk.
-
SemanticChunker counts with its own tokenizer and is the slowest of the four. Tune
thresholdon your own docs. - Measure retrieval, not chunk counts. Try two chunkers on real questions and compare recall@k.
Takeaway
Choose the tokenizer first, then pick the chunker that matches your document structure. Check a few chunks by eye before indexing everything. Chonkie keeps each of those steps to about one line.
How do you chunk today: fixed tokens, sentences, or by structure?
References
- Chonkie GitHub README: https://github.com/chonkie-inc/chonkie
- Chonkie on PyPI (1.7.0, MIT): https://pypi.org/project/chonkie/
- Chonkie docs, TokenChunker: https://docs.chonkie.ai/oss/chunkers/token-chunker
- Chonkie docs, SemanticChunker: https://docs.chonkie.ai/oss/chunkers/semantic-chunker
- Chonkie BENCHMARKS.md: https://github.com/chonkie-inc/chonkie/blob/main/BENCHMARKS.md
- tokie on PyPI: https://pypi.org/project/tokie/
- model2vec (potion models): https://github.com/MinishLab/model2vec
- tiktoken: https://github.com/openai/tiktoken
- Greg Kamradt, 5 Levels of Text Splitting: https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/tutorials/LevelsOfTextSplitting/5_Levels_Of_Text_Splitting.ipynb
Top comments (0)