Sub topic 12
Rewriting and expanding queries
This chapter assumes you can already run top-k retrieval and know reciprocal rank fusion from the hybrid search chapter. It also assumes you can call an LLM from Python.
Why the raw question is often a poor query
Users type what they mean, not what the documents say. Two problems come up often:
- Missing context. In a chat, "What about its pricing?" has no subject. An embedding of that sentence matches nothing useful.
- Vocabulary mismatch. The user asks "How do I cancel?" and the document says "terminate your subscription." Both keyword and vector search can miss it.
Query transformation fixes this before retrieval. A model rewrites the question, or produces several versions of it, and you search with those.
Rewriting follow-up questions
Rewriting turns a question that depends on the conversation into one that stands alone. Give the model the history and ask for only the rewritten question.
def rewrite_prompt(history, question):
turns = "\n".join(f"{role}: {text}" for role, text in history)
return (
"Rewrite the last question so it makes sense on its own. "
"Replace pronouns with the names they refer to. "
"Return only the rewritten question.\n\n"
f"Conversation:\n{turns}\n\n"
f"Last question: {question}\nStandalone question:"
)With the history ("user", "Tell me about the Pro plan") and the question "What about its pricing?", a good rewrite is "What is the pricing of the Pro plan?"
Expanding into multiple queries
Expansion asks the model for a few paraphrases that use different vocabulary. You search with each one and merge the rankings with reciprocal rank fusion.
def reciprocal_rank_fusion(rankings, k=60):
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
def expand_queries(llm, question, n=3):
prompt = (
f"Write {n} alternative search queries for the question below, "
"using different wording. One per line, no numbering.\n\n"
f"Question: {question}"
)
variants = [line.strip("-• ").strip() for line in llm(prompt).splitlines()]
seen, queries = set(), []
for q in [question] + variants:
if q and q.lower() not in seen:
seen.add(q.lower())
queries.append(q)
return queries[: n + 1]
def multi_query_search(search, queries, k=5):
# search(query) returns a ranked list of document ids
return reciprocal_rank_fusion([search(q) for q in queries])[:k]
# Stand-ins so the example runs without a model or an index.
fake_llm = lambda prompt: "terminate subscription\nend my plan\ncancel account steps"
corpus = {"d1": "terminate your subscription", "d2": "billing cycles", "d3": "cancel by email"}
def fake_search(query):
words = set(query.lower().split())
scored = sorted(corpus, key=lambda d: -len(words & set(corpus[d].split())))
return scored
queries = expand_queries(fake_llm, "How do I cancel?")
print(queries)
print(multi_query_search(fake_search, queries, k=2))The original question stays in the list. Keeping it protects you when a variant drifts off topic.
Costs and pitfalls
- Latency and cost. Every rewrite is an extra model call, and every variant is an extra search. Use a small, fast model for this step.
- Drift. A rewrite can add facts the user never asked about. Keep the instruction narrow ("replace pronouns," "paraphrase") and log the rewritten queries.
- Needless rewriting. A self-contained question often retrieves well already. Rewrite only when there is history, or when evaluation shows vocabulary mismatch.
Exercise
A user asks "Does it support SSO?" after discussing the Enterprise plan. Which technique helps first, rewriting or expansion, and why?
Show answer
Rewriting. The question has no subject, so its embedding carries almost no meaning. Rewriting it to "Does the Enterprise plan support SSO?" gives retrieval something to match. Expansion can then add wording variants such as "single sign-on."