Skip to content

< all problems120 · Level 03, RAG

Search Small, Return Big

medium · implement · RAG

Search on single sentences, then hand back the larger passage each match sits in. Implement make_children(docs) and small_to_big(docs, query, k=4, window=None, max_tokens=None). Each doc has an id and sections, each with a title and sentences.

  1. Children. make_children returns one child per sentence, in document order: {"text", "doc": the doc's id, "section": the section's index in its doc, "pos": the sentence's index in its doc, counted across sections from 0}.
  2. Match small. Score every child with similarity(query, text) and keep the best k, best first, dropping any that score 0. Ties keep the children's order.
  3. Return big. Each kept child becomes a passage {"doc", "span": (first, last), "text"}: positions inclusive, text the sentences of the span joined with one space. With window=None the span is the child's whole section. With window=w it is the child plus up to w sentences either side: it may cross sections, never the edge of its document.
  4. One passage per parent. A child whose sentence is already inside a passage you returned adds nothing: skip it. Passages come out in the order of the child that brought them.
  5. Budget. With max_tokens, a passage that would take the total count_tokens of the returned texts over max_tokens is skipped, and later ones are still tried.

The catch. The sentence that matches is often not the one that answers. "Refund requests for annual plans follow a separate rule" matches a refund question well; the next sentence, "They are accepted within 30 days of the renewal date", holds the answer and shares no word with the question. So you search on sentences and return their parents, and a parent's rank comes from its best child, not from how many of its children matched.