方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

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:

  1. Splits text into sentences using a simple rule-based splitter (sentence-ending punctuation followed by whitespace and a capital letter, or end-of-string).
  2. Groups consecutive sentences into a window of size window_size and computes an embedding for each window.
  3. Detects topic shift boundaries where the cosine similarity between consecutive windows drops below a configurable threshold.
  4. Merges sentences into chunks between detected boundaries, up to a max_chunk_size character limit.
  5. Adds overlap by copying the last overlap_sentences sentences from each chunk into the start of the next chunk.
  6. 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 chunk method should accept a plain string and return list[Chunk].
  • Test with a multi-paragraph document where topic shifts are visible.

Rag Systems / medium / Step 1 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

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.