Sub topic 7
HyDE: searching with a hypothetical answer
This chapter assumes you know how a basic RAG pipeline works, how embedding search ranks passages, and how to call an LLM with a prompt. It also assumes you can read Python.
The idea
A question and its answer often look different. The question "Why does my build fail on Apple chips?" shares few words with a passage that says "ARM64 wheels are unavailable for this package." An embedding model places the two texts in different regions of the vector space, so the right passage can rank low.
Hypothetical Document Embeddings (HyDE) closes this gap. You ask the LLM to write a plausible answer, then search with that answer instead of the question. The answer is in the same style and vocabulary as your documents, so it lands closer to them in the vector space.
The hypothetical answer may be wrong. You never show it to the user. You only use it as a search probe. The facts in the final answer come from the retrieved passages.
Where it sits in the pipeline
A minimal implementation
The function below follows the same interface as the other chapters: search(query, top_k) returns a list of passages. The demo uses stub functions so you can run it without a model.
from typing import Callable
def hyde_search(
question: str,
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
top_k: int = 5,
keep_question: bool = True,
) -> list[str]:
prompt = (
"Write a short passage, like one from technical documentation, "
"that answers the question below. It is fine if some details "
"are uncertain.\n\n"
f"{question}"
)
draft = llm(prompt).strip()
query = f"{question}\n{draft}" if keep_question else draft
return search(query, top_k)
def fake_llm(prompt: str) -> str:
return "Builds fail because ARM64 wheels are missing for the package."
def fake_search(query: str, top_k: int) -> list[str]:
docs = [
"ARM64 wheels are unavailable for older releases.",
"Pricing tiers are listed on the billing page.",
]
words = set(query.lower().split())
ranked = sorted(docs, key=lambda d: -len(words & set(d.lower().split())))
return ranked[:top_k]
print(hyde_search("Why does my build fail on Apple chips?", fake_llm, fake_search, top_k=1))The keep_question flag appends the draft to the original question. This is a common safeguard. If the draft is off-topic, the question still anchors the search.
When HyDE helps
HyDE targets vocabulary mismatch between short questions and long, technical documents. It works best when:
- The question is short and abstract, and the documents are detailed.
- The model knows the domain well enough to write a draft in the right register.
- You use dense (embedding) search. Keyword search needs the draft's exact terms to appear in the documents.
Common errors
- Confident but wrong drafts. If the model invents a wrong product name or version, the search follows it. Keeping the question in the query reduces this.
- Private or new topics. The model has never seen your internal terms, so its draft uses generic words. HyDE adds little here, and it adds one LLM call of latency.
- Drafts that are too long. A long draft can drift away from the user's intent. Ask for a short passage.
- Using the draft as evidence. Never pass the draft to the answer step as a source. Pass only retrieved passages.
Choosing HyDE
Use HyDE when a short question fails to match long passages. Use multi-query expansion when one phrasing is not enough. Use decomposition when the question has several parts. You can also combine HyDE with rank fusion by searching with both the question and the draft, then merging the two ranked lists.
Exercise
A user asks "How do I rotate keys?" and your index holds long security runbooks. Your HyDE search returns worse results than the raw question for queries about your company's internal tool "VaultX". What is the likely cause, and what change would you try?
Show answer
The model does not know VaultX, so its draft describes generic key rotation and pulls the search toward generic passages. Try keep_question=True so the original terms stay in the query, or merge the raw-question results and the HyDE results with reciprocal rank fusion. Compare each variant with the raw-question baseline on a set of test queries.