Chunk a document at semantic breakpoints between sentences

Why it matters Semantic chunking improves RAG retrieval because each chunk stays on one topic instead of being split mid-thought.

Fixed-size chunks cut topics in half. Semantic chunking embeds each sentence and splits where neighbouring sentences are unusually different.

Write semantic_chunks(emb, pct). emb is an (n, D) array of sentence embeddings in document order. For i = 0..n-2 let d_i = 1 - cosine(emb[i], emb[i + 1]). threshold = np.percentile(d, pct). A new chunk starts at sentence i + 1 whenever d_i > threshold. Return a list of chunks, each a list of sentence indices. Return [] for n = 0 and [[0]] for n = 1.

Signaturedef semantic_chunks(emb, pct)

Example

semantic_chunks([[1, 0], [1, 0.1], [0, 1], [0.1, 1]], 50) gives [[0, 1], [2, 3]].

Understand the idea

RAG works best when each chunk talks about one thing. Splitting every 500 tokens often cuts a paragraph in half or glues two topics together. Semantic chunking listens to the text instead: embed each sentence and watch the distance between neighbours. Within a topic, neighbours are similar; at a topic change, the distance jumps.

Example: four sentences with embeddings [1, 0], [1, 0.1], [0, 1], [0.1, 1]. Distances between neighbours are about 0.005, 0.9 and 0.005. The 50th percentile is about 0.005, and only the middle jump is above it, so we split after sentence 1: chunks [0, 1] and [2, 3].

Rule: d_i = 1 - cos(e_i, e_(i+1)); threshold = percentile(d, p); start a new chunk at i + 1 when d_i > threshold.

Higher percentiles give fewer, longer chunks; most pipelines also cap chunk length in tokens.

Shapes and data flow

emb: (n, D) -> d: (n - 1,) -> list of chunks
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplesemantic_chunks([[1, 0], [1, 0.1], [0, 1], [0.1, 1]], 50)
  • Sample 2: three topicssemantic_chunks([[1, 0, 0], [0.9, 0.1, 0], [0, 1, 0], [0, 0.9, 0.2], [0, 0, 1], [0.1, 0, 1]], 60)
  • Test 3: singlesemantic_chunks([[3, 4]], 90)
  • Test 4: randomsemantic_chunks(_E, 75)