Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 23. Advanced RAG
  4. 23.4

Lesson 23.4 · 4 of 7 · 4 min read · Reviewed 24 Nov 2026

Query rewriting and expansion

By the end, you can

  • Rewrite and expand queries before searching.
  • Handle conversational follow-up questions.

Query rewriting

A small model call turns a conversational question into a search query:

history:  "How long do I have to return shoes?"  -> answered: 30 days
question: "and for sale items?"
rewrite:  "return policy window for sale items"

This is a prompt chain (chapter 15): rewrite, then retrieve, then answer.

Query expansion

Technique How Helps when
Multi-query Generate 3 to 5 phrasings; search each; merge Vocabulary varies
Decomposition Split “compare A and B” into two queries Questions span topics
Hypothetical answer Ask the model to draft an answer; embed that; search Questions are short, documents are long
Synonyms and acronyms “PTO” also searches “annual leave” Domain jargon

Costs

Each technique adds a model call and more searches. Use evaluationEval: A repeatable test that measures how well an AI system performs on a set of cases with defined success criteria. to keep only the ones that help your questions (chapter 26).

Keep the original

Search with the rewritten query, but answer the user’s original question, with the conversation, so tone and intent are preserved.

Key points

  • User questions are often short, vague, or depend on earlier turns ('what about the blue one?').
  • Rewrite the question into a standalone search query using the conversation, before retrieving.
  • Expansion generates several queries or a hypothetical answer to search with, improving recall.
Hands-on labRuns in the Playground

Rewrite follow-ups into standalone queries

Turn a conversational follow-up into a standalone search query, and see how it changes what retrieval finds.

You will have: A rewrite() function and the top result for the raw and rewritten follow-up.

Steps

  1. Read the conversation: the user asked about the Trailrunner 3, then asked 'and is the blue one waterproof?'.
  2. Write rewrite(): replace 'the blue one' with the colour plus the last product named in the conversation, and drop filler words.
  3. Search the catalogue with the raw follow-up and with the rewrite.
  4. Keep the original question for the answer step.

Done when

  • The raw follow-up's top result is not about the Trailrunner 3.
  • The rewritten query's top result is the Trailrunner 3 blue spec page.

Open in the Playground No API key needed.

Starter code (Python)
import math, re
from collections import Counter

STOP = {"a", "an", "the", "to", "of", "and", "or", "is", "are", "be", "in", "on", "for", "if", "it", "by", "you", "your", "may", "can", "do", "i", "what", "has", "have", "not", "into", "up", "this", "that", "with", "from", "over"}

def words(text):
    out = []
    for w in re.findall(r"[a-z0-9]+", text.lower()):
        if w in STOP:
            continue
        out.append(w[:-1] if w.endswith("s") and len(w) > 3 else w)
    return out

def embed(text):
    """A toy embedding: content-word counts. Real systems use an embedding model."""
    return Counter(words(text))

def cosine(a, b):
    dot = sum(a[k] * b[k] for k in a)
    na = math.sqrt(sum(v * v for v in a.values())); nb = math.sqrt(sum(v * v for v in b.values()))
    return dot / (na * nb) if na and nb else 0.0

def rank_of(target, query_vec, docs):
    order = sorted(docs, key=lambda d: -cosine(query_vec, embed(docs[d])))
    return order.index(target) + 1

PRODUCTS = ["Trailrunner 3", "Roadster 2"]
CATALOGUE = {
    "paint": "Blue paint for outdoor furniture, waterproof finish",
    "raincoat": "Waterproof blue raincoat for walkers",
    "tr3-blue": "Trailrunner 3 shoe in blue: waterproof membrane, sizes 36 to 47",
    "tr3-sizes": "Trailrunner 3 shoe sizes and fit guide",
    "rs2": "Roadster 2 shoe in blue, not waterproof",
}
HISTORY = ["What sizes does the Trailrunner 3 come in?"]
FOLLOW_UP = "and is the blue one waterproof?"

def rewrite(history, question):
    # TODO: find the last product from PRODUCTS mentioned in history
    # TODO: replace "the blue one" with "the blue <product>" and drop a leading "and"
    return question

def top(query):
    qv = embed(query)
    return max(CATALOGUE, key=lambda d: cosine(qv, embed(CATALOGUE[d])))

print("raw:      ", top(FOLLOW_UP))
print("rewritten:", rewrite(HISTORY, FOLLOW_UP), "->", top(rewrite(HISTORY, FOLLOW_UP)))
Show a solution
import math, re
from collections import Counter

STOP = {"a", "an", "the", "to", "of", "and", "or", "is", "are", "be", "in", "on", "for", "if", "it", "by", "you", "your", "may", "can", "do", "i", "what", "has", "have", "not", "into", "up", "this", "that", "with", "from", "over"}

def words(text):
    out = []
    for w in re.findall(r"[a-z0-9]+", text.lower()):
        if w in STOP:
            continue
        out.append(w[:-1] if w.endswith("s") and len(w) > 3 else w)
    return out

def embed(text):
    """A toy embedding: content-word counts. Real systems use an embedding model."""
    return Counter(words(text))

def cosine(a, b):
    dot = sum(a[k] * b[k] for k in a)
    na = math.sqrt(sum(v * v for v in a.values())); nb = math.sqrt(sum(v * v for v in b.values()))
    return dot / (na * nb) if na and nb else 0.0

def rank_of(target, query_vec, docs):
    order = sorted(docs, key=lambda d: -cosine(query_vec, embed(docs[d])))
    return order.index(target) + 1

PRODUCTS = ["Trailrunner 3", "Roadster 2"]
CATALOGUE = {
    "paint": "Blue paint for outdoor furniture, waterproof finish",
    "raincoat": "Waterproof blue raincoat for walkers",
    "tr3-blue": "Trailrunner 3 shoe in blue: waterproof membrane, sizes 36 to 47",
    "tr3-sizes": "Trailrunner 3 shoe sizes and fit guide",
    "rs2": "Roadster 2 shoe in blue, not waterproof",
}
HISTORY = ["What sizes does the Trailrunner 3 come in?"]
FOLLOW_UP = "and is the blue one waterproof?"

def rewrite(history, question):
    product = None
    for turn in history:
        for p in PRODUCTS:
            if p.lower() in turn.lower():
                product = p
    q = question.strip().rstrip("?")
    if q.lower().startswith("and "):
        q = q[4:]
    if product:
        q = q.replace("the blue one", f"the blue {product}")
    return q

def top(query):
    qv = embed(query)
    return max(CATALOGUE, key=lambda d: (cosine(qv, embed(CATALOGUE[d])), d))

raw = top(FOLLOW_UP)
rq = rewrite(HISTORY, FOLLOW_UP)
print("raw follow-up top result:", raw)
print("rewritten query:", rq)
print("rewritten top result:", top(rq))
print("answer step still uses:", FOLLOW_UP)
Quick checkIn a chat, the user asks 'and for sale items?' after a question about return windows. What should be searched?
How sure are you?
Pick an answer and how sure you are