Skip to content

< all problems112 · Level 02, Search

Tell Each Chunk Where It Came From

medium · implement · RAG

A chunk cut out of a report says "Revenue grew 3%" but not whose, so a search naming the company misses it. Implement contextualize(doc, chunks, situate, max_words=40), which has a model write a short context for each chunk before indexing, and search(records, query, k=3). doc has a title and the whole text; each chunk has a text and a heading (its section, maybe empty or missing); situate(prompt) is the model and returns its reply as a string.

  1. One call per chunk, in order. The prompt is DOCUMENT_PROMPT filled with the doc's title and text (as title= and document=), then CHUNK_PROMPT filled with the chunk's text (as chunk=). Document first, chunk last: every call for one document starts with the same bytes, so a prompt cache serves them after the first call.
  2. Tidy the reply. Each run of whitespace becomes one space; the ends are stripped.
  3. Fall back when the tidied reply is empty, has more than max_words words (split on whitespace), or repeats the chunk. The fallback context is From {title}, section {heading}., or From {title}. when the chunk has no heading.
  4. One record per chunk, in order: {"chunk": the chunk's text, "context": the context, "indexed": context + "\n\n" + chunk text}.
  5. search scores each record's indexed text with bm25_scores(query, texts) and returns the chunk of the best k, best first, skipping any that score 0. Ties keep the records' order.

The catch. A model asked to situate a chunk sometimes answers with the chunk itself, reflowed, recased or wrapped in a few words. That is no context: indexed, it counts every word of the chunk twice. A reply repeats the chunk when the chunk's text appears inside it, compared with whitespace tidied and case ignored on both sides.