What are query rewriting and HyDE in retrieval?

Learning path, stage 3 of 5: RAG and fine-tuning · question 7 of 10

User queries are often short, vague or full of conversational references ("what about the second one?"). Query transformation uses an LLM to turn them into better search queries before retrieval. HyDE (Hypothetical Document Embeddings) goes further: the LLM writes a hypothetical answer, and you embed that, because a fake answer usually sits closer in vector space to real answers than the question does.

Techniques

  • Standalone rewrite: resolve chat references using the conversation history ("it" → "the Pro plan").
  • Multi-query: generate 3–5 variations, retrieve for each, merge (for example with RRF).
  • Decomposition: split a compound question into sub-questions, retrieve for each.
  • Step-back: ask a more general question to fetch background first.
  • HyDE: embed a generated answer instead of the query.

Trade-offs

  • An extra LLM call adds latency and cost. Use a small, fast model for the rewrite.
  • HyDE can drift if the model's guess is wrong, so combine it with the original query.
  • Measure the effect with recall@k. Don't assume it helps.

Sources

Code example

tsx
1// Rewrite + HyDE, run in parallel, results fused with RRF.
2import Anthropic from "@anthropic-ai/sdk";
3
4declare function vectorSearch(text: string, k: number): Promise<{ id: string; text: string }[]>;
5declare function rrf(lists: { id: string; text: string }[][]): { id: string; text: string }[];
6
7const client = new Anthropic();
8const ask = async (prompt: string) => {
9 const r = await client.messages.create({
10 model: "claude-haiku-5-5", // a small, fast model is enough for rewriting
11 max_tokens: 400,
12 messages: [{ role: "user", content: prompt }],
13 });
14 return r.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
15};
16
17export async function transformAndRetrieve(history: string, query: string) {
18 const [standalone, hypothetical] = await Promise.all([
19 ask(`Conversation:\n${history}\n\nRewrite "${query}" as a standalone search query. Output only the query.`),
20 ask(`Write a short passage that would answer: "${query}". Plausible detail is fine.`),
21 ]);
22 const lists = await Promise.all([query, standalone, hypothetical].map((t) => vectorSearch(t, 20)));
23 return rrf(lists).slice(0, 8);
24}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app