This prompt is designed for conversational AI engineers building stateful RAG systems where the user's current question cannot be understood in isolation. Its primary job is to resolve anaphora, ellipsis, and implicit references from the conversation history to produce a standalone, self-contained query. The ideal user is a developer integrating this prompt into a multi-turn retrieval pipeline, where a user might ask 'What about the pricing?' immediately after a discussion about a specific product. Without history-conditioned reformulation, the retrieval system would search for the generic term 'pricing' and fail to return the relevant document. This prompt is a pre-retrieval step that sits between the chat interface and the vector or keyword index.
Prompt
History-Conditioned Query Reformulation Prompt for Conversational RAG

When to Use This Prompt
Defines the job, ideal user, required context, and constraints for the history-conditioned query reformulation prompt.
You should use this prompt when your application supports back-and-forth dialogue and your knowledge base is large enough that contextless queries produce noisy or irrelevant results. It requires two inputs: the current user utterance and a structured representation of the conversation history, typically the last N turns. The output is a single, decontextualized query string. This prompt is not a substitute for session state management or long-term memory; it only resolves local conversational dependencies. Do not use it for single-shot Q&A, for injecting user profile data (use a profile-aware rewrite prompt instead), or when the conversation history contains sensitive information that should not be passed to the model. In high-compliance environments, ensure the history passed to the model is scrubbed of PII and access-controlled data before reformulation.
A critical constraint is topic boundary detection. The prompt must be instructed to ignore history that is no longer relevant. If a user discusses 'renewal terms' for ten turns and then asks 'How do I reset my password?', the reformulated query should be exactly 'How do I reset my password?' without dragging in the prior topic. The prompt template below includes explicit instructions for this. Before deploying, build a regression test suite with examples of pronoun resolution ('it', 'they'), comparative references ('the cheaper one'), and topic shifts. Evaluate the reformulated query against a golden set of expected standalone queries. If the reformulated query still contains pronouns or unresolved references, the downstream retrieval will fail silently, which is the most common production failure mode.
Use Case Fit
Where this prompt works and where it does not. History-conditioned reformulation is powerful but introduces stateful failure modes that must be bounded.
Good Fit: Multi-Turn Conversational RAG
Use when: users ask follow-up questions with pronouns ('it', 'they'), ellipsis ('what about pricing?'), or implicit references that require prior turns to resolve. Guardrail: always pass the last N turns as explicit history; never rely on the model's internal memory of the conversation.
Bad Fit: Single-Shot Search or Stateless APIs
Avoid when: each query is independent and there is no conversation history to condition on. The reformulation step adds latency and cost with no benefit. Guardrail: bypass the reformulation prompt entirely when conversation_history is empty or the session is marked stateless.
Required Inputs
Must have: the current user query, a structured conversation history (list of user/assistant turns), and the user's access scope or permission profile. Guardrail: validate that history is not null, that timestamps are monotonic, and that the access scope object is present before calling the prompt. Fail fast with a clear error if inputs are missing.
Operational Risk: Stale Context Poisoning
Risk: old or irrelevant conversation turns cause the reformulated query to carry forward incorrect entities or resolved references. Guardrail: implement a topic boundary detector that truncates history when a clear topic shift is detected. Limit history window to the last 5-10 turns or a configurable time window.
Operational Risk: Permission Leakage Through Reference
Risk: the reformulated query resolves an anaphor to an entity the user mentioned but is not authorized to retrieve. Guardrail: post-process the reformulated query against the user's access control list. Strip or redact any resolved entity that falls outside the permitted scope before sending to retrieval.
Operational Risk: Over-Resolution of Ambiguous References
Risk: the model confidently resolves an ambiguous pronoun to the wrong entity from history, producing a precise but incorrect retrieval query. Guardrail: when confidence is low or multiple candidate referents exist, generate multiple candidate reformulations and use retrieval scoring or user clarification to disambiguate.
Copy-Ready Prompt Template
A reusable prompt that reformulates a user query into a standalone, permission-aware retrieval query by resolving conversational references against history.
This prompt template is the core instruction set for a history-conditioned query reformulation step in a conversational RAG pipeline. It takes the user's latest message, a structured conversation history, and a user access scope, then produces a self-contained query that can be sent directly to a retrieval system. The prompt is designed to resolve anaphora (e.g., 'it', 'that feature'), ellipsis (e.g., 'what about the other one?'), and implicit topic carry-over without losing the user's original intent or introducing information not present in the history.
The template below uses square-bracket placeholders for all dynamic inputs. Replace [CONVERSATION_HISTORY] with a list of prior turns, each containing role and content. Replace [CURRENT_QUERY] with the user's latest message. Replace [USER_ACCESS_SCOPE] with a structured description of what the user is permitted to retrieve (e.g., document labels, project IDs, clearance levels). The [OUTPUT_SCHEMA] placeholder should be replaced with your expected JSON structure, such as {"standalone_query": "string", "resolved_references": ["string"], "access_constraints_applied": ["string"]}. The [FEW_SHOT_EXAMPLES] block is optional but strongly recommended for production; include 2-4 examples that demonstrate pronoun resolution, topic shifts, and access scope application.
textYou are a query reformulation engine for a secure conversational retrieval system. Your job is to convert the user's latest query into a standalone, self-contained retrieval query that can be executed independently against a search index. ## Inputs - Conversation History: [CONVERSATION_HISTORY] - Current User Query: [CURRENT_QUERY] - User Access Scope: [USER_ACCESS_SCOPE] ## Rules 1. Resolve all pronouns, demonstratives (this, that, these, those), and implicit references by substituting the specific entities or topics from the conversation history. 2. If the current query is a follow-up that omits the main subject, carry forward the subject from the most recent relevant turn. 3. Do NOT introduce new entities, constraints, or assumptions not present in the history or current query. 4. Apply the User Access Scope as a filter: if the resolved query would retrieve documents outside the user's permitted scope, add explicit scope-limiting terms or metadata constraints to the query. 5. If the user's query introduces a new topic unrelated to the history, treat it as a fresh query and do not force a connection to prior turns. 6. Preserve the user's original phrasing where possible; only modify what is necessary for standalone clarity and access compliance. ## Output Format Return a JSON object matching this schema exactly: [OUTPUT_SCHEMA] ## Examples [FEW_SHOT_EXAMPLES] Now reformulate the current query.
After copying this template, adapt the [USER_ACCESS_SCOPE] input to match your authorization model. If your system uses document-level ACLs, pass a list of allowed document IDs or label filters. If you use role-based scoping, describe the role's permitted knowledge domains. The [OUTPUT_SCHEMA] should include at minimum the standalone_query field; adding resolved_references and access_constraints_applied fields makes the reformulation auditable. Before deploying, run this prompt against a regression test set that includes pronoun chains, topic shifts, and queries that should be blocked by access scope. If the reformulated query still contains unresolved pronouns or leaks access-scoped terms, add more few-shot examples targeting those failure patterns rather than lengthening the rules.
Prompt Variables
Required inputs for the History-Conditioned Query Reformulation Prompt. Each placeholder must be populated before the prompt is sent to the model. Missing or malformed variables are the most common cause of reformulation failures in production.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_QUERY] | The user's latest message that may contain anaphora, ellipsis, or implicit references to prior turns. | What about the compliance risks for that? | Must be a non-empty string. Reject null or whitespace-only input before prompt assembly. If empty, return an error to the caller; do not send to the model. |
[CONVERSATION_HISTORY] | Ordered list of prior user and assistant turns, truncated to a configurable window. Used to resolve references in [CURRENT_QUERY]. | [{"role": "user", "content": "Show me Q3 revenue for EMEA."}, {"role": "assistant", "content": "EMEA Q3 revenue was $42M."}] | Must be a valid JSON array of objects with 'role' and 'content' keys. Role must be 'user' or 'assistant'. Validate array structure before prompt injection. An empty array is allowed for first-turn queries. |
[USER_ACCESS_SCOPE] | Structured object defining the user's permission boundaries: allowed document collections, data regions, and classification levels. | {"collections": ["finance_reports", "emea_data"], "regions": ["EMEA"], "max_classification": "internal"} | Must be a valid JSON object. Validate against the organization's permission schema. If null or missing, the prompt must default to the most restrictive scope. Never allow an empty scope object to imply full access. |
[USER_ROLE] | The user's organizational role used to inject role-specific terminology and context into the reformulated query. | "financial_analyst" | Must be a non-empty string matching a known role in the identity provider. Validate against an allowed-roles list. If unknown, set to 'default' and log a warning. Do not accept free-form user input for this variable. |
[USER_PREFERENCES] | Optional object containing explicit user preferences for terminology, expansion weight, and retrieval bias. Used to personalize the rewrite. | {"preferred_terms": ["revenue"], "expansion_weight": 0.7, "retrieval_bias": "recent_first"} | Must be a valid JSON object or null. If provided, validate keys against a known preference schema. Reject unexpected keys. Staleness check: if last_updated is older than 90 days, log a warning and consider reducing expansion_weight. |
[MAX_HISTORY_TURNS] | Integer controlling how many prior turns from [CONVERSATION_HISTORY] are included in the prompt context window. | 5 | Must be a positive integer between 1 and 20. Validate range before use. Values above 20 risk context overflow and degraded reference resolution. Default to 5 if not specified. |
[TOPIC_BOUNDARY_DETECTION] | Boolean flag enabling a pre-check that truncates [CONVERSATION_HISTORY] at the most recent topic shift to prevent stale context from polluting the reformulation. | Must be a boolean. If true, apply topic boundary detection logic to [CONVERSATION_HISTORY] before prompt assembly. If false, use the raw truncated history. Default to true for conversational RAG systems. |
Implementation Harness Notes
How to wire the history-conditioned query reformulation prompt into a production conversational RAG application.
This prompt is designed to be called synchronously as a pre-retrieval step in a conversational RAG pipeline. Before any search query hits your vector or keyword index, the raw user utterance and the conversation history must pass through this reformulation prompt. The output is a single, standalone, permission-aware query string that resolves anaphora, ellipsis, and implicit references. The application should treat this prompt as a deterministic transformation layer: it takes state (history, user profile) and an input (user message) and produces a cleaned output (reformulated query). Do not expose the raw reformulation to the end user unless you are building a debug or transparency panel.
To integrate this into your application, construct a request to your LLM provider with the prompt template as the system or user message. The [CONVERSATION_HISTORY] placeholder should be populated with a serialized list of prior turns, typically the last N messages formatted as User: ... Assistant: .... The [USER_QUERY] placeholder receives the current raw user input. The [USER_ACCESS_SCOPE] placeholder must be injected from your application's authentication layer, containing a structured summary of the user's roles, departments, and permission boundaries. After receiving the model's response, validate the output before retrieval: check that the reformulated query is a non-empty string, that it does not contain unresolved pronouns (e.g., 'it', 'they') unless they refer to entities explicitly named in the query itself, and that it does not introduce terms or access scopes beyond what is present in the user's profile. If validation fails, log the raw and reformulated queries, the history context, and the validation error, then either retry with a stricter temperature setting or fall back to using the raw user query with a warning flag.
For production resilience, implement a retry wrapper around this prompt call. Use a low temperature (0.0–0.2) to maximize deterministic reformulation. If the model returns a malformed response or the validator rejects the output, retry once with an explicit error instruction appended to the prompt, such as 'The previous output was invalid. Ensure the query is a single standalone sentence with no unresolved references.' Log every reformulation event—including the original query, the reformulated query, the conversation history window used, and the validator result—to a structured logging system. This log becomes essential for debugging retrieval failures and for building a regression test suite. For high-stakes domains where a bad reformulation could surface unauthorized documents, add a human review step for queries that trigger permission-boundary warnings or that the validator flags as ambiguous. Finally, treat this prompt as a versioned artifact in your codebase, with explicit release gates and a golden test set of conversation snippets that must pass before any prompt update is deployed.
Common Failure Modes
What breaks first when using history-conditioned query reformulation in production RAG and how to guard against it.
Stale Context Poisoning
Risk: The model resolves a pronoun or implicit reference using an outdated or irrelevant prior turn, producing a query that retrieves wrong documents. Guardrail: Implement a topic-shift detector that truncates or summarizes history when the user changes subjects. Always include a [CURRENT_TOPIC] variable in the prompt and instruct the model to ignore history that contradicts it.
Permission Leakage via Reference
Risk: The reformulated query expands an anaphoric reference into a term or entity that the user is not authorized to see, causing the retriever to surface restricted documents. Guardrail: Append the user's [ACCESS_SCOPE] as a mandatory filter constraint in the prompt. Validate the output query against a deny-list of high-sensitivity terms before retrieval execution.
Runaway Query Expansion
Risk: The model over-resolves context, adding excessive detail from the history that narrows the query too much and causes zero-result retrieval. Guardrail: Set a maximum token limit for the reformulated query. Implement a fallback path that strips added context and retries with the raw user query if the first retrieval returns empty.
Hallucinated History Injection
Risk: The model fabricates details not present in the conversation history to fill gaps in an ambiguous query, leading to confident but incorrect retrieval. Guardrail: Instruct the model to only use explicit entities from [CONVERSATION_HISTORY] and to output [UNRESOLVED] for any reference it cannot confidently map. Log and alert on high rates of unresolved outputs.
Multi-User Session Contamination
Risk: In a shared or agent-handoff session, the history contains turns from different roles or permission levels, causing the reformulated query to inherit an incorrect access context. Guardrail: Tag each history turn with a [ROLE] or [USER_ID] marker. Filter the history to only include turns from the current user before passing it to the reformulation prompt.
Evaluation Rubric
Use this rubric to test the quality of reformulated queries before shipping. Each criterion targets a specific failure mode in history-conditioned query rewriting. Run these tests against a golden dataset of conversation turns with known correct reformulations.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Anaphora Resolution | Pronouns and references (it, he, they, that) in [CURRENT_QUERY] are replaced with the correct entity from [CONVERSATION_HISTORY] | Output retains unresolved pronouns or maps them to the wrong entity from history | Automated check: Compare resolved entities in output against a labeled ground-truth set for 50+ conversation pairs |
Ellipsis Completion | Truncated or implicit phrases (e.g., 'What about pricing?') are expanded to a complete, standalone question using prior context | Output is a fragment, repeats the incomplete query verbatim, or adds hallucinated context not present in history | Human eval: Verify that the output can be understood without reading the history. Automated BLEU/ROUGE against canonical completions |
Permission Boundary Adherence | The reformulated query does not introduce terms, entities, or access scopes that exceed the provided [USER_ACCESS_SCOPE] | Output includes project codes, department names, or document labels not listed in the user's allowed scope | Automated check: Token-level comparison of output against a deny-list derived from [USER_ACCESS_SCOPE]. Flag any out-of-scope token |
Topic Boundary Detection | When [CURRENT_QUERY] starts a new topic, the output ignores irrelevant prior turns and does not carry over stale context | Output forces a connection to the previous topic, injecting terms from an unrelated prior turn into the new query | Automated check: Measure semantic similarity between output and the last turn of [CONVERSATION_HISTORY]. Flag if similarity > 0.8 when a topic shift is labeled |
Standalone Query Generation | The output is a single, self-contained query string that requires no external context to understand or execute | Output contains phrases like 'as mentioned', 'the previous one', or 'the same as above' without explicit resolution | Human eval: Ask a blinded reviewer to read the output and state the user's intent. Compare against the labeled intent for the turn |
Implicit Reference Resolution | Vague references like 'the last one', 'that document', or 'his report' are resolved to specific titles or IDs from [CONVERSATION_HISTORY] | Output keeps the vague reference or hallucinates a title not present in the provided history | Automated check: Regex for vague phrases. If found, cross-reference with history entities. Flag if no exact match exists in history |
Schema Consistency | The output strictly matches the [OUTPUT_SCHEMA] format (e.g., a single string, no extra commentary or JSON wrapper) | Output includes preamble text like 'The reformulated query is:', markdown formatting, or extra fields | Automated schema validation: Parse the output and check type == string and length > 0. Retry once on failure before flagging |
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 small conversation history buffer (last 3 turns). Use simple string concatenation for history injection. Skip formal schema validation on the output—just check that the reformulated query reads as a standalone sentence.
code[CONVERSATION_HISTORY] User: [USER_QUERY] Reformulated standalone query:
Watch for
- Anaphora resolution failures on pronouns ("it," "they," "that one")
- Ellipsis gaps where the model copies the user query verbatim without expansion
- No access scope injection yet—retrieval may return documents the user shouldn't see

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