Back to Tutorials
LLM Application Development
Intermediate

Query Rewriting: Fixing the Question Before You Search

Follow-ups like “how long does it take?” break RAG search. Rewrite 22 help-desk chats four ways with a small open model and see where the answer lands, and where rewriting makes it worse.

10 minInteractive: drag, click and try things as you read


A chatbot built on retrieval looks up its answers in your documents, and it searches with whatever the customer typed. People don’t type search queries. They type “and the other one?” and “how long does it take?”, which only make sense halfway through a conversation. Search with what the customer means, not just what they typed: rewrite the question before you retrieve. Here you’ll take 22 made-up help-desk chats, fix each search four ways (three of them written by a small open model), and see where the passage that answers it lands.

Why follow-ups break search#

In retrieval-augmented generation (RAG), a question goes to a search engine first, the top few passages go into the prompt, and the model answers from them. The search engine sees only the text it is given, not the conversation. A follow-up like “how long does it take?” has no product, no place and no topic in it, so search falls back on whatever happens to match “long” and “take”.

The fix is a step before search, called query rewriting: give a language model the conversation and ask it for a standalone search query, “How long does it take to ship to Ireland?”. It’s one extra model call, usually to a small, fast model.

Predict first

A customer asks “Do you ship to Ireland?”, the bot says yes, and the customer asks “how long does it take?”. A vector search of the help centre with just that last message: what comes top?

Try it
The help centre is the same 50 made-up Hearth passages as in the reranking explainer; the conversations are made up too. The rewrites and draft answers were written by Qwen3-4B, a small open model, run offline and shown exactly as it wrote them. Keyword scores are computed live; vector scores come from all-MiniLM-L6-v2, computed offline.

Four ways to fix the query#

  • Search the whole conversation. No model call at all: paste every turn into the query. The missing context is in there, along with everything else that was said.
  • Rewrite it. Ask a model for one standalone query, as above. The prompt we used gives three short worked examples, which helped a lot.
  • Rewrite it three ways (multi-query). Ask for several different phrasings, search with each, and merge the results with reciprocal rank fusion: every passage gets 1 ÷ (60 + its rank) from each list, added up. A passage that several searches rank highly comes out on top.
  • Draft an answer first (HyDE, short for hypothetical document embeddings, from a 2022 paper). Ask the model to write the help article it imagines would answer the question, and search with that. A draft answer looks more like the real passage than a question does, even when its details are made up.

What happened on 22 chats#

Now all 22 chats at once. Most are short follow-ups; two are a single message (chat 21 is a fault code, chat 22 is two questions in one). Every one has a passage in the help centre that answers it.

Predict first

Rewriting gives search the missing context. Which search engine do you think gains more from it, keyword search or vector search?

Try it
Every conversation (rows) searched every way (columns). Each cell is the rank of the passage that answers it (two numbers when the answer needs two passages). Found means it’s in the top 3, the passages a typical RAG prompt would include.

On keyword search, every fix beats the last message alone: the whole conversation finds 17, the rewrite 18, the draft answer 19. Pasting in the whole conversation costs no model call and gets most of that gain, since the missing nouns are in the earlier turns. On vector search the gains are smaller: three rewrites does best with 19, the draft answer finds 18, and the single rewrite and the whole conversation stay at 17. No way of rewriting won on both engines, so measure on your own search before you pick one.

Two chats show what each method is for. Chat 22 asks two things, returns and warranty, and only three rewrites put both passages in the top 3 on both engines: the model wrote one query about returns and one about breaking, and each search found its own half. Chat 21, “thermostat shows E503”, defeats every keyword search, because the help centre writes the code as E-503 and no rewrite knows that. Vector search finds it at rank 1 every time. That gap is what hybrid search (keyword plus vector) is for, not rewriting.

The extra model call isn’t free. The rewrites averaged about 14 tokens, the three rewrites about 37 and the draft answers about 48, and the model has to finish writing before search can start, so the customer waits for every one of those tokens.

When rewriting goes wrong#

The model can make the query worse. Pick these chats in the first figure to see each one:

  • It drops what the customer wanted. In chat 5 the customer wants to remove their brother when he moves out. The rewrite, “Heating access for brother when he moves out”, kept the brother and lost the removing; vector search ranks the right passage 10th.
  • It drags the old question back in. Chat 7 became “Thermostat works with combi boiler and does I have to fit it myself?”. The boiler half wins, and the installation passage drops to 12th.
  • It adds a word that pulls the wrong way. Chat 15, “will it still update itself?”, found the software updates passage at rank 1 as it was. The rewrite, “Thermostat will still update itself?”, sent vector search to other thermostat passages (factory reset, trade-ins, power cuts), and the answer fell to 10th.
  • It doesn’t do the job you asked for. Asked for three search queries in chat 3, the model repeated the assistant’s sentence about holiday mode three times. The away mode passage, which answers the question, lands 9th on keyword search.

The draft answers make things up, which is the point of HyDE but worth seeing. The Ireland draft says 3 to 5 business days (the help centre says 4 to 6), the gift card draft says cards never expire (they last two years), and the Hearth Plus draft says a year costs £42 (it’s £35). Each still found the right passage, at rank 1 or 2, because it sounds like the right passage. A draft answer is only a search key: never show it to the customer.

One idea that didn’t help here: searching with both the last message and the rewrite and merging the two lists. It found 13 on keyword search and 16 on vector, no better than the last message alone.

In code#

The Ireland conversation, searched with MiniLM before and after the rewrite. Any chat model can do the rewriting; this uses the reply Qwen3-4B gave:

from sentence_transformers import SentenceTransformer

passages = {
    "Delivery": "Delivery. Orders take 2 to 4 working days in the UK. Orders placed before 2pm on a working day "
                "ship the same day, and you'll get a tracking link by email.",
    "Delivery outside the UK": "Delivery outside the UK. We currently ship to the UK and Ireland only. Orders to "
                               "Ireland take 4 to 6 working days, and import charges are included in the price.",
    "Where's my order?": "Where's my order? Your tracking link is in the email we send when your order ships. If the "
                         "link shows no movement for three working days, contact us and we'll chase the courier.",
    "Returns": "Returns. You can send back any Hearth product within 30 days of delivery for a full refund, as long "
               "as it's undamaged and in its original box.",
}
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
P = model.encode(list(passages.values()), normalize_embeddings=True)

def search(query):
    scores = P @ model.encode(query, normalize_embeddings=True)
    ranked = sorted(zip(passages, scores), key=lambda x: -x[1])[:2]
    return [(name, round(float(s), 2)) for name, s in ranked]

chat = ["Do you ship to Ireland?", "Yes, we deliver to the UK and Ireland.", "how long does it take?"]
rewrite_prompt = (
    "Rewrite the customer's last message as a standalone search query. Replace words like 'it' and "
    "'that' with what they refer to. Reply with the query only.\n\nConversation:\n"
    + "\n".join(("Customer: " if i % 2 == 0 else "Assistant: ") + t for i, t in enumerate(chat))
)
# send rewrite_prompt to any chat model; Qwen3-4B, running locally, replied:
rewritten = "How long does it take to ship to Ireland?"

print("last message:", search(chat[-1]))
print("rewritten:   ", search(rewritten))
# last message: [('Delivery', 0.44), ("Where's my order?", 0.3)]
# rewritten:    [('Delivery outside the UK', 0.76), ('Delivery', 0.63)]

What to remember

  • Search sees only the query, so follow-ups like “how long does it take?” retrieve the wrong passages unless the context goes with them.
  • Rewriting helped keyword search most here (13 of 22 found with the last message, up to 19), while vector search gained less; three rewrites suit questions that ask two things at once.
  • Rewrites can drop what the customer wanted, drag in the old question, or invent details, and they add a model call before every search: test them on your hardest follow-ups.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.