Split a document into overlapping chunks
RAG pipelines cut documents into chunks before embedding. Overlap between neighbours stops a sentence from being cut in half with no context.
Write chunk_tokens(tokens, size, overlap) that returns a list of chunks (lists). Each chunk starts size - overlap tokens after the previous one. Stop once a chunk reaches the end of the tokens, so the last chunk may be shorter, and never emit a chunk that is entirely contained in the previous one. Assume 0 <= overlap < size. An empty input gives [].
def chunk_tokens(tokens, size, overlap)Understand the idea
Before embedding, RAG pipelines cut long documents into chunks. Neighbouring chunks share a few tokens of overlap so a sentence cut at a boundary still has context on both sides. Like photocopying a long page in pieces with a little overlap so no line is lost. Each new chunk starts size - overlap tokens after the previous one, and you stop as soon as a chunk reaches the end, so the last chunk can be shorter. Worked example: 10 tokens numbered 0 to 9, size 4, overlap 1, so the step is 3. Chunks: [0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9]. The third chunk touches the end, so stop. With 8 tokens: [0..3], [3..6], [6, 7], then stop. Continuing would produce a chunk like [9] that is already inside the previous chunk. Rule: start = 0, 3, 6, ... (step = size - overlap); chunk = tokens[start : start + size]; stop after the chunk whose end reaches len(tokens). Empty input gives []. Every RAG ingestion pipeline has a chunker like this.