Chunking with Overlap

Split a long text into pieces small enough to embed and retrieve, overlapping so no fact is cut in half.

AI · intermediate · 6 min · 21 steps · free

What you'll learn

chunking.py

def chunk(words, size, overlap):
    chunks = []
    start = 0
    while start < len(words):
        chunks.append(' '.join(words[start:start + size]))
        start += size - overlap
    return chunks

text = 'returns are free for thirty days if the item is unused and still in its box'
pieces = chunk(text.split(), 6, 2)
print(len(pieces), pieces)

Step by step

  1. Python defines the function chunk(). Its body does not run yet: it runs each time the function is called.
  2. text is created with the value 'returns are free for thirty days if the item is unused and still in its box'.
  3. Python calls chunk(), with words = ['returns', 'are', 'free', 'for', 'thirty', 'days', 'if', 'the', …], size = 6 and overlap = 2. It gets its own names.
  4. chunks is created and points to a new list: [].
  5. start is created with the value 0.
  6. start < len(words) is true, so the loop body runs.
  7. The first chunk: words 0 to 5.
  8. The next chunk starts at 6 - 2 = 4, not 6: two words overlap.
  9. start < len(words) is true, so the loop body runs.
  10. "thirty days" appears in both chunks, so the fact "free for thirty days" is not split away from its context.
  11. start changes from 4 to 8.
  12. start < len(words) is true, so the loop body runs.
  13. 'item is unused and still in' is added to the end of the list that chunks points to.
  14. start changes from 8 to 12.
  15. start < len(words) is true, so the loop body runs.
  16. 'still in its box' is added to the end of the list that chunks points to.
  17. start changes from 12 to 16.
  18. start < len(words) is false, so the loop ends.
  19. The function returns chunks.
  20. Four overlapping chunks, ready to embed.
  21. It prints 4 ['returns are free for thirty days', 'thirty days if the item is', 'item is unused and still in', 'still in its box'].

Common mistakes

Best practices

Key takeaways

Check yourself

size 6, overlap 2: chunk starts?

Answer: 0, 4, 8, 12

Overlap 0 risks?

Answer: Cutting a fact in two

·

More in Retrieval