This prompt is for retrieval engineers and RAG system builders who need to transform a user's follow-up question into a standalone, search-optimized query. The core job-to-be-done is resolving anaphora and implicit context from a multi-turn conversation into a concrete retrieval query without hallucinating constraints that were never stated. The ideal user is an AI engineer integrating this prompt into a retrieval pipeline where a vector database, search index, or hybrid retrieval system expects a clean, decontextualized query string. You need the full conversation history and the current user message as inputs. Do not use this prompt when the user's question is already a complete, self-contained query, or when you are generating the final answer rather than preparing for retrieval.
Prompt
Follow-Up Query Expansion Prompt with History

When to Use This Prompt
Define the job, reader, and constraints for the Follow-Up Query Expansion Prompt with History.
This prompt is a pre-retrieval step, not a generation step. It should be wired directly into your query rewriting stage, before any call to a vector store or search API. The output is a single expanded query string, not a conversation reply. The primary failure mode is over-expansion, where the model adds assumed constraints like date ranges, filters, or entity names that the user never mentioned. To guard against this, you must validate the output by checking that every term in the expanded query has a direct antecedent in the conversation history or the current question. A secondary failure mode is under-expansion, where the model fails to resolve a pronoun or reference, leaving the query too vague to retrieve relevant documents. Implement a simple validation check: if the output query contains unresolved pronouns or demonstratives like 'it,' 'that,' or 'this,' reject it and retry.
This prompt is not a substitute for a full conversational agent. It does not decide whether retrieval is necessary, nor does it handle clarification requests. Use it as a narrow, testable component in your retrieval pipeline. Before deploying, build a golden dataset of conversation turns and expected expanded queries, and run regression tests to measure query drift and over-expansion rates. If your use case involves high-stakes domains like healthcare or legal research, add a human review step for any query that introduces new constraints not explicitly present in the history.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Follow-Up Query Expansion Prompt with History is the right tool for your retrieval pipeline.
Good Fit: Multi-Turn RAG with Coreference
Use when: Users ask follow-ups like 'What about the pricing?' or 'How does that compare?' that rely on prior turns for meaning. Why: The prompt resolves pronouns and implicit references into a standalone search query without hallucinating constraints.
Bad Fit: Single-Shot or Stateless Retrieval
Avoid when: Every user query is independent and there is no conversation history to reference. Risk: The prompt may over-expand a self-contained question by injecting irrelevant prior context, polluting the retrieval with noise.
Required Inputs: History and Current Query
What you need: The current user message plus a structured representation of the prior conversation turns (user questions and system answers). Guardrail: Without history, the prompt degrades to a simple query rewrite. Validate that history is present and non-empty before calling.
Operational Risk: Query Drift
What to watch: The expanded query may introduce terms or constraints not present in the original follow-up, causing retrieval to return irrelevant documents. Guardrail: Implement a semantic similarity check between the expanded query and the original user message. Flag expansions below a threshold for human review or fallback to the raw query.
Operational Risk: Over-Expansion
What to watch: The model may add excessive detail from the history, creating a long, overly specific query that misses relevant results. Guardrail: Set a token or character limit on the expanded query. Use a post-generation validator to truncate or reject queries that exceed the limit.
When Not to Use: Ambiguous Follow-Ups
Avoid when: The follow-up itself is ambiguous even with history (e.g., 'What about the other one?'). Risk: The model may guess the wrong referent, leading to a confidently wrong expanded query. Guardrail: Pair this prompt with a clarification request prompt. If the expansion confidence is low, ask the user to disambiguate instead of expanding.
Copy-Ready Prompt Template
A reusable prompt template for expanding a follow-up user query into a standalone search query using conversation history.
The following prompt template is designed to be dropped into a retrieval pipeline immediately after a user sends a follow-up message. Its job is to rewrite the user's latest utterance into a self-contained search query that incorporates necessary context from prior conversation turns. The template uses square-bracket placeholders for all dynamic inputs, making it straightforward to populate from your application's session store and retrieval configuration.
textYou are a query rewriter for a retrieval system. Your task is to convert a user's follow-up question into a standalone search query that can be understood without the conversation history. ## Conversation History [HISTORY] ## Latest User Message [USER_MESSAGE] ## Instructions 1. Resolve all pronouns, anaphora, and implicit references in the latest message by substituting them with explicit entities or concepts from the conversation history. 2. If the latest message is a clarification, correction, or refinement of a prior question, incorporate that intent into the expanded query. 3. Do not introduce new constraints, entities, or assumptions that are not present in the history or the latest message. 4. If the latest message is a complete topic shift that does not depend on history, return it unchanged. 5. Output only the expanded query text. Do not include explanations, prefixes, or formatting. ## Expanded Query
To adapt this template, replace [HISTORY] with a serialized representation of prior turns—typically the last 3–5 user and assistant message pairs, formatted as User: ... Assistant: .... Replace [USER_MESSAGE] with the raw text of the current user input. For production use, add a [MAX_QUERY_LENGTH] constraint if your search backend has token limits, and consider injecting [DOMAIN_GLOSSARY] as a list of canonical entity names to normalize terminology. Always validate the output before passing it to retrieval: if the expanded query is identical to the raw user message when history is non-empty, the rewrite likely failed and should trigger a retry or fallback to the original message.
Prompt Variables
Required inputs for the Follow-Up Query Expansion Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Missing or malformed variables are a common source of over-expansion, query drift, and hallucinated constraints.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_QUERY] | The user's latest follow-up question that needs expansion into a retrieval-ready query. | What about the pricing model? | Must be a non-empty string. Reject null or whitespace-only input. Check for minimum length of 3 characters to avoid empty follow-ups. |
[CONVERSATION_HISTORY] | The prior turns of the conversation, including user questions and assistant answers, formatted as a list of turn objects. | [{"role": "user", "content": "What is the enterprise plan?"}, {"role": "assistant", "content": "The enterprise plan includes..."}] | Must be a valid JSON array of turn objects with 'role' and 'content' keys. Reject if history is missing or not parseable. Allow empty array for first-turn fallback. |
[LAST_ASSISTANT_ANSWER] | The assistant's most recent answer, extracted from conversation history for explicit reference in expansion. | The enterprise plan includes SSO, priority support, and custom SLAs starting at $500/month. | Must be a non-empty string if conversation history contains at least one assistant turn. Null allowed only for first-turn queries. Validate that the string is present when history length > 0. |
[RETRIEVAL_DOMAIN] | A short description of the knowledge domain to scope the expanded query and prevent off-topic expansion. | product pricing and enterprise features | Must be a non-empty string. Check for maximum length of 200 characters to avoid over-constraining. Reject if domain is too vague (e.g., 'stuff' or 'things'). |
[MAX_EXPANSION_TOKENS] | The maximum number of tokens allowed for the expanded query to prevent over-expansion and query drift. | 50 | Must be a positive integer between 10 and 200. Reject values outside this range. Validate as integer, not float. Default to 75 if not specified. |
[PRIOR_ENTITIES] | Key entities, terms, or constraints extracted from prior turns that must be preserved in the expanded query. | ["enterprise plan", "SSO", "pricing"] | Must be a valid JSON array of strings. Allow empty array if no entities detected. Validate each element is a non-empty string. Reject if array contains null or non-string values. |
[EXPANSION_MODE] | Controls whether expansion should be conservative (minimal additions) or aggressive (include related concepts). | conservative | Must be one of: 'conservative', 'balanced', 'aggressive'. Reject any other value. Default to 'balanced' if not specified. Conservative mode reduces hallucination risk; aggressive mode increases recall at cost of precision. |
Implementation Harness Notes
How to wire the follow-up query expansion prompt into a production retrieval pipeline with validation, retries, and drift monitoring.
This prompt is designed to sit between the user's latest message and your retrieval system. It takes the current query, a window of conversation history, and optionally the last retrieved context, then produces a self-contained search query. The harness should treat this as a pre-retrieval transformation step: the model's output is never shown to the user directly. Instead, it feeds into your vector database, keyword index, or hybrid search. This separation means you can iterate on the expansion prompt without changing your answer-generation logic, and you can log expanded queries independently for debugging.
Wire the prompt into your application with a validation layer before the query hits retrieval. At minimum, check that the output is non-empty, is not a verbatim copy of the user's raw input (which signals the model didn't expand), and does not exceed a reasonable token length for your search backend. For stricter control, implement a drift detector: compare the expanded query against the original using embedding similarity. If the cosine similarity drops below a threshold (e.g., 0.4), the expansion may have introduced unrelated concepts. In that case, fall back to the raw user query or flag the turn for review. Log the original query, the expanded query, the similarity score, and the conversation turn ID for trace analysis.
Model choice matters here. This is a latency-sensitive, low-creativity task. Use a fast, smaller model (e.g., GPT-4o-mini, Claude Haiku, or a fine-tuned open-weight model) rather than a large reasoning model. The prompt is structured for single-turn completion, so avoid models that overthink or produce chain-of-thought unless you explicitly parse out the final query. Set temperature=0 or very low to keep expansions deterministic. If you're using a model that supports structured outputs, constrain the response to a JSON object with a single expanded_query field to avoid parsing ambiguity. Implement a single retry on validation failure with a slightly higher temperature (0.1–0.2) to break out of degenerate outputs, but stop after one retry to avoid latency spikes.
For multi-turn RAG systems, integrate this prompt into your context assembly pipeline just before retrieval. The conversation history you pass should be a compressed summary of prior turns, not raw dialogue, to keep the prompt's token budget predictable. If your system already maintains a session summary for the answer-generation step, reuse that same summary here. Avoid passing the full retrieved context from prior turns into the expansion prompt unless you've confirmed it improves retrieval quality—it often introduces anchoring bias where the model expands toward previously retrieved documents rather than the user's actual intent. Test this with a small golden dataset of follow-up turns before enabling it in production.
Finally, build eval checks into your harness. For each expanded query, record whether the downstream retrieval returned relevant results (measured by answer quality or user feedback). Track the rate of no_results or low-relevance retrievals that follow an expansion. If expansion consistently produces worse retrieval than the raw query, your prompt is over-expanding or hallucinating constraints. Set up a periodic review of a sample of expanded queries—especially those with low similarity scores or high token counts—to catch drift before it degrades the user experience. This prompt is a pipeline component, not a set-and-forget artifact; treat its performance as a metric you monitor alongside retrieval precision and answer accuracy.
Expected Output Contract
Defines the structure, types, and validation rules for the expanded query output. Use this contract to parse the model response and gate it before passing to a retrieval system.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
expanded_query | string | Must be non-empty. Length must be between 10 and 500 characters. Must differ from [CURRENT_QUESTION] by at least one substantive token. | |
reasoning | string | If present, must not exceed 200 characters. Must not contain any hallucinated constraints not present in [CONVERSATION_HISTORY] or [CURRENT_QUESTION]. | |
referenced_turn_ids | array of strings | Each element must match a turn ID format from [CONVERSATION_HISTORY]. If empty or null, the query is treated as self-contained. | |
expansion_type | enum: ['clarification', 'decomposition', 'contextualization', 'none'] | Must be one of the four allowed values. 'none' is only valid if expanded_query equals [CURRENT_QUESTION]. | |
confidence_score | float between 0.0 and 1.0 | Must be a number. Values below 0.5 should trigger a fallback to the raw [CURRENT_QUESTION]. | |
hallucinated_entity_flag | boolean | Must be false. If true, the output must be rejected and a retry requested with stricter grounding instructions. | |
token_count | integer | If present, must be a positive integer. Used for budget tracking. A null value is acceptable. |
Common Failure Modes
What breaks first when expanding follow-up queries with conversation history and how to guard against it.
Query Drift from Stale Context
What to watch: The expanded query incorporates outdated or resolved constraints from earlier turns, pulling retrieval toward irrelevant documents. This happens when the prompt over-weights history and fails to recognize that prior conditions no longer apply. Guardrail: Add a history relevance check step before expansion. Explicitly instruct the model to identify and drop constraints that have been satisfied, contradicted, or superseded by the current turn.
Over-Expansion with Hallucinated Constraints
What to watch: The model invents search terms, filters, or entity names that never appeared in the conversation history, producing a query that looks specific but retrieves zero results or misleading documents. This is common when the model tries to 'fill gaps' in ambiguous follow-ups. Guardrail: Constrain expansion to only terms present in the conversation. Use a strict instruction: 'Do not introduce new entities, dates, or constraints not explicitly mentioned in the current question or prior turns.' Validate output against input tokens.
Pronoun and Anaphora Resolution Failure
What to watch: The follow-up question contains pronouns ('it', 'they', 'that approach') or implicit references that the expansion prompt resolves incorrectly, mapping to the wrong entity from history. This produces a query that searches for the wrong thing entirely. Guardrail: Include an explicit resolution step in the prompt: 'Identify all pronouns and implicit references in the current question. Map each to the specific entity or concept from prior turns before constructing the expanded query.' Test with ambiguous reference cases.
Topic Shift Misinterpretation
What to watch: The user changes subjects but uses language that superficially resembles the prior topic. The expansion prompt anchors on the old topic and produces a hybrid query that mixes unrelated domains, degrading retrieval precision. Guardrail: Add a topic continuity check before expansion. If the current question introduces a new subject, reset the history context and expand from the current turn only. Pair with a topic shift detection classifier upstream.
Runaway Query Length and Token Waste
What to watch: The expanded query accumulates terms from every prior turn without pruning, producing a bloated search query that exceeds embedding model context limits or dilutes retrieval signal with noise. Guardrail: Set a hard token or term limit on the expanded query. Instruct the model to prioritize the most salient constraints from history and drop low-signal terms. Log expansion ratio (output tokens / input tokens) and alert on spikes.
Temporal Constraint Staleness
What to watch: Prior turns reference time-sensitive constraints ('last quarter', 'recent release', 'current policy') that become stale across turns. The expansion prompt carries these forward without updating temporal references, retrieving outdated documents. Guardrail: Instruct the model to treat relative time references as session-relative and flag them for re-evaluation. If the conversation spans a time boundary, prefer absolute dates or re-resolve temporal expressions against the current turn's timestamp.
Evaluation Rubric
How to test output quality before shipping. Use this rubric to evaluate the expanded query against the original follow-up question and conversation history.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Core Intent Preservation | Expanded query retains the original follow-up question's core intent without introducing new constraints or topics | Query adds entities, filters, or topics not present in the original question or conversation history | Compare expanded query entities against original question entities; flag additions not grounded in history |
History Context Incorporation | Expanded query correctly resolves anaphora and implicit references using prior turns without copying irrelevant history | Query fails to resolve pronouns or references, or copies entire prior turns verbatim without extracting relevant context | Check that all pronouns and implicit references in the original question are resolved in the expanded query; verify no full-sentence copy from history |
No Hallucinated Constraints | Expanded query contains zero fabricated constraints, dates, filters, or named entities not present in the input or history | Query adds specific values like date ranges, product names, or metadata filters that were never mentioned | Diff expanded query against input and history; flag any new named entities or filter-like tokens |
Retrieval Relevance Improvement | Expanded query produces retrieval results with higher relevance scores than the raw follow-up question alone | Retrieval results from expanded query are worse or identical to raw question results | Run both raw and expanded queries through retrieval; compare top-k relevance scores using same embedding model |
Over-Expansion Control | Expanded query adds only necessary context terms; query length increase is proportional to ambiguity resolved | Query balloons to 3x+ the original length or adds broad generic terms that dilute retrieval precision | Measure token count ratio of expanded to original; flag if ratio exceeds 2.5 without clear ambiguity justification |
Ambiguity Resolution Completeness | All ambiguous references in the follow-up question are resolved in the expanded query | Expanded query leaves unresolved pronouns, demonstratives, or incomplete references | Scan expanded query for remaining pronouns or demonstratives; flag any that persist from the original |
Temporal Consistency | Expanded query respects temporal references from conversation history without shifting timeframes | Query changes time references or applies past context to a present-tense follow-up incorrectly | Check temporal expressions in expanded query against conversation timeline; flag mismatches |
Output Format Compliance | Expanded query is a single search-ready string with no commentary, explanation, or meta-text | Output includes prefixes like 'Expanded query:' or contains multiple query variants or explanatory text | Validate output is a single string with no colons, bullet points, or line breaks indicating multiple queries |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a simple conversation history array. Use a lightweight model call without strict output validation. Focus on whether the expanded query captures the follow-up intent.
codeSYSTEM: You rewrite follow-up questions into standalone search queries. CONVERSATION HISTORY: [USER_PREVIOUS_QUESTION] [ASSISTANT_PREVIOUS_ANSWER] CURRENT FOLLOW-UP: [FOLLOW_UP_QUESTION] EXPANDED QUERY:
Watch for
- Over-expansion that adds constraints the user never stated
- Dropping key entities from prior turns
- Producing a query that's too similar to the original question

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us