Skip to content

< all problems121 · Level 03, RAG

Cut Where the Meaning Changes

medium · implement · RAG

Split a document where its meaning changes instead of every N words. Implement semantic_chunks(sentences, embed, percentile=90, min_size=2, max_size=8), which returns the chunks as lists of consecutive sentences, in order. embed(sentence) returns a vector (a stand-in for an embedding model); distance(u, v), the cosine distance, is provided.

  1. Gaps. Embed every sentence and take the distance between each sentence and the next: n sentences give n - 1 gaps.
  2. Threshold. The percentile-th percentile of this document's gaps by nearest rank: sort the gaps ascending and take the one at 1-based rank ceil(percentile * len(gaps) / 100), at least 1.
  3. Cut between two sentences when their gap is strictly greater than the threshold. A gap equal to the threshold is not a cut.
  4. Too small. While there is more than one chunk and some chunk has fewer than min_size sentences, take the first such chunk and merge it with a neighbour: the one across its smaller gap (the earlier neighbour when its two gaps are equal). The first chunk can only merge forward, the last only back.
  5. Too big. Then split every chunk longer than max_size into pieces of max_size sentences from its start; the last piece keeps the rest, however short.
  6. No sentences give []; one sentence gives one chunk.

The catch. The threshold is not a fixed distance. Embedding models differ, and so do documents: the shifts in a page that jumps from baking to taxes are far apart, the shifts inside one contract are close. Taking the percentile over the gaps of the document being split cuts each document at its own largest shifts: about the top (100 - percentile) percent of its gaps.