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
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)chunk(). Its body does not run yet: it runs each time the function is called.text is created with the value 'returns are free for thirty days if the item is unused and still in its box'.chunk(), with words = ['returns', 'are', 'free', 'for', 'thirty', 'days', 'if', 'the', …], size = 6 and overlap = 2. It gets its own names.chunks is created and points to a new list: [].start is created with the value 0.start < len(words) is true, so the loop body runs.start < len(words) is true, so the loop body runs.start changes from 4 to 8.start < len(words) is true, so the loop body runs.chunks points to.start changes from 8 to 12.start < len(words) is true, so the loop body runs.chunks points to.start changes from 12 to 16.start < len(words) is false, so the loop ends.chunks.4 ['returns are free for thirty days', 'thirty days if the item is', 'item is unused and still in', 'still in its box'].Answer: 0, 4, 8, 12
Answer: Cutting a fact in two
← Embeddings and Cosine Similarity · A Tiny Vector Store →