Skip to content

< CollectionsAll the RAGs · 13 of 42 ·118 · Level 03, RAG

Ask Four Ways, Fuse the Rankings

medium · implement · Embeddings & Retrieval

Have a model rewrite the question several ways, search each, and fuse the rankings. Implement parse_queries(reply) and fusion_search(question, generate, search, n=4, top=5, depth=10). generate(prompt) is the model and returns a string; search(query, depth) returns up to depth hits, best first, each {"id", "snippet"}.

  1. One model call with QUERIES_PROMPT filled with n and the question (as n= and question=).
  2. parse_queries reads the reply line by line. Strip the line, remove a list marker at its start (-, *, •, or digits then . or ), followed by whitespace), strip again, remove " and ' from both ends, and turn each run of whitespace into one space. Skip lines left empty and lines ending in : (a header like Here are 4 queries:). Return the rest in order.
  3. The queries are the question itself first, then the parsed rewrites, skipping any that repeat a query already listed (compared lowercased with whitespace runs collapsed), keeping at most n rewrites. A reply with nothing usable leaves the question alone.
  4. Search each query with search(query, depth), in order.
  5. Fuse with reciprocal rank fusion: a document's score is the sum, over the lists it appears in, of 1 / (RRF_K + rank), rank counted from 1 (RRF_K is 60). Best first; equal scores by id.
  6. Return {"queries": the queries, "results": [(id, score), ...]} for the best top.

The catch. The same document comes back from different queries with a different snippet, because a snippet marks the words that matched. Fusion counts documents, so key the scores by id. Keyed by anything else, a document every query found splits into weak copies and loses to one that a single query found.