AI Engineer Portal
Your personal operating system for career transition.
Exercise
Implement semantic chunking with overlap
Implement Semantic Chunking with Overlap
Fixed-size chunking is fast but blind to sentence boundaries — it cuts paragraphs in half, splits mid-sentence, and produces chunks where neither half carries the full context. Semantic chunking detects topic shifts using embedding similarity, then splits at the boundaries where meaning changes. Combined with overlap, this produces index-ready chunks that each contain a coherent unit of thought.
What you are building
Create a SemanticChunker class that:
- Splits text into sentences using a simple rule-based splitter (sentence-ending punctuation followed by whitespace and a capital letter, or end-of-string).
- Groups consecutive sentences into a window of size
window_sizeand computes an embedding for each window. - Detects topic shift boundaries where the cosine similarity between consecutive windows drops below a configurable threshold.
- Merges sentences into chunks between detected boundaries, up to a
max_chunk_sizecharacter limit. - Adds overlap by copying the last
overlap_sentencessentences from each chunk into the start of the next chunk. - Attaches metadata to each chunk: source identifier, chunk index, character start/end, and the sentences it contains.
Why this matters
Semantic chunking is the approach used in production systems where chunk quality directly affects answer quality — legal documents, medical content, technical specifications. Understanding how it works means you can tune the threshold and window size for your corpus rather than accepting a library default.
Constraints
- Mock the embedding call with a simple hash-based fake that returns a deterministic vector — the exercise is about the chunking logic, not the API.
- All type hints required.
- The
chunkmethod should accept a plain string and returnlist[Chunk]. - Test with a multi-paragraph document where topic shifts are visible.
Rag Systems / medium / Step 1 of 6
General drill
Keep the solution explicit and reviewable.
Make the solution explicit, debuggable, and easy to explain.
Review where the boundary is, what gets validated, and what would be hard to debug later.
Practice
Generate a variation
Generate a new exercise variation to deepen understanding or practice a related concept.
Attempt history
Recent submissions
Before you submit, decide what a strong answer should make obvious to the reviewer.
No attempts yet.