HyDE
Search with a draft answer.
Questions and answers are written differently. HyDE, short for hypothetical document embeddings, asks the model to write a draft answer first. The draft looks like a help page, so it matches help pages better than the question does.

- Questions look different
- Write a draft answer
- Search with the draft
Searching with a draft
The model writes a short, likely answer, without seeing our documents. The draft may be wrong on details, but it uses the right words. We search with the question, then with the draft. Run it. The question misses, but the draft finds the charging chunk.
from rag_kit import load_docs, make_chunks, Index
from llm import llm
index = Index(make_chunks(load_docs()))
q = "How many hours until my e-bike is full again?"
draft = llm.invoke(f"Write a short, likely answer to this question, as a help page would: {q}").text
print("question finds:", index.search(q, 1)[0][1]["text"][:40])
print("draft finds: ", index.search(draft, 1)[0][1]["text"][:40])question finds: ## Parts and electrics Components such a draft finds: ## Charging The Volt 500 battery charges
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Using HyDE safely
Only search with the draft. Never show it to the customer, because it may contain made up facts. HyDE adds one model call, and helps most when questions are short or oddly worded.
| key | value |
|---|---|
| Draft | for search only |
| Never show | may be wrong |
| Cost | one model call |
| Best for | odd questions |
Summary
HyDE searches with a draft answer, which looks more like your documents than the question does. Next, splitting big questions.
Key takeaways- Write a draft
- Search with it
- Never show it