LESSON 41 Β· CHUNKING

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.

35 min readβ€’Intermediateβ€’Generative AI

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.
1

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.

SentencesBreak document into units
β†’
EmbedRepresent meaning as vectors
β†’
CompareMeasure neighboring similarity
β†’
SplitCut at topic changes
Key idea:semantic chunking tries to place a boundary where the meaning changes, not merely where a character or sentence count reaches a limit.
2

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.

LENGTH-BASED

One chunk, two topics

A chunk may contain the end of a database section followed by the beginning of a pricing section.

β†’
SEMANTIC

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.

3

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.

Sentence Aβ€œThe refund is processed within five business days.”
β†’
Embedding A[0.12, -0.31, 0.44, ...]
↔
Embedding B[0.10, -0.28, 0.41, ...]
β†’
SimilarityHigh β†’ likely same topic
Important: semantic chunking depends on the embedding model. Different models can produce different similarity patterns, so chunking settings should be tested with the actual model used by your application.
4

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.

STEP 1Split sentencesCreate natural-language units first.
STEP 2Create embeddingsTurn each sentence into a vector.
STEP 3Compare neighborsMeasure semantic similarity.
STEP 4Create boundariesSplit where the topic changes enough.
5

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.

THRESHOLD TOO HIGH

Too many chunks

Small meaning differences can cause unnecessary splits and fragmented context.

BALANCED

Coherent topics

Related sentences stay together while clear topic changes create boundaries.

THRESHOLD TOO LOW

Chunks become broad

Different topics may remain together, reducing retrieval precision.

Practical rule:do not treat a threshold such as 0.70 or 0.80 as universally correct. Tune it using representative documents and real retrieval questions.
6

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.

</> Python
!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}")
What to observe:sentences about vector databases should generally be closer to one another than sentences that switch to customer support. The exact scores depend on the embedding model.
7

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.

</> Python
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")
Learning point: the threshold is only one control. You should also prevent extremely tiny chunks and prevent a long sequence of moderately similar sentences from creating an oversized chunk.
8

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.

MINIMUM SIZEAvoid tiny fragmentsMerge or delay a boundary when the current chunk is too small.
SEMANTIC SIGNALDetect topic changeUse similarity to decide whether neighboring sentences still belong together.
MAXIMUM SIZEProtect context budgetForce a smaller split when a semantically broad section becomes too large.
Best practice:use semantic similarity as a signal, not as the only rule. Size limits make the chunker safer for real RAG systems.
9

Semantic Chunking vs Other Strategies

FIXED-SIZE

Length first

Simple and predictable. It may cut through ideas or combine nearby topics.

VS
SENTENCE

Sentence boundaries

Preserves complete sentences but does not automatically know when the topic changes.

VS
RECURSIVE

Structure first

Uses a hierarchy of separators to preserve document structure before smaller boundaries.

VS
SEMANTIC

Meaning first

Uses embedding similarity to find topic changes and can adapt to uneven sentence lengths.

10

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.

1Load document

Extract text from PDFs, web pages, manuals, or other sources.

2Split into sentences

Create the units that will be compared semantically.

3Find boundaries

Use embedding similarity and size constraints.

4Create chunk embeddings

Embed the final chunks and store them with metadata.

5Retrieve

Compare a query embedding with stored chunk embeddings.

6Generate

Send the best context to the language model.

11

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.

Topic ASentences about one idea
β†’
BoundarySimilarity drops
β†’
Topic BSentences about another idea
Trade-off: too much overlap can duplicate information and increase embedding, storage, and retrieval costs. Start small and measure whether it improves answer quality.
12

Metadata Still Matters

Semantic chunking decides where to split. Metadata tells your application where the chunk came from and how it was created.

SOURCEemployee-handbook.pdf

Original document identifier.

SECTIONLeave Policy

Useful for filtering and citations.

CHUNK INDEX17

Position within the source.

STRATEGYsemantic

Records how the chunk was produced.

Why it matters: metadata supports filtering, citations, debugging, evaluation, and reconstruction of nearby context.
13

Where Semantic Chunking Works Well

TECHNICAL DOCSTopic-based sections

Useful when documentation changes between APIs, configuration, troubleshooting, and examples.

SUPPORT CONTENTDistinct customer topics

Helpful when articles contain several questions or workflows.

LONG ARTICLESUneven paragraphs

Can adapt better than a single fixed character size when topics have different lengths.

KNOWLEDGE BASESMeaningful retrieval units

Can create focused chunks for semantic search and RAG.

14

When Semantic Chunking Can Struggle

Very short sentences

Short text may not contain enough information for a stable semantic signal.

Highly repetitive documents

Different sections can use similar language even when their topics differ.

Tables and code

Sentence-level semantics may not preserve the structure needed to interpret tabular or code content.

Poor sentence extraction

If PDF or HTML extraction damages sentence order, semantic boundaries can also become unreliable.

Embedding cost

Embedding every sentence during ingestion adds computation and latency compared with simple length-based splitting.

15

Common Mistakes

Using one threshold everywhere

Different embedding models and document types can produce different similarity distributions.

Ignoring maximum size

A long sequence of related sentences can become one oversized chunk.

Splitting too aggressively

Small score changes do not always represent a meaningful topic change.

Evaluating only chunk counts

A lower or higher number of chunks does not prove that retrieval improved.

Forgetting document structure

Headings, tables, lists, and code may require structure-aware handling before semantic splitting.

16

How to Evaluate Semantic Chunking

Evaluate the complete retrieval pipeline rather than optimizing chunk boundaries in isolation.

RETRIEVAL RELEVANCEDid the right chunk rank highly?
CONTEXT COMPLETENESSDid the chunk contain enough information?
NOISEDid retrieved chunks contain unrelated topics?
COSTHow many embeddings and tokens are required?
ANSWER QUALITYDid the final model answer improve?
Simple experiment:build the same retrieval evaluation set and compare fixed-size, recursive, and semantic chunking using the same embedding model, vector database, top-k value, and questions.
PRACTICE

Build a Semantic Chunker

Take a short document with at least 10 sentences and create semantic chunks using sentence embeddings.

Challenge: test at least three thresholds. Record the number of chunks, average chunk size, and which topic boundaries were detected. Then run five questions against the resulting chunks and compare retrieval quality.
Extension: store source, section, chunk_index, similarity_to_previous, word_count, and chunking_strategy with every chunk.

Quick Quiz

1. What makes semantic chunking different from fixed-size chunking?

It uses meaning-based signals such as embedding similarity instead of relying only on a length limit.

2. What is a semantic boundary?

A point where the similarity between neighboring content drops enough to suggest a topic or meaning change.

3. Does semantic chunking remove the need for size limits?

No. Minimum and maximum sizes help prevent tiny fragments and oversized chunks.

4. Why can the threshold not be copied blindly between projects?

Similarity scores depend on the embedding model and the document distribution.

5. What should ultimately decide whether semantic chunking is better?

Measured retrieval and answer quality, along with cost and context efficiency.

30-Second Recap

1Meaning-based

Semantic chunking looks for changes in meaning.

2Embeddings

Sentences are represented as vectors for comparison.

3Similarity

Neighboring similarity can reveal topic boundaries.

4Threshold

The threshold controls how readily boundaries are created.

5Size limits

Minimum and maximum sizes keep chunks practical.

6Evaluate

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.