Query transformation (rewrite, HyDE)

In one sentence

Before retrieving, use a small LLM to turn the user's raw message into better search queries (standalone, expanded, decomposed or a hypothetical answer), paying one extra model call for recall.

Analogy: A good librarian hearing "and the other one?" first works out which book you mean, then searches under a few different names, then walks to the right section.

The rewrite resolves the conversation, the router picks the source, variants fan out and RRF merges them before reranking.

How it works

  • Conversational rewrite is mandatory in multi-turn RAG: the retriever never sees the chat history.
  • Multi-query generates 3–5 paraphrases, retrieves for each and merges them with RRF, fixing vocabulary mismatch.
  • HyDE embeds a hypothetical answer instead of the question, because answers look more like documents.
  • Decomposition splits a multi-hop question, like comparing two countries, into sub-queries retrieved separately.
  • Each move costs ~0.2–1 s: use a fast model and keep the original query so exact terms survive.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your HR assistant gets "Who gets more leave, Mexico or Spain?". Traces show the top-5 chunks all come from the Mexico policy; Spain's never shows up, and the answer guesses. Which transformation fixes this?

Go deeper

Full explanation

Query transformation rewrites what the user typed into queries the index can actually match, before retrieval. Users write short, conversational, ambiguous messages; documents use different words. The main moves:

  • Conversational rewrite: turn "and for contractors?" plus the chat history into a standalone query ("vacation policy for contractors"). Mandatory in multi-turn RAG: the retriever never sees the history.
  • Multi-query expansion: generate 3–5 paraphrases, retrieve for each, merge with Reciprocal Rank Fusion (RAG-Fusion). Buys recall on vocabulary mismatch.
  • HyDE: have the LLM write a hypothetical answer and embed that instead of the question. Answers look more like documents than questions do; hallucinated details matter little because only the embedding is used.
  • Decomposition: split multi-hop questions ("compare Q1 and Q2 churn") into sub-questions and retrieve each.
  • Step-back: also ask a more general question to fetch background principles.
  • Routing: send the query to the right index, tool or filter (SQL vs docs, product A vs B).

Each costs an extra LLM call before retrieval, ~0.2–1 s with a small model. Use a fast model, parallelize, and keep the original query in the mix so exact terms survive.

Code Rewrite, expand and HyDE in one call, fused with RRF
pythonRewrite, expand and HyDE in one call, fused with RRF
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()
MODEL = "gpt-4.1-mini"  # any small, fast chat model

class Queries(BaseModel):
    standalone: str        # follow-up resolved against the history
    variants: list[str]    # 3 paraphrases with different vocabulary
    hyde: str              # short passage that would answer it

def transform(history: list[dict], message: str) -> Queries:
    # One structured call instead of three: latency is the main cost
    resp = client.responses.parse(model=MODEL, text_format=Queries, input=[
        {"role": "system", "content": "Rewrite the last user message as a "
         "standalone search query, give 3 paraphrases, and write a ~80-word "
         "passage that would answer it."},
        *history, {"role": "user", "content": message}])
    return resp.output_parsed

def rrf(rankings: list[list[str]], k: int = 60) -> list[str]:
    scores: dict[str, float] = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

message = "and for contractors?"
q = transform(history, message)
queries = [message, q.standalone, *q.variants]   # keep the original too
runs = [hybrid_search(x, k=50) for x in queries]
runs.append(vector_search(embed(q.hyde), k=50))  # HyDE: embed the answer
candidates = rrf(runs)[:50]                      # then rerank
Real example

An HR assistant gets "How many vacation days do I get?", then "and in Mexico?". Embedding "and in Mexico?" alone returns the Mexico City office address. The rewrite step produces "annual vacation entitlement for employees in Mexico" and the Mexico leave policy jumps to #1. Later someone asks "Who gets more leave, Mexico or Spain?": one embedding lands near one country's policy and misses the other, so decomposition issues two sub-queries and retrieves both. Cost: one small-model call, ~300 ms, on every turn.

Trade-offs +3 · −4

+ You gain

  • Fixes follow-up turns, a frequent and silent failure in chat RAG.
  • Query-time only: no re-indexing, works with any retriever.
  • Multi-query and HyDE raise recall on vocabulary mismatch; routing shrinks the search space.

− You pay

  • An extra LLM call before retrieval even starts: ~0.2–1 s plus its token cost.
  • Rewrites drift: they drop a constraint, invent an entity or "fix" a product code.
  • Multi-query multiplies retrieval load ×3–5 and needs a fusion step.
  • HyDE misleads when the model doesn't know your domain: the fake answer lands in the wrong neighborhood.

Use it when

Multi-turn chat (the rewrite is mandatory), short or vague queries, users and documents using different vocabulary, multi-hop questions, or several indexes and tools to choose from.

Avoid it when

Exact lookups (IDs, error codes, SKUs) where a rewrite corrupts the key, tight latency budgets, or when recall@k is already high — measure before adding a call.

Numbers to know 3
  • Latency: +1 small-model call, ~0.2–1 s; produce rewrite, variants and HyDE passage in a single call.
  • Multi-query: 3–5 variants → retrieval fan-out ×3–5 → fuse with RRF, score = Σ 1/(60 + rank).
  • HyDE (Gao et al., 2022) is zero-shot: it beat the unsupervised Contriever retriever without any relevance labels.
Common pitfalls 4
  • Sending the raw follow-up ("what about it?") to the retriever, which has no access to the chat history.
  • Dropping the original query: search with it too, or you lose exact terms the rewrite paraphrased away.
  • Using your big answer model for a ~50-token rewrite; a small model is enough and much faster.
  • Shipping it unmeasured: compare recall@k per transform on real multi-turn logs; HyDE can hurt on niche domains.
Interview questions 3

Answer out loud first, then reveal.

Your chatbot answers the first question well but follow-ups badly. Why?Show answer

Because the retriever only sees the last message. "And for contractors?" has no subject, so its embedding matches noise. I add a conversational rewrite: a small model reads the last few turns and outputs a standalone query, which I embed, search and log. I keep the original message in a lexical search so exact terms survive. The trade-off is ~300 ms per turn and a new failure mode, a rewrite that drops a constraint, so I evaluate on real multi-turn conversations, not single questions.

HyDE or multi-query: when would you use each?Show answer

Both attack vocabulary mismatch. HyDE embeds a generated answer because answers sit closer to documents in embedding space than questions do; it's zero-shot and shines on short questions over general-knowledge corpora. It fails when the model doesn't know the domain: the fake answer points to the wrong neighborhood. Multi-query keeps the user's intent, fans out 3–5 paraphrases and fuses them with RRF; safer, but it multiplies retrieval load. I'd start with rewrite + hybrid search + reranker and add either only when recall@k on my eval set shows a gap.

How do you keep query transformation from blowing the latency budget?Show answer

Four levers. One call, not three: a single structured-output call returns the rewrite, the variants and the HyDE passage. A small, fast model, since the output is ~50–150 tokens. Skip it when it isn't needed: self-contained first turns, or exact-ID queries caught by a regex. And overlap work: start retrieval with the original query while the rewrite runs, then fuse. I watch end-to-end p95, not just the rewrite's own timing.