Semantic Chunking
Semantic chunking groups sentences by meaning instead of relying only on fixed lengths or punctuation. It uses semantic similarity to detect topic changes, creating chunks that are more likely to keep related ideas together.
By the end of this lesson, you will be able to:
- Explain what semantic chunking is and why meaning-based boundaries can help retrieval.
- Understand how sentence embeddings can be compared to detect topic changes.
- Build a simple semantic chunker with Python.
- Choose similarity thresholds and minimum chunk sizes carefully.
- Compare semantic chunking with fixed-size, sentence, and recursive chunking.
- Evaluate semantic chunks for RAG retrieval quality, cost, and context completeness.
What Is Semantic Chunking?
Semantic chunking creates chunks by looking for changes in meaning. Instead of saying βevery 500 characters is a chunk,β the algorithm asks whether neighboring sentences are still talking about the same idea.
Why Semantic Boundaries Matter
A document can contain sentences of very different lengths. A fixed-size splitter may put two unrelated topics in the same chunk simply because they happen to be close in the original text.
One chunk, two topics
A chunk may contain the end of a database section followed by the beginning of a pricing section.
Boundary at topic change
A semantic splitter can detect that the neighboring sentences have become less similar and create a cleaner boundary.
This can improve retrieval because a returned chunk is more likely to contain a coherent idea rather than unrelated neighboring material.
Semantic Chunking Uses Embeddings
To compare meaning, sentences can be converted into embeddings. Each sentence becomes a vector, and neighboring vectors can then be compared with a similarity measure such as cosine similarity.
How Topic Boundaries Are Detected
A simple approach compares each sentence with the next sentence. If similarity stays high, the sentences can remain in the same chunk. If similarity falls below a chosen threshold, the algorithm can start a new chunk.
Similarity Threshold
The threshold controls how much semantic change is required before creating a new chunk. A high threshold creates more boundaries; a low threshold allows more sentences to stay together.
Too many chunks
Small meaning differences can cause unnecessary splits and fragmented context.
Coherent topics
Related sentences stay together while clear topic changes create boundaries.
Chunks become broad
Different topics may remain together, reducing retrieval precision.
Simple Semantic Chunking in Python
The following example uses Sentence Transformers to create sentence embeddings and cosine similarity to detect topic changes. It is intentionally simple so you can see the mechanism.
!pip install -q sentence-transformers
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
sentences = [
"A vector database stores embeddings for fast similarity search.",
"It can return the most relevant vectors for a query.",
"Metadata filters can narrow the search to a specific product.",
"Our support team answers customer emails from 9 AM to 6 PM.",
"Support requests are tracked with a ticket number."
]
model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = model.encode(sentences)
for i in range(len(sentences) - 1):
score = cosine_similarity(
[embeddings[i]],
[embeddings[i + 1]]
)[0][0]
print(f"{i} -> {i + 1}: {score:.3f}")Building Chunks From the Scores
Once neighboring similarities are available, you can use a threshold to decide where a new chunk starts. A production implementation should also enforce minimum and maximum chunk sizes.
def semantic_chunks(sentences, embeddings, threshold=0.55):
chunks = [[sentences[0]]]
for i in range(1, len(sentences)):
score = cosine_similarity(
[embeddings[i - 1]],
[embeddings[i]]
)[0][0]
if score < threshold:
chunks.append([sentences[i]])
else:
chunks[-1].append(sentences[i])
return [" ".join(chunk) for chunk in chunks]
chunks = semantic_chunks(sentences, embeddings, threshold=0.55)
for index, chunk in enumerate(chunks, start=1):
print(f"Chunk {index}: {chunk}\n")Minimum and Maximum Chunk Size
Pure semantic similarity can produce awkward chunks if it is allowed to split whenever a score changes. Practical systems usually combine semantic boundaries with size constraints.
Semantic Chunking vs Other Strategies
Length first
Simple and predictable. It may cut through ideas or combine nearby topics.
Sentence boundaries
Preserves complete sentences but does not automatically know when the topic changes.
Structure first
Uses a hierarchy of separators to preserve document structure before smaller boundaries.
Meaning first
Uses embedding similarity to find topic changes and can adapt to uneven sentence lengths.
Semantic Chunking in RAG
Semantic chunking happens during ingestion, before chunks are embedded and stored for retrieval. Better boundaries can make the retrieved context more coherent.
Extract text from PDFs, web pages, manuals, or other sources.
Create the units that will be compared semantically.
Use embedding similarity and size constraints.
Embed the final chunks and store them with metadata.
Compare a query embedding with stored chunk embeddings.
Send the best context to the language model.
Semantic Chunking and Overlap
Semantic boundaries already try to keep related ideas together, so overlap is not automatically required. However, a small overlap can still help when important information crosses a detected boundary.
Metadata Still Matters
Semantic chunking decides where to split. Metadata tells your application where the chunk came from and how it was created.
Original document identifier.
Useful for filtering and citations.
Position within the source.
Records how the chunk was produced.
Where Semantic Chunking Works Well
Useful when documentation changes between APIs, configuration, troubleshooting, and examples.
Helpful when articles contain several questions or workflows.
Can adapt better than a single fixed character size when topics have different lengths.
Can create focused chunks for semantic search and RAG.
When Semantic Chunking Can Struggle
Short text may not contain enough information for a stable semantic signal.
Different sections can use similar language even when their topics differ.
Sentence-level semantics may not preserve the structure needed to interpret tabular or code content.
If PDF or HTML extraction damages sentence order, semantic boundaries can also become unreliable.
Embedding every sentence during ingestion adds computation and latency compared with simple length-based splitting.
Common Mistakes
Different embedding models and document types can produce different similarity distributions.
A long sequence of related sentences can become one oversized chunk.
Small score changes do not always represent a meaningful topic change.
A lower or higher number of chunks does not prove that retrieval improved.
Headings, tables, lists, and code may require structure-aware handling before semantic splitting.
How to Evaluate Semantic Chunking
Evaluate the complete retrieval pipeline rather than optimizing chunk boundaries in isolation.
Build a Semantic Chunker
Take a short document with at least 10 sentences and create semantic chunks using sentence embeddings.
source, section, chunk_index, similarity_to_previous, word_count, and chunking_strategy with every chunk.Quick Quiz
It uses meaning-based signals such as embedding similarity instead of relying only on a length limit.
A point where the similarity between neighboring content drops enough to suggest a topic or meaning change.
No. Minimum and maximum sizes help prevent tiny fragments and oversized chunks.
Similarity scores depend on the embedding model and the document distribution.
Measured retrieval and answer quality, along with cost and context efficiency.
30-Second Recap
Semantic chunking looks for changes in meaning.
Sentences are represented as vectors for comparison.
Neighboring similarity can reveal topic boundaries.
The threshold controls how readily boundaries are created.
Minimum and maximum sizes keep chunks practical.
Measure retrieval and final answer quality.
Key Takeaways
- Semantic chunking uses meaning rather than length alone to create boundaries.
- Sentence embeddings and cosine similarity provide a practical way to detect topic changes.
- Similarity thresholds must be tuned for the embedding model and document collection.
- Semantic rules should be combined with minimum and maximum chunk sizes.
- Tables, code, headings, and other structured content may need specialized handling.
- The best chunking strategy is the one that improves retrieval and answer quality for your actual workload.