Sub topic 4
Turning Follow-Up Questions into Standalone Queries
Prerequisites
This chapter assumes you can read Python, you have a working RAG pipeline (index, retrieve, generate), and you can call an LLM with a text prompt. You should also know how embedding or BM25 search returns a ranked list for a query string. The earlier chapters on why raw queries fail and on the role of query rewriting give the background. This chapter covers one failure mode in detail: the question that only makes sense inside a conversation.
The problem: the retriever has no memory
A chat user writes the way people talk. They rely on earlier turns and leave out anything already said. Consider this exchange:
- User: "How does the Acme Cloud Pro plan handle data retention?"
- Assistant: "Pro keeps logs for 90 days by default."
- User: "What about its pricing?"
The generator can read the whole conversation, so it knows what "its" means. The retriever cannot. A vector index or a BM25 index receives one string, "What about its pricing?", and nothing else. The embedding of that string is close to generic pricing text. Keyword search finds nothing useful, because "Acme", "Cloud" and "Pro" are not in the query.
The fix is to rewrite the follow-up into a standalone query before searching. Here that would be "What is the pricing of the Acme Cloud Pro plan?". A standalone query is understandable by someone who has seen none of the conversation.
Where the rewrite sits
The rewrite happens before retrieval. The original follow-up still goes to the generator, along with the history and the retrieved passages. Only the retriever sees the rewritten query.
Keeping the original question for the generator matters. The rewrite is a tool for search. It is not a replacement for what the user said, and it may be wrong.
A condensing function
This function takes the history as a list of (role, text) pairs, the new follow-up, and any callable that sends a prompt to a model and returns text.
from typing import Callable
def condense_question(
history: list[tuple[str, str]],
follow_up: str,
llm: Callable[[str], str],
) -> str:
if not history:
return follow_up
transcript = "\n".join(f"{role}: {text}" for role, text in history)
prompt = (
"Rewrite the final user question so it can be understood without "
"the conversation. Keep all names and constraints. "
"Return only the rewritten question.\n\n"
f"{transcript}\nuser: {follow_up}"
)
return llm(prompt).strip()Each piece of this function does a job:
- The empty-history shortcut. The first turn has nothing to resolve. Returning the question unchanged saves one model call and removes any chance of the rewrite damaging it.
- "Keep all names and constraints." Without this, models tend to summarize. A constraint such as "in the EU region" or "before 2023" can silently vanish, and retrieval then returns plausible but wrong passages.
- "Return only the rewritten question." Chatty output such as "Sure! Here is the rewritten question:" would be embedded along with the question and worsen the match. Instruct the model to return the bare query, and still strip whitespace as the code does.
- The follow-up placed last. The transcript ends with the exact message to rewrite, so the model does not have to guess which turn is the target.
Running it with a stub model
You can test the plumbing without an API key by passing a fake model. This block assumes condense_question from the previous block is already defined in the same file or session.
def fake_llm(prompt: str) -> str:
print("--- prompt sent to model ---")
print(prompt)
return " What is the pricing of the Acme Cloud Pro plan?\n"
history = [
("user", "How does the Acme Cloud Pro plan handle data retention?"),
("assistant", "Pro keeps logs for 90 days by default."),
]
print(condense_question(history, "What about its pricing?", fake_llm))
print(condense_question([], "What is Acme Cloud?", fake_llm))The first call prints the prompt and then the cleaned rewrite. The second call prints only the original question, because the history is empty and the model is never called. Testing the stub this way confirms the prompt looks right before you pay for real calls.
Limiting the history you send
Sending the full history has two costs. It adds latency and tokens to every turn, and a long, unrelated history gives the model more chances to pull in the wrong context. A common compromise is to keep only the last few messages:
def recent(history: list[tuple[str, str]], max_messages: int = 6) -> list[tuple[str, str]]:
return history[-max_messages:]
rewritten = condense_question(recent(history), "What about its pricing?", fake_llm)Six messages is three user and assistant exchanges. Most follow-ups refer to the previous one or two turns. If your users often refer back further ("go back to the first plan you mentioned"), raise the limit or summarize older turns instead of dropping them.
Long assistant answers can dominate the transcript. If they do, you can truncate each assistant message to its first few hundred characters before building the prompt. The entity names that matter are usually in the user's messages and the start of the answer.
Edge cases
| Situation | What goes wrong | What to do |
|---|---|---|
| Already standalone ("What is the refund policy?") | A careless rewrite adds context from the previous topic | Tell the model to return the question unchanged if it is already self-contained |
| Topic switch ("Unrelated, how do I reset my password?") | The rewrite mixes in the old topic | Same rule as above. Log rewrites so you can spot this |
| Pronoun with two candidates ("Which one is cheaper?" after comparing two plans) | The model picks one and hides the ambiguity | Ask the model to name both, or ask the user to clarify |
| Reference to the assistant's own wording ("Explain the second point") | The rewrite needs the assistant text, which was truncated | Keep assistant messages whole for the last turn |
| Non-question follow-up ("Thanks", "ok") | The model invents a question | Skip retrieval for such messages. See the chapter on routing |
| Multi-part follow-up ("And the pricing and the limits?") | One query covers two needs | Condense first, then decompose in a later step |
Common errors
Answering instead of rewriting. A model given a question may simply answer it. The output is then a statement, not a query. A prompt that says "Return only the rewritten question" reduces this. A check that the output ends in a question mark, or is shorter than a few hundred characters, catches many remaining cases. When the check fails, fall back to the original follow-up.
Losing constraints. The rewrite drops a date, product version, or region. Test this directly by building a few conversations where the constraint appears only in an earlier turn and checking that it survives.
Over-expansion. The model adds background it invented, such as a plan feature not mentioned in the conversation. The extra words steer retrieval away from the user's real intent. Limit the instruction to resolving references, not adding information.
Rewriting every turn by default. The extra model call adds latency before retrieval can even start. Use the empty-history shortcut, and consider a cheap check for obvious standalone questions, or a smaller, faster model for this step.
Trusting the rewrite blindly. If the rewrite is wrong, retrieval is wrong, and the generator may answer confidently from the wrong passages. Log the original and rewritten pair together with the retrieved document IDs, so you can find these failures later.
Combining with other techniques
Condensing is usually the first rewriting step, because later steps assume a self-contained question. Multi-query expansion, HyDE, and decomposition all work better when they start from "What is the pricing of the Acme Cloud Pro plan?" than from "What about its pricing?". In a pipeline, the order is typically condense, then expand or decompose, then retrieve and merge. Each stage adds a model call, so measure whether each one earns its cost. The evaluation chapter shows how.
Exercise
A user asks "How do I rotate API keys in Acme Cloud?" and gets an answer. They then write "Does that work for the EU region too?" Your pipeline sends only this second message to the retriever and gets irrelevant passages. (1) Write the standalone query you would want. (2) Name two details the condense prompt must preserve. (3) What should your code do if the model's reply is a long paragraph instead of a single question?
Show answer
(1) "Does rotating API keys in Acme Cloud work for the EU region?" (2) The product name (Acme Cloud) and the task (rotating API keys) come from the earlier turn. The constraint "EU region" comes from the follow-up and must not be dropped. (3) Treat the reply as a failed rewrite, because the model probably answered instead of rewriting. Fall back to the original follow-up, or retry once. Log the case so you can adjust the prompt.