Sub topic 7
HyDE: Searching with a Hypothetical Answer
This chapter assumes you have a working RAG pipeline with an index, a retriever and a generation step. It also assumes you know what embeddings and cosine similarity are, can call an LLM with a text prompt, and can read Python. Earlier chapters covered conversational rewriting and multi-query expansion. HyDE is a different kind of rewrite. It does not rephrase the question. It replaces the question with a made-up answer and searches with that.
The gap HyDE targets
A dense retriever turns text into a vector and returns the stored passages whose vectors are closest. A question and a passage that answers it are different kinds of text. The question is short and interrogative, and it often uses the user's words. The passage is declarative, longer, and uses the document author's vocabulary.
Embedding models trained on question-passage pairs close much of this gap. It still shows up in three situations:
- The user describes a symptom and the document names the cause. "Why does my app keep kicking users out?" has little surface overlap with "Access tokens expire after one hour."
- The question is short and vague, so its vector sits in a generic region of the embedding space.
- The corpus is specialised, and the embedding model has seen few examples of how questions map to its passages.
HyDE stands for Hypothetical Document Embeddings. The idea is to ask an LLM to write a passage that would answer the question, embed that passage, and use the resulting vector as the query. The passage can contain factual mistakes. It only has to look like the kind of document you want to find. Because it is written in answer style, with domain vocabulary, its vector usually lies closer to the real answer passages than the question's vector does.
How the pipeline changes
HyDE adds one LLM call before retrieval. Nothing else in the pipeline changes. The index is the same, the vector search is the same, and the generation step still receives real retrieved passages.
The hypothetical text is a means to get a vector. It is not evidence, and it should not reach the final prompt as if it were.
A runnable implementation
The function below takes the model calls as arguments, so you can plug in any provider. It optionally averages the hypothetical vector with the question vector. This keeps some anchor to what the user actually asked.
import math
from typing import Callable
Vector = list[float]
def mean_vector(vectors: list[Vector]) -> Vector:
return [sum(values) / len(vectors) for values in zip(*vectors)]
def hyde_search(
question: str,
llm: Callable[[str], str],
embed: Callable[[str], Vector],
search_by_vector: Callable[[Vector, int], list[str]],
top_k: int = 5,
include_question: bool = True,
) -> list[str]:
prompt = (
"Write a short passage (3 to 5 sentences) from a reference document "
"that answers the question below. Use the technical vocabulary a "
"document author would use. Do not mention the question.\n\n"
f"Question: {question}"
)
hypothetical = llm(prompt).strip()
vectors = [embed(hypothetical)]
if include_question:
vectors.append(embed(question))
return search_by_vector(mean_vector(vectors), top_k)
# --- Toy demo with stand-ins for the model and the index ---
VOCAB = ["token", "expire", "refresh", "login", "session", "hour", "cache", "invalid"]
DOCS = {
"d1": "Access tokens expire after one hour. Use the refresh token to get a new access token.",
"d2": "Clear the cache to fix stale pages.",
"d3": "A session ends when the user logs out.",
}
def toy_embed(text: str) -> Vector:
words = text.lower().replace(".", " ").replace(",", " ").split()
return [float(sum(w.startswith(v) for w in words)) for v in VOCAB]
def cosine(a: Vector, b: Vector) -> float:
norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
return sum(x * y for x, y in zip(a, b)) / norm if norm else 0.0
def toy_search(vector: Vector, k: int) -> list[str]:
ranked = sorted(DOCS, key=lambda d: cosine(vector, toy_embed(DOCS[d])), reverse=True)
return ranked[:k]
def fake_llm(prompt: str) -> str:
return (
"Access tokens expire after a short time. When the token expires, "
"the session is invalid and the user must login again with a refresh token."
)
question = "Why does my app keep kicking users out?"
print(toy_search(toy_embed(question), 1)) # the raw question matches nothing
print(hyde_search(question, fake_llm, toy_embed, toy_search, top_k=1, include_question=False))The first print shows the failure. The question shares no vocabulary with the corpus, so its vector is all zeros and the ranking is arbitrary. The second print returns ['d1'], the passage about token expiry, because the hypothetical answer contains the words the document uses. The toy embedding only counts words, so a real embedding model will behave less sharply, but the mechanism is the same.
Design choices
What to embed. You have three options: the hypothetical alone, the question alone (the baseline), or an average of both. Averaging is a safe default. It limits the damage when the hypothetical goes in the wrong direction. Using the hypothetical alone gives the largest gains when the question is vague. It also gives the largest losses when the model misreads the question.
How many hypotheticals. The original HyDE method samples several hypothetical documents and averages their vectors. This smooths out the noise in any single generation. It costs more tokens, and the calls can run in parallel, so latency barely grows. One sample is a reasonable starting point. Move to three or five if evaluation shows that results are unstable.
Length and style of the hypothetical. Match the style of your corpus. If your index holds API reference pages, ask for a reference-style paragraph. If it holds support tickets, ask for a ticket-style resolution. A hypothetical that is much longer than your chunks tends to drift toward a topic average, so aim for roughly the size of one chunk.
Keyword search. HyDE also helps BM25. The hypothetical answer adds vocabulary the question lacked, which acts as query expansion. In a hybrid system, you can run the hypothetical through the keyword index and merge the results with the baseline using reciprocal rank fusion.
How HyDE compares with other rewrites
| Technique | Failure it addresses | What it produces | Extra cost |
|---|---|---|---|
| Conversational condensing | Follow-up depends on earlier turns | One standalone question | One short LLM call |
| Multi-query expansion | One phrasing misses relevant passages | Several questions | One call and several searches |
| HyDE | Question and passage use different vocabulary or style | A fake answer passage | One longer LLM call |
| Step-back | Question is too specific for the available passages | A broader question | One short LLM call |
Use HyDE when the right documents exist but the question's wording does not lead to them. Do not use it when the question is already specific and uses the corpus vocabulary, such as an error code or a product name.
Failure modes
- Confident wrong specifics. The model may invent a version number, a function name or a figure. The embedding then pulls toward passages that mention that invented detail. This risk is highest for topics after the model's training cutoff and for private corpora the model has never seen.
- Wrong domain. If the question is ambiguous ("How do I reset the cache?"), the model picks one interpretation. The retriever then commits to it. Averaging with the question vector, or adding multi-query expansion, reduces this.
- Exact-match queries. Searches for identifiers, error strings or names rely on exact tokens. A hypothetical answer may paraphrase or drop them. Route these queries to keyword search without HyDE.
- Little gain on strong retrievers. If your embedding model already handles question-to-passage matching well, HyDE may add latency and nothing else.
- Leakage into the answer. If you pass the hypothetical to the generator, the model may repeat its invented claims as facts.
Cost and latency
HyDE adds one generation call before search begins. Generating 100 to 150 tokens usually takes noticeably longer than a condensing call that returns one sentence. Because the search cannot start until the generation finishes, the added time sits directly on the critical path. A smaller, faster model is often good enough for the hypothetical, since it only needs to produce the right vocabulary. You can also cache hypotheticals for repeated questions.
Measure before adopting HyDE. The next chapters cover evaluation in detail, but the check is simple. Take a set of questions with known relevant passages, run retrieval with and without HyDE, and compare recall at k. Look at the questions that got worse as well as the average, because HyDE tends to help some queries a lot and hurt others.
Exercise
A user asks, "What is the error E4021?" Your corpus contains a page that says "E4021: upstream connection timed out." Should you apply HyDE here, and what would you do instead?
Show answer
HyDE is a poor fit. The query depends on an exact identifier, and a model that has never seen your error codes will invent a plausible but wrong description, pulling the search away from the real page. Search with the raw question, preferably through keyword (BM25) or hybrid search so the exact token "E4021" matches. If you still want HyDE for other questions, route queries that contain identifiers or error codes around it.
Exercise
Your HyDE function averages the hypothetical vector with the question vector. On a test set, recall at 5 improves for vague questions but drops for specific ones. Name two changes you could try.
Show answer
Options include: weight the question vector more heavily for short, specific queries; apply HyDE only when a router detects a vague or symptom-style question; generate several hypotheticals and average them to reduce the effect of one bad generation; or run the baseline and HyDE searches separately and merge the two ranked lists with reciprocal rank fusion.