Search Tutorials
--Ads--Conversational Query Condensing
Rewrite follow-up questions in a chat into standalone search queries.
In a chat, people ask follow-up questions that only make sense in context. After asking "How many leave days do new employees get?", a user types "and after the first year?" or "can I carry them over?". Embedding "can I carry them over?" on its own retrieves nothing useful, because "them" means nothing without the conversation. Query condensing rewrites each follow-up into a standalone question before retrieval.
Example
| Conversation so far | Follow-up | Standalone question |
|---|---|---|
| User: How many leave days do new employees get? Assistant: 18 days in the first year. | and after that? | How many paid leave days do employees get after their first year? |
| (same) | can I carry them over? | Can unused paid leave days be carried over to the next year? |
| User: What is the hotel limit in Pune? Assistant: 4,000 rupees per night. | what about Mumbai? | What is the hotel cost limit per night in Mumbai? |
Implementation
condense.py
from rag_helpers import ask
CONDENSE_PROMPT = """Below is a conversation and a follow-up message from the user.
Rewrite the follow-up as a standalone search question that can be understood without the
conversation. Resolve pronouns and references ("it", "them", "that policy", "what about...")
using the conversation. Keep all specific details. If the follow-up is already standalone,
return it unchanged. Output only the question.
<conversation>
{history}
</conversation>
Follow-up: {question}
Standalone question:"""
def format_history(messages: list[dict], max_turns: int = 6) -> str:
recent = messages[-max_turns:]
return "\n".join(f"{m['role'].capitalize()}: {m['content'][:500]}" for m in recent)
def condense(messages: list[dict], question: str) -> str:
if not messages: # first question: nothing to resolve
return question
return ask(CONDENSE_PROMPT.format(history=format_history(messages), question=question),
max_tokens=200).strip()
history = [
{"role": "user", "content": "How many leave days do new employees get?"},
{"role": "assistant", "content": "New employees get 18 days of paid leave in their first year."},
]
print(condense(history, "can I carry them over?"))
Can unused paid leave days be carried over to the next year?
Design details
- Only recent turns. Six messages (three exchanges) are usually enough to resolve references, and long assistant answers are truncated. This keeps the call fast and cheap.
- Skip the first turn. There is nothing to resolve.
- Use the condensed question for retrieval only. When generating the final answer, give the LLM the real conversation history and the user's actual words, plus the retrieved context. The condensed question is a search tool, not a replacement for the conversation.
- Topic switches. If the user changes topic ("ok, different question: how do I book travel?"), a good prompt returns the follow-up unchanged instead of forcing it into the old topic. Include such cases in your tests.
- Log both versions. Logging the original and condensed question makes retrieval failures in chats much easier to debug.
Putting it into a chat loop
from retriever import DenseRetriever # from the top-k search lesson
def chat_turn(messages: list[dict], user_message: str, retriever: DenseRetriever) -> str:
search_query = condense(messages, user_message)
hits = retriever.search(search_query, k=4)
context = "\n\n".join(f'<source id="{h.id}">\n{h.text}\n</source>' for h in hits)
prompt = (f"<conversation>\n{format_history(messages)}\n</conversation>\n\n"
f"<sources>\n{context}\n</sources>\n\n"
"Answer the user's latest message using the sources, citing source ids. "
"If the sources do not contain the answer, say so.\n\n"
f"User: {user_message}")
answer = ask(prompt)
messages += [{"role": "user", "content": user_message}, {"role": "assistant", "content": answer}]
return answer
The full conversational RAG system, with memory management, is built in Conversational RAG with Memory.
Key takeaways
- Follow-up questions contain references that make them unsearchable on their own.
- Condense each follow-up into a standalone question using the recent conversation.
- Use the condensed question for retrieval, but answer using the real conversation.
- Handle topic switches and log both the original and condensed questions.