The idea
Long documents are cut into windows before they are embedded or sent to a model, because both have a length limit. token_windows slides a window of size tokens along the list and moves it forward by size - overlap each time, so neighbouring windows share overlap tokens. A sentence that straddles a boundary then stays whole in at least one window.
Two details make it correct. Each window is returned with its start index, so a later citation can point back to the exact place in the document. The loop also stops as soon as a window reaches the end. The tail is covered once, and no extra window is emitted that would only repeat tokens already seen.
How it works
- Require
size and overlap to be real integers with size > 0 and 0 <= overlap < size, otherwise raise ValueError. - Begin with
start = 0 and an empty result; an empty token list returns []. - Append
(start, list(tokens[start:start + size])); the slice is shorter if the document ends first. - Stop when
start + size >= len(tokens), because this window already reached the end. - Otherwise advance
start by size - overlap and repeat.
What it costs
- Windows
- ≈ n / (size - overlap)
- Time
- O(windows · size)
- Space
- O(windows · size)
Each window copies up to size tokens, so overlap multiplies storage: with overlap at half of size, every token is stored about twice.
Where it is used
- LangChain's
RecursiveCharacterTextSplitter takes chunk_size and chunk_overlap parameters for splitting documents before embedding. - Hugging Face tokenizers return overlapping windows of a long text when called with
return_overflowing_tokens=True and a stride. - LlamaIndex's
SentenceSplitter splits documents into nodes using a chunk_size and a chunk_overlap.
Watch out for
- Looping with
range(0, len(tokens), size - overlap) and no early stop, which emits a last window made only of tokens already covered. - Allowing
overlap == size: the step becomes zero and the loop never ends. - Returning windows without their
start, so a chunk can no longer be mapped back to its position in the source.