Velamuvi AIAcademy

Lesson 11 of 16 · Retrieval

Query Rewriting

Improve RAG retrieval by rewriting questions: standalone follow-ups, several phrasings fused together, hypothetical answers (HyDE) and sub-questions.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why the user's exact words are often a poor search query
  • Rewrite follow-up questions into standalone questions using the conversation
  • Use multi-query retrieval and fuse the results
  • Know when to use HyDE and question decomposition, and what they cost

The question is not always a good query

Users type questions the way they talk: “and for that?”, “who pays for dinner?”, “compare the two plans”. Documents are written differently. Query rewriting uses an LLM (usually a small, cheap one) to turn the user's message into one or more better search queries before retrieval.

Follow-ups need the conversation

In a chat, the second question often depends on the first. Searching with the follow-up alone loses the topic:

Try it yourselfPython
import math, re

# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
    "leave":     "leave holiday holidays vacation annual time-off carried",
    "sick":      "sick ill illness unwell doctor self-certify",
    "remote":    "remote home hybrid office hours",
    "expenses":  "expenses expense claim reimbursed receipt receipts meals",
    "equipment": "laptop laptops monitor headset equipment lost stolen",
    "security":  "password passwords 2fa two-factor login phishing security",
    "parental":  "parental maternity paternity baby birth adoption adoptive",
    "training":  "training course courses learning books conferences",
    "travel":    "travel trip trips flight flights train trains journeys",
    "pay":       "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}

def words(text):
    return re.findall(r"[a-z0-9'-]+", text.lower())

def embed(text):
    v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
    length = math.sqrt(sum(x * x for x in v))
    return [x / length for x in v] if length else v

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))       # vectors are unit length

# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
    "Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
    "Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
    "Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
    "Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
    "Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
    "Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
    "Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
    "Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
    "Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}

VECS = {t: embed(t + ". " + text) for t, text in HANDBOOK.items()}

def top(query, k=2):
    q = embed(query)
    matches = [t for t in VECS if cosine(q, VECS[t]) > 0]          # ignore unrelated sections
    return sorted(matches, key=lambda t: cosine(q, VECS[t]), reverse=True)[:k]

# 1. A follow-up question only makes sense with the conversation before it
history = "User: My partner is having a baby in May.\nAssistant: Congratulations!"
follow_up = "How much leave do I get for that?"
rewritten = "How much paternity or partner leave do I get when my partner has a baby?"   # written by an LLM
print("Follow-up as typed:", top(follow_up))
print("Rewritten:         ", top(rewritten))

# 2. Users and documents use different words
question = "Who pays for my dinner on a work trip?"
rewrites = [                      # an LLM generates several phrasings
    question,
    "Are meals reimbursed on business trips?",
    "Can I claim food as an expense when travelling?",
]

fused = {}
for r in rewrites:
    for pos, title in enumerate(top(r, k=3), start=1):
        fused[title] = fused.get(title, 0) + 1 / (60 + pos)
print()
print("Original question:", top(question))
print("Multi-query fused:", sorted(fused, key=fused.get, reverse=True)[:2])

“How much leave do I get for that?” on its own found annual leave, a sensible guess but the wrong section. The rewritten, standalone question, which an LLM wrote using the conversation, puts parental leave first.

A prompt for this step can be short:

Here is a conversation and a follow-up question. Rewrite the follow-up as a
standalone question that includes everything needed to understand it.
Reply with the question only.

Conversation:
user: My partner is having a baby in May.
assistant: Congratulations!

Follow-up: How much leave do I get for that?

Multi-query: several phrasings, fused

The second part of the program shows a vocabulary mismatch: “Who pays for my dinner on a work trip?” mostly matched the travel section, because “dinner” and “pays” mean nothing to the retriever. Asking an LLM for a few alternative phrasings (“Are meals reimbursed on business trips?”), searching with each, and fusing the results with RRF puts the expenses section first.

HyDE and decomposition

The hypothetical answer may contain wrong facts. That doesn't matter, because it's only used for searching and is never shown to the user. Its job is to sound like the documents.

Decomposition splits a complex question into simpler ones: “Do partners get more leave than the training budget allows for courses?” becomes “How much leave do partners get?” and “What is the training budget?”, each retrieved separately, with all the results given to the model.

Common mistakes

Practice exercise

Build the prompt for conversational query rewriting. The LLM's answer (something like: Does the training budget cover books?) is what you would search with.

Your solutionPython
history = [
    ("user", "Do we get a training budget?"),
    ("assistant", "Yes, 1,000 euros per year."),
]
follow_up = "Does it cover books?"

# Build a prompt asking an LLM to rewrite the follow-up as a standalone search query.
# Print exactly:
# Rewrite the last question so it makes sense on its own.
# user: Do we get a training budget?
# assistant: Yes, 1,000 euros per year.
# user: Does it cover books?
# Standalone question:
Knowledge check

What does HyDE search with?

Summary

  • User questions are often poor search queries; query rewriting improves them before retrieval.
  • Rewrite follow-ups into standalone questions using the conversation.
  • Multi-query retrieval searches with several phrasings and fuses the results.
  • HyDE searches with a hypothetical answer; decomposition splits complex questions.
  • Rewriting costs an extra LLM call: keep the original question for the final answer.

Next: writing prompts that keep answers grounded in the sources, with citations.

Finished reading? Tick it off to track your progress.