Chunk text by sentences under a token budget
Why it matters Chunking quality is one of the biggest levers on RAG answer accuracy.
Good RAG chunks do not cut sentences in half.
Write sentence_chunks(text, max_words, overlap). Split text into sentences after '.', '!' or '?' followed by whitespace (use re.split(r"(?<=[.!?])\s+", text.strip())). Greedily add sentences to the current chunk while the word count stays <= max_words. When the next sentence would exceed it, close the chunk and start the next one with the last `overlap` sentences of the closed chunk (as long as that leaves room; drop overlap sentences from the front until the new sentence fits). A single sentence longer than max_words becomes its own chunk. Return chunks as strings joined with single spaces.
def sentence_chunks(text, max_words, overlap)Example
sentence_chunks("A b. C d. E f.", 4, 0) is ["A b. C d.", "E f."].
Understand the idea
A RAG chunk that cuts a sentence in half loses meaning, so this chunker treats sentences as unbreakable blocks. It fills a chunk with whole sentences up to a word budget. When the next sentence does not fit, it closes the chunk and starts the next one with the last few sentences repeated, so a fact near a boundary appears in both. Worked example: 'A b c. D e. F g h. I j.' with max_words 5, overlap 1. Sentences have 3, 2, 3 and 2 words. Chunk 1: 'A b c.' plus 'D e.' is 5 words. 'F g h.' would make 8, so close it. Chunk 2 starts with 'D e.' (overlap) and adds 'F g h.' for 5 words. 'I j.' would make 7, so close it. Chunk 3 is 'F g h. I j.'. Rule: split with the given regex; add sentences while the total stays <= max_words; on overflow, close the chunk, seed the next with the last overlap sentences, then drop seed sentences from the front until the new sentence fits; a single sentence over budget is its own chunk. Join with single spaces. Used in: preparing documents for embedding and retrieval.