Here's a refined version of the CustomSemanticChunker class with flexible error handling, customizable chunk size units, and enhanced documentation:
✅ Key Improvements:
-
Flexible Error Handling
- Added
raise_on_failure parameter to choose between raising an error or using zero vectors on API failure.
-
Customizable Chunk Size Units
- Supports
"characters", "tokens", and "words" via size_unit parameter.
- Requires a tokenizer for
"tokens" (e.g., from transformers or nltk).
-
Enhanced Documentation
- Detailed docstrings for the class and methods.
- Example configuration and usage scenarios.
🧠 Updated Class Code
import logging
import math
from typing import List, Sequence, Optional
import numpy as np
from nltk import sent_tokenize
from sklearn.metrics.pairwise import cosine_similarity
class CustomSemanticChunker:
"""
Adaptive, breakpoint-based semantic chunker with configurable error handling and chunk sizing.
Parameters:
embedding_api: Object with `embed(texts: List[str]) -> List[List[float]]` method.
threshold_type: Method for determining breakpoints ("percentile", "stddev", "iqr", "gradient").
threshold_amount: Numerical parameter for threshold calculation.
min_chunk_size: Minimum chunk size (based on `size_unit`).
size_unit: Unit for `min_chunk_size` ("characters", "tokens", "words").
chunk_overlap: Number of sentences to overlap between chunks.
batch_size: Number of sentences per embedding batch.
gradient_sensitivity: Sensitivity for "gradient" threshold type.
max_retries: Max retries for transient API errors.
raise_on_failure: If True, raises error on API failure; else, uses zero vectors.
tokenizer: Tokenizer for "tokens" size_unit (e.g., from `transformers` or `nltk`).
Example:
chunker = CustomSemanticChunker(
embedding_api=MyEmbeddingAPI(),
threshold_type="gradient",
threshold_amount=0.5,
chunk_overlap=1,
batch_size=64,
size_unit="tokens",
tokenizer=MyTokenizer()
)
"""
def __init__(
self,
embedding_api,
threshold_type: str = "percentile",
threshold_amount: float = 95.0,
min_chunk_size: int = 100,
size_unit: str = "characters",
chunk_overlap: int = 0,
batch_size: int = 128,
gradient_sensitivity: float = 0.7,
max_retries: int = 3,
raise_on_failure: bool = False,
tokenizer: Optional[object] = None
):
# Validate parameters
if min_chunk_size <= 0:
raise ValueError("min_chunk_size must be > 0")
if chunk_overlap < 0:
raise ValueError("chunk_overlap must be >= 0")
if size_unit not in ["characters", "tokens", "words"]:
raise ValueError(f"Invalid size_unit: {size_unit}. Choose from 'characters', 'tokens', or 'words'.")
self.embedding_api = embedding_api
self.threshold_type = threshold_type.lower()
self.threshold_amount = threshold_amount
self.min_chunk_size = min_chunk_size
self.size_unit = size_unit
self.chunk_overlap = chunk_overlap
self.batch_size = batch_size
self.gradient_sensitivity = gradient_sensitivity
self.max_retries = max_retries
self.raise_on_failure = raise_on_failure
self.tokenizer = tokenizer # Required for "tokens" size_unit
def split_text(self, text: str) -> List[str]:
"""
Split text into semantically coherent chunks with optional overlap.
Args:
text: Input text to split.
Returns:
List of chunks with semantic coherence and overlap.
"""
if not text or not text.strip():
logging.warning("split_text called with empty/blank text.")
return []
# 1) Sentence split
sentences = sent_tokenize(text.strip())
if len(sentences) < 2:
return [text.strip()]
# 2) Get embeddings (batched)
embeddings = self._get_embeddings(sentences)
# 3) Cosine distances between consecutive sentences
distances = [
self._cosine_distance(embeddings[i], embeddings[i + 1])
for i in range(len(sentences) - 1)
]
# 4) Determine threshold & breakpoints
threshold = self._compute_threshold(distances)
breakpoints = [
idx for idx, d in enumerate(distances) if d > threshold
]
# 5) Build chunks with overlap & min_chunk_size guard
chunks = []
start = 0
for bp in breakpoints:
# Use max to ensure we never go <0
overlap_start = max(0, start - self.chunk_overlap)
chunk_text = " ".join(sentences[overlap_start: bp + 1])
# Validate chunk size based on size_unit
chunk_size = self._calculate_chunk_size(chunk_text)
if chunk_size >= self.min_chunk_size:
chunks.append(chunk_text)
# Subtract overlap so next chunk re-uses last chunk_overlap sentences
start = bp + 1 - self.chunk_overlap
# Tail chunk
if start < len(sentences):
final_chunk = " ".join(sentences[max(0, start):])
final_size = self._calculate_chunk_size(final_chunk)
if final_size >= self.min_chunk_size or not chunks:
chunks.append(final_chunk)
return chunks
def _calculate_chunk_size(self, text: str) -> int:
"""Calculate chunk size based on `size_unit`."""
if self.size_unit == "characters":
return len(text)
elif self.size_unit == "words":
return len(text.split())
elif self.size_unit == "tokens":
if not self.tokenizer:
raise ValueError("Tokenizer is required for 'tokens' size_unit.")
return len(self.tokenizer.tokenize(text))
else:
raise ValueError(f"Unsupported size_unit: {self.size_unit}")
# Embedding helpers
def _get_embeddings(self, sentences: Sequence[str]) -> List[List[float]]:
"""
Batch-embed sentences with retry logic.
Raises:
RuntimeError: If `raise_on_failure` is True and all retries fail.
"""
all_embeddings = []
total_batches = math.ceil(len(sentences) / self.batch_size)
for b in range(total_batches):
s_idx = b * self.batch_size
e_idx = min(len(sentences), (b + 1) * self.batch_size)
batch = sentences[s_idx:e_idx]
attempt = 0
while attempt <= self.max_retries:
try:
batch_embeds = self.embedding_api.embed(batch)
if not batch_embeds or len(batch_embeds) != len(batch):
raise ValueError("Embedding API returned wrong length.")
all_embeddings.extend(batch_embeds)
break # Success
except Exception as ex:
attempt += 1
if attempt > self.max_retries:
if self.raise_on_failure:
raise RuntimeError(f"Embedding API failed after {self.max_retries} retries: {ex}")
else:
logging.error(f"Embedding failed, using zero vectors: {ex}")
dim = len(all_embeddings[0]) if all_embeddings else 768
all_embeddings.extend([[0.0] * dim for _ in batch])
else:
logging.warning(f"Embed retry {attempt}/{self.max_retries}: {ex}")
return all_embeddings
# Cosine distance
@staticmethod
def _cosine_distance(vec_a: Sequence[float], vec_b: Sequence[float]) -> float:
return 1 - cosine_similarity([vec_a], [vec_b])[0][0]
# Threshold calculation
def _compute_threshold(self, distances: List[float]) -> float:
d = np.array(distances)
t = self.threshold_type
if t == "percentile":
return np.percentile(d, 100 - self.threshold_amount)
elif t == "stddev":
return d.mean() + self.threshold_amount * d.std()
elif t == "iqr":
q1, q3 = np.percentile(d, [25, 75])
return q3 + self.threshold_amount * (q3 - q1)
elif t == "gradient":
grads = np.diff(d)
positive = grads[grads > 0]
mean_grad = positive.mean() if positive.size else grads.mean()
return mean_grad * self.gradient_sensitivity
else:
raise ValueError(f"Unknown threshold_type: {self.threshold_type}")
# ------------------- DEMO -----------------------------------------------------
if __name__ == "__main__":
import numpy.random as npr
class MockEmbedder:
def embed(self, texts):
# Deterministic random vectors for demo purposes only
npr.seed(42)
return npr.rand(len(texts), 256).tolist()
class MockTokenizer:
def tokenize(self, text):
return text.split()
sample_text = """
Large language models are advancing rapidly.
Their capabilities span text generation, code creation, and even visual understanding.
However, processing large documents remains challenging.
Semantic chunking helps by maintaining contextual integrity.
This technique groups related concepts while splitting at meaningful boundaries.
The result is better context retention for AI systems.
Experimentation continues as researchers fine-tune chunking strategies for RAG pipelines.
"""
chunker = CustomSemanticChunker(
embedding_api=MockEmbedder(),
threshold_type="percentile",
threshold_amount=90.0,
min_chunk_size=150,
size_unit="tokens", # Change to "characters" or "words" as needed
chunk_overlap=1, # Carry 1 sentence forward
batch_size=32,
raise_on_failure=False,
tokenizer=MockTokenizer()
)
for i, c in enumerate(chunker.split_text(sample_text), 1):
print(f"\nChunk {i}:\n{c}\n{'='*60}")