HyDE (hypothetical document embeddings): search with an imagined answer
HyDE asks a model to write a pretend answer, then searches with that text instead of the short question. Use it when questions are short or vague and the documents are written in a different style.
HyDE in 60 seconds
- What: a language model writes a hypothetical document that answers the question, and that text is embedded and used for the search.
- Why it works: the pretend answer looks like real documents, so it lands near them in embedding space even though the question did not.
- Safety net: the final answer must come from the real retrieved passages, never from the pretend one.
- Tips: write several hypotheticals, combine them, and include the original query.
- Cost: one extra model call before every search, and a risk of drift if the pretend answer is wrong.
Where this type fits
HyDE is in the quality-loop family, but it improves quality before retrieval and not after. Its one job is to produce a better search input. It pairs naturally with the other members: corrective, self, and advanced retrieval. See the overview of RAG types for the whole map.
The problem it solves
A question and its answer rarely look alike. The question why does my build fail on the second run? is eight words long and uses everyday language. The document that explains it may be a long page on cache invalidation, written in formal terms, with none of the question's words in it. Embedding models do a fair job of linking them, but they were trained on a mix of text, and the gap between short query and long passage is exactly where they lose precision.
Think of looking for a book in a library by shouting a question at the shelves. You would do better to describe what the book probably says: write a paragraph in the style of the book and see which shelf it resembles. HyDE does the same. It asks a model to imagine the answer, in the voice and vocabulary of a real document, and uses that imagined text as the search key.
The imagined answer may contain mistakes. That does not matter much, and the reason is the heart of the method. The search does not read the pretend text for facts. It only uses its embedding to find the closest real documents. Invented specifics, such as a wrong number, are unlikely to match anything and tend to get ignored, while the general shape and topic of the answer still point to the right region.
How it works
- Receive the query: the user's question arrives as usual.
- Generate hypotheticals: an instruction-following model is asked to write a passage that answers the question. It is told not to hedge and not to worry about accuracy, since the text is only a search key.
- Embed: an encoder turns the hypothetical passage, or the average of several, into one vector.
- Search: the vector store returns the real documents nearest to that vector.
- Optionally combine: merge the results with those from the original query, using a fusion rule such as reciprocal rank fusion.
- Generate the answer: the model answers from the real retrieved passages only, with citations.
The method was introduced in Precise Zero-Shot Dense Retrieval without Relevance Labels (Gao et al., 2022). The authors describe an instruction-following model that writes a hypothetical document capturing relevance patterns, an encoder that maps it to a vector, and retrieval of the nearest real documents. They describe the encoder's compression as a bottleneck that filters out incorrect details, which is the effect described above.
The diagram shows why the final generator is kept apart from the hypothetical step. If the pretend text reached the final prompt, a wrong invented fact could become a stated fact. Keeping it out means HyDE can only affect which documents are found, not what the answer claims.
A worked example
Acme has a runbook library. An engineer asks: why does my deploy hang after the second retry?
- Plain search: the five-word core of the query matches two forum-style posts about retries in general. The runbook that explains the real cause is not in the top ten.
- Hypothetical 1: When a deployment hangs after repeated retries, the deployment controller is often waiting for a lock held by an earlier failed attempt. The lock is released only after a timeout...
- Hypothetical 2: A stuck deploy after retries can come from a health check that keeps failing, so the rollout never completes...
- Hypothetical 3: Deployments may hang when a stale lease prevents the next attempt from acquiring the release lock...
- Embed and average: the three texts become three vectors and one average vector, together with the original query vector.
- Search: the runbook titled Release locks and lease expiry is now the second result, and the health-check runbook is fourth.
- Answer: the model reads the two real runbooks and explains the lock timeout, quoting the 15 minute lease from the page. The hypotheticals never appear in the prompt.
{
"query": "why does my deploy hang after the second retry?",
"hypotheticals": [
"When a deployment hangs after repeated retries, the controller is often waiting on a lock held by an earlier failed attempt...",
"A stuck deploy after retries can come from a health check that keeps failing...",
"Deployments may hang when a stale lease prevents the next attempt from acquiring the release lock..."
],
"search_vectors": ["query", "mean(hypotheticals)"]
}Building it
# Placeholders: llm.generate(), embed(), vector_store. Replace with your own.
N_HYPOTHETICALS = 3 # more samples smooth out one bad guess
TOP_K = 8
HYDE_TIMEOUT_S = 4 # skip HyDE if generation is slow
HYDE_PROMPT = '''Write a short passage, in the style of a technical document,
that answers the question below. Be direct. Accuracy is not required.
Question: {q}'''
def mean(vectors):
n = len(vectors)
return [sum(v[i] for v in vectors) / n for i in range(len(vectors[0]))]
def hypothetical_vector(question):
texts = []
for _ in range(N_HYPOTHETICALS):
# Non-zero temperature so the samples differ from one another.
texts.append(llm.generate(HYDE_PROMPT.format(q=question),
temperature=0.7, timeout=HYDE_TIMEOUT_S)) # placeholder
return mean([embed(t) for t in texts]) # placeholder
def rrf(rankings, k=60):
# Reciprocal rank fusion: reward documents that rank well in any list.
score = {}
for ranking in rankings:
for rank, doc in enumerate(ranking):
score[doc.id] = score.get(doc.id, 0.0) + 1.0 / (k + rank + 1)
return sorted(score, key=score.get, reverse=True)
def retrieve(question):
plain = vector_store.search(embed(question), k=TOP_K)
try:
hyde = vector_store.search(hypothetical_vector(question), k=TOP_K)
except TimeoutError:
return plain # degrade to plain search, never fail the request
fused_ids = rrf([plain, hyde])[:TOP_K]
by_id = {d.id: d for d in plain + hyde}
return [by_id[i] for i in fused_ids]
def answer(question):
passages = retrieve(question)
# Only real passages go in the prompt, never the hypothetical text.
prompt = ('Answer only from the passages. Cite them.\n'
+ '\n'.join(p.text for p in passages) + '\nQuestion: ' + question)
return llm.generate(prompt)Two choices in the code are worth noting. The fallback to plain search means a slow or failing generator never takes the whole feature down. And the fusion step keeps the original query in the mix, which protects against a hypothetical that wandered off topic.
Design decisions
- Where to apply it: use HyDE only for query types that benefit, such as short or vague ones, selected by a simple rule or a classifier. Plain search stays the default for exact lookups like error codes.
- Number of hypotheticals: three is a sensible start. More improves stability and increases cost and delay linearly.
- Model size: a small, fast model is usually enough because the text is only a search key. Reserve the large model for the final answer.
- Combine with the original query: fuse both result lists. This guards against drift and keeps exact-term matches that embeddings blur.
- Caching: cache hypothetical vectors by normalised query text. Repeated questions then skip the generation call.
- Failure handling: set a timeout and degrade to plain search. Log how often that happens.
- Access control: apply permission filters at search time as usual. The hypothetical text must not be stored with user data beyond its cache lifetime.
Measuring it
- Recall at k: for labelled questions, the share where a known relevant document appears in the top k results, with and without HyDE.
- Mean reciprocal rank: the average of one over the rank of the first relevant document, which shows whether HyDE moves the right result upward.
- Win and loss analysis: list questions where HyDE helps and where it hurts. Exact-term queries often get worse.
- Answer faithfulness: confirm that final answers still cite only real passages and that no hypothetical content leaks in.
- Added latency and cost: the generation time and tokens per request, and the cache hit rate.
def recall_at_k(examples, search, k=5):
# examples: (question, set_of_relevant_doc_ids) labelled by people.
hits = 0
for question, relevant in examples:
found = {d.id for d in search(question)[:k]}
hits += bool(found & relevant)
return hits / len(examples) if examples else 0.0
# Compare: recall_at_k(data, plain_search) versus recall_at_k(data, retrieve)When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Users type short or vague questions | Yes | The pretend answer supplies the missing vocabulary and context. |
| Documents are long and formal, questions are casual | Yes | The pretend document bridges the difference in style. |
| No labelled relevance data exists to train a retriever | Yes | The method was designed for retrieval without relevance labels. |
| Queries are exact identifiers, codes, or names | No | Keyword or hybrid search matches these better, and a pretend answer adds noise. |
| The topic is very new or niche to the model | With care | The pretend answer may be far off and pull the search away from the right area. |
| Latency budget is very tight | Only with caching | Each uncached request pays for a generation call. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Better recall for short or vague questions; possible harm for exact-term ones. | Route by query type and fuse with plain search. |
| Latency | A model call before every search. | Use a small model, a timeout, and a cache. |
| Cost | Tokens for one to several hypotheticals per request. | Limit samples and cache by normalised query. |
| Complexity | A prompt, a fusion rule, and routing to maintain. | Keep the pipeline small and measure each part. |
| Failure modes | A wrong pretend answer pulls the search off topic; the model may refuse or hedge. | Include the original query and fall back to plain search. |
Compared with related types
Advanced RAG includes query rewriting and expansion, and HyDE can be seen as one special kind of query expansion: instead of rewording the question, it writes an answer. In an advanced pipeline, HyDE is one option before retrieval, alongside metadata filters and hybrid search.
Simple RAG embeds the question itself, which is cheaper and often good enough. Branched RAG also creates several variants, but it splits the question into sub-questions or interpretations and answers each, whereas HyDE only uses its variants to search.
What this means for your role
Common mistakes
Further reading
- Precise Zero-Shot Dense Retrieval without Relevance Labels by Gao et al., 2022, the paper that introduced HyDE.
- Vector search and chunking for how embeddings and nearest-neighbour search behave.
- Caching types in AI systems for caching hypothetical vectors and other model-side results.
HyDE changes only what you search with, which makes it one of the safer ways to improve recall. Test it on your own questions, and keep the pretend document out of the answer.