Search Tutorials
--Ads--Semantic Chunking
Use embedding similarity between sentences to find natural topic boundaries.
Fixed-size and structure-aware chunking need either a length or explicit markup. Many documents have neither: transcripts, long emails, scraped articles and OCR output are walls of text where topics change without warning. Semantic chunking finds topic boundaries from the meaning of the text itself, using embeddings.
How it works
- Split the text into sentences.
- Embed each sentence (optionally together with its neighbours, for stability).
- Compute the similarity between each sentence and the next one.
- Where the similarity drops sharply, the topic has changed: start a new chunk there.
Implementation
import re
import numpy as np
from rag_helpers import embed
def split_sentences(text: str) -> list[str]:
# Simple rule-based splitter; use nltk or spaCy for difficult text
parts = re.split(r"(?<=[.!?])\s+(?=[A-Z0-9\"'(])", text.strip())
return [p.strip() for p in parts if p.strip()]
def semantic_chunks(text: str, percentile: float = 90, window: int = 1,
max_sentences: int = 25) -> list[str]:
sentences = split_sentences(text)
if len(sentences) < 3:
return [" ".join(sentences)]
# Embed each sentence together with `window` neighbours on each side for stability
windows = [" ".join(sentences[max(0, i - window): i + window + 1]) for i in range(len(sentences))]
vectors = embed(windows)
# Distance between consecutive sentence windows (1 - cosine similarity)
distances = 1 - np.sum(vectors[:-1] * vectors[1:], axis=1)
threshold = np.percentile(distances, percentile)
chunks, current = [], [sentences[0]]
for i, distance in enumerate(distances, start=1):
if distance > threshold or len(current) >= max_sentences:
chunks.append(" ".join(current))
current = []
current.append(sentences[i])
chunks.append(" ".join(current))
return chunks
transcript = (
"Welcome to the quarterly review. Revenue grew 12% compared to last quarter. "
"Most of the growth came from the enterprise plan. Renewals were also strong. "
"Next, an update on hiring. We added 14 engineers this quarter. "
"Two senior roles are still open in the data team. "
"Finally, the office move. The new office opens on 1 March. "
"Parking passes will be emailed next week."
)
for chunk in semantic_chunks(transcript, percentile=80):
print("-", chunk)
- Welcome to the quarterly review. Revenue grew 12% compared to last quarter. Most of the growth came from the enterprise plan. Renewals were also strong.
- Next, an update on hiring. We added 14 engineers this quarter. Two senior roles are still open in the data team.
- Finally, the office move. The new office opens on 1 March. Parking passes will be emailed next week.
Choosing the threshold
A fixed similarity threshold does not transfer between documents or models, because similarity ranges vary. Using a percentile of the distances in each document adapts automatically: with percentile=90, the 10% largest jumps become boundaries. Lower percentiles give more, smaller chunks. The max_sentences guard stops a chunk from growing without limit when a document has no clear topic changes.
When semantic chunking helps, and when it does not
| Helps | Does not help much |
|---|---|
| Transcripts, meeting notes, podcasts | Well-structured Markdown or HTML (use headings) |
| Long emails and chat logs | Short documents that fit in one chunk |
| OCR text with no formatting | Tables, code and lists |
| News articles that cover several stories | Very large collections where indexing cost matters |
Benchmarks comparing chunkers have found that semantic chunking is not consistently better than a well-tuned recursive splitter, while it costs one embedding per sentence at indexing time. Treat it as a tool for unstructured text, and confirm the gain on your own evaluation set.
LangChain provides SemanticChunker in the langchain_experimental package, and LlamaIndex provides SemanticSplitterNodeParser. Both implement the same idea with percentile, standard-deviation or interquartile thresholds.
Key takeaways
- Semantic chunking splits where the similarity between neighbouring sentences drops.
- Use a per-document percentile threshold, sentence windows for stability and a maximum chunk size.
- It shines on unstructured text such as transcripts; for structured documents, use their structure.
- It costs more to index, so measure the improvement before adopting it.