Sentence-Window Retrieval

easy
Unit 4 · Fine-Tuning & Evaluation0/2 to milestone

Embedding single sentences gives precise matches but too little context to answer from. Sentence-window retrieval (LlamaIndex) retrieves sentences, then expands each hit to include its neighbours.

Implement:

  • expand_hits(hits, n_sentences, window): for each hit index, take the inclusive range [hit - window, hit + window] clipped to the document. Merge ranges that overlap or touch ([1, 3] and [4, 6] become [1, 6]), and return sorted (start, end) inclusive pairs.
  • window_texts(sentences, ranges): the text of each range, sentences joined with a space
  • context_tokens(sentences, ranges, count=lambda s: len(s.split())): the total token count of the expanded context, to check it against a budget
#rag#retrieval#chunking2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Sentence-Window Retrieval · TechGradify