Chunking: Cutting Documents for Retrieval

A long document is cut into overlapping chunks, and only the chunk that matches the question goes into the prompt.

AI · beginner · 8 min · 19 steps · free

What you'll learn

chunking.py

# Long documents are cut into chunks, so retrieval can find just the part that answers.
doc = "our shop opens at 9 am . returns are free for 30 days . we ship to india and nepal . gift cards never expire"
words = doc.split(" ")
size, overlap = 8, 2

chunks = []
for start in range(0, len(words), size - overlap):
    chunks.append(" ".join(words[start:start + size]))

question = "do gift cards expire"
scores = [len(set(question.split(" ")) & set(c.split(" "))) for c in chunks]
best = chunks[scores.index(max(scores))]
print(best)

Step by step

  1. A shop's help page: four facts in one long text.
  2. Split into words: 25 in all.
  3. Chunks of 8 words, each overlapping the previous one by 2.
  4. chunks is created and points to a new list: [].
  5. Chunk starts step forward by 8 − 2 = 6 words: 0, 6, 12, 18, 24.
  6. Words 0 to 7.
  7. start changes from 0 to 6.
  8. Words 6 to 13: it repeats ". returns", the overlap.
  9. start changes from 6 to 12.
  10. 'days . we ship to india and nepal' is added to the end of the list that chunks points to.
  11. start changes from 12 to 18.
  12. Words 18 to 25: this one contains the gift card fact.
  13. start changes from 18 to 24.
  14. A last small chunk with the final word.
  15. Python moves to the next item of the loop: for start in range(0, len(words), size - overlap).
  16. The question.
  17. Score every chunk by how many question words it shares (& is set intersection). The gift card chunk scores 3.
  18. best is created with the value 'and nepal . gift cards never expire'.
  19. Only this chunk goes into the prompt: short, and it holds the answer. Real systems compare embeddings instead of counting words, and often send the top few chunks.

Common mistakes

Best practices

Key takeaways

Check yourself

Chunks of 10 words with an overlap of 3. How far apart do chunks start?

Answer: 7 words. Each chunk starts size − overlap = 7 words after the previous one.

Why not put the whole document in the prompt?

Answer: It may not fit, costs more, and buries the answer. Retrieving just the relevant chunk keeps the prompt small and focused.

·

More in Building with Models