Skip to content

< all problems117 · Level 02, Search

Search With the Answer You Hope to Find

medium · implement · Embeddings & Retrieval

Search with a model's guess at the answer instead of the question. Implement hyde_vector(question, write, n=4), which returns (vector, kept), and hyde_search(question, passages, write, k=3, n=4). write(prompt) is the model and returns its reply as a string; embed(text) (provided) returns a list of floats; each passage is {"id", "text"}.

  1. Sample n hypothetical documents. Call write n times, every time with the same prompt, HYDE_PROMPT filled with the question (as question=). The model samples, so the replies differ.
  2. Keep the usable ones. Strip each reply and drop it if that leaves it empty. A call that raises counts as an empty reply: a failing writer must not fail the search. kept is the stripped replies, in order.
  3. Average. vector is the element-wise mean of embed(question) and embed(doc) for every kept document: with m kept, m + 1 vectors, each position summed and divided by m + 1. With nothing kept it is embed(question) alone, which is plain dense search.
  4. hyde_search ranks the passages with rank(vector, passages, k) (provided) and returns {"ids": the ids it gives, "context": ...}. The context has one [id] text entry per found passage, best first, joined by a blank line ("\n\n"); with no passages found it is "".

The catch. A hypothetical document is made up. It reads like an answer, which is why its vector lands near real answers, and its facts are the model's guess, which is why nothing downstream may use it. It steers the search and stops there: it is never in ids and never in context, which hold real passages only.