Tell Each Chunk Where It Came From
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.
- One call per chunk, in order. The prompt is
DOCUMENT_PROMPTfilled with the doc'stitleandtext(astitle=anddocument=), thenCHUNK_PROMPTfilled with the chunk'stext(aschunk=). Document first, chunk last: every call for one document starts with the same bytes, so a prompt cache serves them after the first call. - Tidy the reply. Each run of whitespace becomes one space; the ends are stripped.
- Fall back when the tidied reply is empty, has more than
max_wordswords (split on whitespace), or repeats the chunk. The fallback context isFrom {title}, section {heading}., orFrom {title}.when the chunk has no heading. - One record per chunk, in order:
{"chunk": the chunk's text, "context": the context, "indexed": context + "\n\n" + chunk text}. searchscores each record'sindexedtext withbm25_scores(query, texts)and returns thechunkof the bestk, 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.