Module 3 · Advanced retrieval

Query rewriting, HyDE and multi-query

6 min read

The user's question is not the best search query. It contains politeness, typos, spoken language ("the thing to send stuff back"), another language, or several topics at once. Before searching, it can be transformed with an LLM. This lesson presents four transformations — rewriting, HyDE, multi-query, decomposition — their cost, and how to decide whether they are worth it.

Four transformations

TechniquePrincipleProblem addressed
RewritingRephrase in the documents' vocabularySpoken language, another language, vague words
HyDEWrite a hypothetical answer and search with itShort question, far from the documents' style
Multi-querySeveral phrasings, results fusedAmbiguity, sensitivity to phrasing
DecompositionSplit into sub-questions, one search eachQuestions on several topics

Rewriting

Prism's prompt describes the corpus and the expected vocabulary, and forces French for a French corpus:

REWRITE = """Reformule la question d'un client en une requête de recherche pour le centre d'aide
d'une boutique en ligne : vocabulaire précis des documents (rétractation, garantie, frais de remise
en stock…), sans politesse, en français même si la question est dans une autre langue.
Réponds uniquement par la requête.

Question : {question}"""


def rewrite(question: str) -> str:
    return llm.complete("rewrite", REWRITE.format(question=question), fast=True, max_tokens=200)

(The prompt asks to rephrase a customer question into a search query with the documents' precise vocabulary — withdrawal, warranty, restocking fees — without politeness, in French even if the question is in another language.) It is a simple task: a small fast model (fast=True, Claude Haiku) is enough. For an English question, rewriting makes lexical search useful again — it is the only way for BM25 to find anything.

One risk: rewriting can betray the question (add an assumption, lose a product reference). That is why you often search with the original question and the rewrite, rather than with the rewrite alone.

HyDE: searching with a fake answer

Hypothetical Document Embeddings starts from an observation: a question and its answer do not look alike ("refund time?" versus "The refund is issued within 14 days of receipt…"). An imagined answer, even wrong in the details, looks much more like the documents than the question does:

HYDE = """Rédige en trois phrases le paragraphe du centre d'aide d'une boutique en ligne qui
répondrait à cette question. Invente des valeurs plausibles si nécessaire : ce texte sert
uniquement à la recherche, jamais à répondre au client.

Question : {question}"""


def search_hyde(dense_retriever, question: str, k: int = 5) -> list[Hit]:
    """HyDE : on cherche avec l'embedding d'une réponse imaginaire, plus proche des documents
    que la question."""
    return dense_retriever.search(hyde(question), k)

(The prompt asks for the three-sentence help center paragraph that would answer the question, inventing plausible values if needed: the text is used only for search, never to answer the customer.) The hypothetical answer is used only for search: it must never reach the user, since it contains invented values. HyDE is only useful for dense search; with BM25, the invented values add lexical noise.

Multi-query: several phrasings

Ask for several rephrasings (with structured output, to get a real list), search with each, and fuse with RRF:

def search_multi(retriever, question: str, k: int = 5, n: int = 3) -> list[Hit]:
    """Recherche avec la question d'origine ET ses reformulations, fusion par RRF."""
    queries = [question, *multi_query(question, n)]
    return rrf([retriever.search(q, 20) for q in queries], limit=k)

Multi-query reduces the sensitivity of the result to one particular phrasing. It multiplies the number of searches (cheap) but adds only one LLM call.

Decomposition

"What is the supplier of the Lift desk and how long are its motors under warranty?" spans two articles. A single search often brings back only one: this is exactly dense search's failure on multi-source questions (0.75). Decomposition creates one search per topic:

def search_decomposed(retriever, question: str, k: int = 5) -> list[Hit]:
    """Une recherche par sous-question ; la fusion garantit que chaque sujet est représenté."""
    return rrf([retriever.search(q, 10) for q in decompose(question)], limit=k)

The prompt says to return the question as is if it is simple: decomposing a simple question only multiplies the calls.

The cost, and honest numbers

Each transformation adds one LLM call before the search, hence hundreds of milliseconds of latency and a cost per query. On Prism, hybrid search with re-ranking already reaches 1.00 recall and 0.97 MRR without any transformation: there is nothing left to gain on this question set. That is a lesson in itself: you add a transformation to fix a measured failure, not on principle.

The cases where they win clearly, on real corpora:

  • the corpus and the users do not speak the same language, and no good multilingual dense search is available;
  • questions are very short or very vague ("delivery problem");
  • many questions span several topics, and you do not want an agent (lesson 4.2);
  • the users' vocabulary is very far from the documents' (internal jargon, legal documents).

In offline mode (PRISM_FAKE=1), examples/03_query_and_context.py checks the mechanics of each transformation; with an API key, add them to the test bench to measure them on your questions.

Transform only when useful

An economical strategy: search first with the question as is, and transform only if the search seems to have failed — for example if the re-ranker's best score is below the threshold calibrated in the previous lesson. Most queries then pay nothing extra. This is the principle of corrective RAG (lesson 4.3).

Key takeaways

  • The user's question is not the best query: it can be rewritten, imagined as an answer (HyDE), rephrased several times or decomposed.
  • Rewriting: the documents' vocabulary and the corpus language; also search with the original.
  • HyDE: the invented answer is used for dense search only, never shown to the user.
  • Decomposition: one search per topic for multi-source questions.
  • Each transformation costs an LLM call: add one only to fix a measured failure, ideally conditionally.

Practice

  1. With an API key, add a "Dense + HyDE" configuration to the test bench and compare it with dense search on rephrased questions.
  2. Run query.decompose on the six multi-source questions: how many are split correctly?
  3. Implement a conditional search: rewrite only if the re-ranker's best score is below a threshold.

Resources