Sentence-Aware Chunking with Overlap

medium
Unit 18 · Agents0/3 to milestone

Chunk documents at sentence boundaries with a token budget and a little overlap, so a fact split across a boundary still appears whole in one chunk.

Implement chunk_sentences(text, max_tokens, overlap_sentences=1, count_tokens=lambda s: len(s.split())):

  • Split into sentences after ., ! or ? followed by whitespace. Strip each sentence and drop empty ones.
  • Build chunks greedily: add sentences while the chunk's total tokens stay <= max_tokens.
  • Each new chunk starts with the last overlap_sentences sentences of the previous chunk (if they fit with the next sentence; drop overlap sentences from the front until they do).
  • A single sentence longer than max_tokens becomes its own chunk, unsplit.
  • Join sentences in a chunk with a single space. Never emit a chunk that consists only of overlap.
#rag#chunking#nlp2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Sentence-Aware Chunking with Overlap · TechGradify