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
Split a document into fixed-size chunks with overlap
Score chunks against a question
Explain why overlap helps
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
A shop's help page: four facts in one long text.
Split into words: 25 in all.
Chunks of 8 words, each overlapping the previous one by 2.
Words 6 to 13: it repeats ". returns", the overlap.
start changes from 6 to 12.
'days . we ship to india and nepal' is added to the end of the list that chunks points to.
start changes from 12 to 18.
Words 18 to 25: this one contains the gift card fact.
start changes from 18 to 24.
A last small chunk with the final word.
Python moves to the next item of the loop: for start in range(0, len(words), size - overlap).
The question.
Score every chunk by how many question words it shares (& is set intersection). The gift card chunk scores 3.
best is created with the value 'and nepal . gift cards never expire'.
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
Chunks so small they lose meaning, or so big they waste the context window
No overlap, so an answer split across two chunks is lost
Best practices
Split on natural boundaries (paragraphs, sentences) where possible, with a little overlap
Key takeaways
Long documents are split into chunks before retrieval.
Chunks overlap a little so facts on a boundary are not cut in half.
Each chunk is scored against the question; the best go into the prompt.
Chunk size is a balance between enough context and too much text.
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.