This prompt is for conversational RAG engineers who need to resolve a user's follow-up question into a standalone, retrieval-ready query. The core job is to take the current user utterance, the full conversation history, and any previously resolved entities or clarifications, and produce a single, unambiguous query that can be sent to a vector, keyword, or hybrid search backend. It is designed for multi-turn interactions where anaphora ('it', 'they'), ellipsis ('what about the second one?'), and implicit context from earlier turns would otherwise break retrieval. The ideal user is a developer or AI engineer building a stateful RAG application, such as a customer support copilot, an enterprise document assistant, or a research tool that maintains a conversation thread.
Prompt
Session-Aware Query Rewrite Prompt with User History

When to Use This Prompt
Define the job, reader, and constraints for the session-aware query rewrite prompt.
Use this prompt when your system maintains a session state and users ask follow-up questions that depend on prior turns. It is appropriate when you have access to a structured conversation log, including user messages, assistant responses, and any entities or filters that were explicitly resolved in previous steps. The prompt is not suitable for single-shot Q&A systems with no session memory, or for applications where each query must be treated as fully independent. It is also not a replacement for a full dialog manager or a long-term user profile store; it operates strictly within the scope of the current session. If your retrieval system requires metadata filters based on user permissions or roles, pair this prompt with a separate permission-aware filter generation step, not inside this rewrite.
Before implementing, ensure you have a reliable way to detect topic shifts and stale context. The prompt includes instructions for the model to signal when the conversation has moved to a new topic and prior context should be discarded. You should also prepare a set of regression tests that cover pronoun resolution, entity carry-over, clarification incorporation, and explicit topic resets. If the rewritten query will be used to retrieve sensitive or compliance-bound documents, add a human review step or an automated guardrail that validates the rewritten query against the user's access scope before execution. Start by running this prompt against a golden dataset of multi-turn conversations and measure whether the rewritten queries retrieve the correct documents compared to a baseline of single-turn, context-free queries.
Use Case Fit
Where this prompt works and where it does not. Session-aware query rewriting is powerful but brittle. Use it when conversation history is essential for resolving the current query. Avoid it when the session is noisy, the topic has shifted, or the cost of getting context wrong is high.
Good Fit: Multi-Turn Clarifications
Use when: the user asks a follow-up that relies on a previous turn's entity or constraint (e.g., 'What about the pricing for the enterprise tier?' after discussing features). Guardrail: always include the last N turns and resolved entities in the prompt context.
Bad Fit: Abrupt Topic Shifts
Avoid when: the user changes the subject completely without signaling. The prompt may incorrectly merge old context with the new query. Guardrail: implement a topic shift detector before the rewrite step and clear session context when a shift is detected.
Required Input: Structured Session State
Risk: passing raw, unstructured chat logs leads to the model resolving the wrong 'it' or 'that.' Guardrail: input must be a structured list of prior turns, each with speaker, timestamp, and any resolved entities. Do not pass the full chat transcript as a single blob.
Operational Risk: Stale Context Poisoning
Risk: a correction or fact from 10 turns ago is still in the session window and overrides the user's new, contradictory statement. Guardrail: implement a staleness threshold. Summarize or drop turns older than a set number of interactions or minutes.
Bad Fit: Single-Shot or Stateless Systems
Avoid when: the retrieval system has no session concept or the user's question is fully self-contained. Adding a session-aware rewrite in these cases introduces latency and potential context hallucination with no benefit. Guardrail: route single-turn queries to a simpler, non-session prompt.
Required Input: Resolved Entity Map
Risk: the model re-resolves an entity from the raw text of a prior turn instead of using the application's canonical resolution, leading to inconsistency. Guardrail: provide a map of {mention: canonical_entity_id} from the application's entity resolver as part of the prompt input.
Copy-Ready Prompt Template
A reusable prompt template for rewriting a user's current query by resolving references from conversation history and user context.
This template is the core instruction set for a session-aware query rewriter. It forces the model to treat the current user message as part of an ongoing dialogue, resolving ambiguous pronouns, implicit topics, and follow-up clarifications against the provided conversation history. The goal is to produce a single, standalone, and context-rich query that can be sent to a retrieval system without losing the thread of the conversation. The prompt is designed to be stateless from the model's perspective—all necessary state must be passed in via the placeholders.
codeSYSTEM: You are a query rewriter for a conversational search system. Your task is to transform the user's latest message into a standalone, self-contained query suitable for a retrieval engine. You must resolve all anaphora, ellipsis, and implicit references using the provided conversation history and user context. Do not answer the user's question. Output only the rewritten query. USER CONTEXT: Role: [USER_ROLE] Access Scope: [USER_ACCESS_SCOPE] CONVERSATION HISTORY: [CONVERSATION_HISTORY] CURRENT USER MESSAGE: [USER_MESSAGE] CONSTRAINTS: - Resolve all pronouns (e.g., 'it', 'they', 'he') to their specific entities from the history. - Expand incomplete phrases (e.g., 'What about the second one?') with the full subject. - If the user corrects or clarifies a previous turn, incorporate the correction and drop the invalidated context. - If the topic has clearly shifted, ignore irrelevant history and focus only on the new topic. - Maintain the user's original language and terminology where possible, but expand acronyms on first use in the rewritten query. - Do not add information not present in the history or current message. - Respect the user's access scope; do not introduce terms or entities that would require broader permissions. OUTPUT: Provide only the rewritten query string, with no preamble or explanation.
To adapt this template, replace the square-bracket placeholders with data from your application's session store. [CONVERSATION_HISTORY] should be a structured log of prior turns, ideally formatted as User: ... Assistant: ... pairs. [USER_ROLE] and [USER_ACCESS_SCOPE] are critical for enterprise deployments where the rewriter must not hallucinate terms from documents the user cannot access. If your system does not use access controls, you can remove those lines and the final constraint. For high-stakes applications, add a [STALE_TOPIC_INDICATOR] flag to force a context reset when the session has been idle beyond a threshold. The next step is to wire this prompt into an application harness that validates the output is a non-empty string and is distinct from the raw user input before sending it to your retrieval pipeline.
Prompt Variables
Required inputs for the session-aware query rewrite prompt. Each variable must be populated before the prompt is assembled and sent to the model. Missing or malformed variables are the most common cause of rewrite failures in production.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_QUERY] | The latest user utterance that needs to be rewritten into a standalone, retrieval-ready query. | "What about the pricing for that?" | Required. Must be a non-empty string. Reject if only whitespace or under 3 characters. Log and escalate if identical to the previous turn's [CURRENT_QUERY] (possible client-side loop). |
[SESSION_HISTORY] | Ordered list of prior turns in the current conversation session, including user queries, assistant responses, and any resolved entities or clarifications. | [{"turn":1,"user":"Show me enterprise plans","assistant":"Here are the enterprise plans: Plan A, Plan B...","resolved_entities":["Plan A","Plan B"]}] | Required. Must be a valid JSON array. If the session has no prior turns, pass an empty array []. Each turn object must include a 'user' field. Validate array length does not exceed the model's context window limit for the session-history section. |
[USER_PROFILE] | Structured object containing the user's role, department, access level, and any explicit preferences that should constrain the rewrite. | {"role":"procurement_manager","department":"Supply Chain","access_level":"confidential","preferences":{"preferred_vendors":["Acme Corp"]}} | Required. Must be a valid JSON object. If no profile is available, pass an empty object {}. Validate that 'access_level' is one of the allowed enum values in your system. Reject if the object contains un-sanitized PII outside of approved fields. |
[RESOLVED_ENTITIES] | A list of entities, acronyms, or terms that were explicitly resolved or disambiguated in prior turns to prevent re-resolution. | ["Plan A (Enterprise - Annual)", "Q3 Forecast", "Acme Corp (Vendor ID: 4523)"] | Optional. Must be a valid JSON array of strings. If no entities have been resolved, pass an empty array []. Each string should include the canonical form and, where applicable, the disambiguating identifier in parentheses. Validate that no entity appears more than once. |
[TOPIC_SHIFT_THRESHOLD] | A numeric confidence score between 0.0 and 1.0. If the model detects a topic shift with confidence above this threshold, it should discard stale session context. | 0.85 | Required. Must be a float. Validate that the value is between 0.0 and 1.0. A value of 0.0 disables topic shift detection. A value of 1.0 means only the highest-confidence shifts are acted upon. Log a warning if set below 0.5 or above 0.95, as this may cause context thrashing or failure to detect real shifts. |
[OUTPUT_SCHEMA] | The strict JSON schema the model must use for its output, defining the shape of the rewritten query and any metadata. | {"type":"object","properties":{"rewritten_query":{"type":"string"},"context_used":{"type":"array","items":{"type":"string"}},"topic_shift_detected":{"type":"boolean"}},"required":["rewritten_query","context_used","topic_shift_detected"]} | Required. Must be a valid JSON Schema object. The 'rewritten_query' field must be required. Validate the schema itself before sending it to the model. A malformed schema is a common cause of unparseable model output. Store this schema in a version-controlled configuration, not hard-coded in the application. |
[MAX_REWRITE_LENGTH] | The maximum number of tokens allowed for the rewritten query to prevent overly verbose rewrites that degrade retrieval performance. | 128 | Required. Must be an integer. Validate that the value is greater than 10 and less than the model's maximum output tokens. A value that is too high can produce rewrites that are as long as the original context, defeating the purpose. Log a warning if set above 256 for most retrieval backends. |
Implementation Harness Notes
How to wire the session-aware query rewrite prompt into a production RAG application with validation, retries, and state management.
The session-aware query rewrite prompt is not a standalone component—it is a preprocessing step that sits between the user's conversational input and your retrieval engine. In a production RAG application, this prompt should be called before every retrieval call in a multi-turn session. The harness must manage session state, feed the prompt with the correct conversation history window, validate the rewritten query, and handle failures gracefully without breaking the user experience. A typical implementation wraps this prompt in a query rewriter service that accepts the current user message, session ID, and user profile, then returns a standalone, permission-aware query string ready for your vector or keyword index.
State Management and Context Assembly: The prompt requires [CONVERSATION_HISTORY], [CURRENT_QUERY], and [USER_PROFILE]. Your harness must assemble these from your session store. For [CONVERSATION_HISTORY], maintain a sliding window of the last N turns (typically 5–10) in a structured format: [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]. Include resolved entities and clarifications from prior turns as metadata. For [USER_PROFILE], inject only the fields relevant to retrieval scoping—role, department, access level, and recent document interactions—not the full user record. Stale context detection is critical: if the session has been idle beyond a configurable TTL (e.g., 30 minutes), flush the history or prompt the user to confirm topic continuity before rewriting. Implement a topic shift detector as a lightweight pre-check: compare the embedding of the current query against the centroid of recent turns; if cosine similarity drops below a threshold (e.g., 0.3), treat the query as a new topic and clear the history window.
Validation and Guardrails: The rewritten query must pass validation before hitting retrieval. Implement a schema validator that checks: (1) the output is a non-empty string, (2) it does not contain unresolved anaphora (e.g., 'it', 'that', 'they') without explicit referents, (3) it does not inject terms that would expand access beyond the user's permission boundary. For permission enforcement, maintain a deny-list of document scopes or metadata filters derived from the user's entitlements. After the rewrite, run a permission boundary check: tokenize the rewritten query and flag any term that maps to a restricted scope not in the user's allow-list. If a violation is detected, either strip the term and re-rewrite or escalate for human review depending on the sensitivity of the data domain. Log every rewrite with the original query, rewritten query, session ID, and any validation failures for auditability.
Retry and Fallback Logic: Model calls can fail, return malformed JSON, or produce rewritten queries that fail validation. Implement a retry loop with exponential backoff (3 attempts maximum). On each retry, include the validation error message in the prompt context so the model can self-correct. If all retries are exhausted, fall back to a degraded rewrite: use the current query as-is after basic normalization (lowercasing, stop-word removal) and append the user's role-based metadata filters directly. This ensures retrieval continues, albeit with reduced context awareness. For high-stakes domains like healthcare or legal, if the rewrite fails validation and retries are exhausted, route the query to a human review queue instead of proceeding with a degraded rewrite. Model choice matters: use a faster, cheaper model (e.g., GPT-4o-mini or Claude Haiku) for the rewrite step, reserving larger models for the final answer generation where quality impact is higher.
Observability and Regression Testing: Every rewrite must be logged with a trace ID that links the original query, rewritten query, session context, validation results, and retrieval performance downstream. This trace data is essential for debugging bad retrievals—when an answer is poor, you need to know whether the rewrite introduced the error. Before deploying any change to the prompt template, run it against a golden dataset of session transcripts with known-good rewrites. Your regression suite should include: (1) follow-up questions with anaphora ('What about the pricing?'), (2) topic shifts mid-session ('Actually, let's talk about security instead'), (3) stale context scenarios where the user returns after a long pause, and (4) adversarial inputs attempting to escape permission boundaries. Automate these tests in your CI pipeline and gate prompt changes on passing the full suite. If your RAG system serves multiple tenants, ensure your test suite includes tenant-isolated sessions to catch cross-tenant context leakage.
Expected Output Contract
The model must return a JSON object containing the rewritten query, a list of resolved entities, a list of dropped stale topics, and a confidence score. Validate each field before passing the rewrite to retrieval.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
rewritten_query | string | Must be a non-empty string. Must not contain unresolved pronouns or anaphora from [SESSION_HISTORY]. Check that the query is standalone and incorporates resolved entities from [RESOLVED_ENTITIES]. | |
resolved_entities | array of objects | Each object must have 'mention' (string), 'canonical_entity' (string), and 'source_turn' (integer). 'source_turn' must reference a valid turn index in [SESSION_HISTORY]. Array must not be empty if the query contains anaphora. | |
dropped_topics | array of strings | List of topic labels from prior turns that are explicitly excluded from the current rewrite due to topic shift. Each string must match a topic label in [SESSION_HISTORY]. Array can be empty if no topic shift is detected. | |
confidence | number | Float between 0.0 and 1.0. Represents the model's confidence that the rewrite correctly resolves all references and respects topic boundaries. If below 0.7, trigger a clarification prompt to the user. | |
clarification_needed | boolean | Set to true if the model cannot resolve a reference or detects an ambiguous topic boundary. If true, the 'rewritten_query' field should contain a clarifying question for the user, not a retrieval query. | |
active_topic | string | The single topic label from [SESSION_HISTORY] that the current query continues. Must match an existing topic label. If a new topic is introduced, use the label from [CURRENT_QUERY_TOPIC]. | |
rewrite_strategy | string | Must be one of: 'anaphora_resolution', 'entity_substitution', 'topic_continuation', 'topic_shift', or 'clarification'. Determines how downstream retrieval should weight the rewritten query against prior context. |
Common Failure Modes
Session-aware query rewrites fail in predictable ways. These are the most common production failure modes and how to guard against them before they degrade retrieval quality.
Stale Context Carryover
What to watch: The rewrite retains entities, filters, or constraints from earlier turns that no longer apply. A user shifts from 'Q3 revenue' to 'customer churn' but the rewrite still injects date-range filters from the revenue discussion. Guardrail: Implement a topic-shift detector that compares the current utterance embedding against the running session embedding. When cosine similarity drops below a threshold, discard prior context and rewrite from the current turn only.
Anaphora Resolution Failure
What to watch: Pronouns and implicit references ('it', 'that', 'the first one', 'hers') resolve to the wrong entity from conversation history or fail to resolve entirely, producing a query that retrieves irrelevant documents. Guardrail: Maintain an explicit entity map updated after each turn. Before rewriting, run a resolution check that links each pronoun to a specific entity ID. If resolution confidence is below threshold, emit a clarification request instead of a bad rewrite.
Topic Boundary Bleeding
What to watch: The rewrite merges context from two distinct topics when the user shifts subjects without an explicit boundary marker. A discussion about 'pricing tiers' followed by 'what about security' produces a rewrite about 'pricing tier security' instead of a clean security query. Guardrail: Segment the session into topic windows using embedding clustering. Only pull context from the current topic window. When a new topic is detected, start a fresh context window and log the boundary for traceability.
Over-Expansion from History
What to watch: The rewrite injects too many terms, synonyms, or constraints from prior turns, producing an over-specified query that returns zero or near-zero results. The user asks a simple follow-up but the rewrite includes every entity mentioned in the last five turns. Guardrail: Cap the number of history-derived terms injected into any rewrite. Apply a query relaxation fallback: if the expanded query returns fewer than N results, progressively drop history-derived constraints until retrieval recovers.
Clarification Loop Contamination
What to watch: When the system asks a clarification question and the user answers, the rewrite treats the clarification exchange as independent context rather than resolving it into the original query thread. The rewrite loses the original intent. Guardrail: Tag clarification turns explicitly in session state. When a clarification response arrives, merge it with the parent query that triggered the clarification before rewriting. Discard the intermediate system prompt from the rewrite context.
Session Boundary Mismatch
What to watch: The rewrite pulls context from a different session, a stale browser tab, or a resumed conversation where the user's intent has changed. Multi-tab or long-pause scenarios produce rewrites that mix unrelated contexts. Guardrail: Bind session context to a unique session ID with a configurable TTL. On session resume after a timeout, require a lightweight re-grounding turn before allowing history-dependent rewrites. Log session age as a metric and alert on anomalous session durations.
Evaluation Rubric
Criteria for testing the quality of session-aware query rewrites before deploying to production. Each criterion targets a specific failure mode in multi-turn conversational retrieval.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Anaphora Resolution | Pronouns and implicit references from [USER_HISTORY] are resolved to explicit entities in the rewritten query | Output retains pronouns like 'it', 'he', 'they' without explicit referent | Run 20 multi-turn test cases with clear antecedents; check output for unresolved pronouns using regex |
Ellipsis Handling | Incomplete follow-up questions are expanded into full, standalone queries using prior turn context | Output is a fragment that cannot be understood without the prior turn | Compare output to a human-authored standalone version; require semantic similarity score >= 0.85 |
Topic Shift Detection | When [CURRENT_QUERY] introduces a new topic, the rewrite ignores stale [USER_HISTORY] context | Output injects terms from a prior topic that is clearly unrelated to the current query | Create test pairs with abrupt topic shifts; verify cosine similarity between rewrite and prior topic terms is below threshold |
Entity Carry-Forward | Resolved entities from prior turns are correctly carried into the rewrite when still relevant | Output drops a previously resolved entity that is required to answer the current query | Track entity presence across turns; assert that active entities persist in rewrite until topic closure |
Clarification Incorporation | User corrections or clarifications from [USER_HISTORY] override prior ambiguous terms in the rewrite | Output uses a term the user explicitly corrected or rejected in a prior turn | Simulate clarification sequences; check that corrected terms replace original terms in the output |
Stale Context Pruning | Turns older than [SESSION_WINDOW] or marked as resolved are excluded from the rewrite | Output references entities or constraints from turns outside the active window | Set [SESSION_WINDOW] to 3 turns; assert no terms from turn 4+ appear in rewrite for a 6-turn session |
Permission Scope Preservation | The rewrite does not expand the query beyond the access boundaries defined in [USER_PERMISSIONS] | Output introduces filter terms or entity scopes that would retrieve documents outside user's authorized set | Run rewrites against a permission-aware retrieval index; assert zero results from unauthorized partitions |
Output Format Compliance | Output matches [OUTPUT_SCHEMA] exactly with all required fields present and correctly typed | Output is missing fields, has extra fields, or uses wrong types | Validate output against JSON Schema; fail on any schema violation; retry once on failure |
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
Use the base prompt with a simple conversation history array and a single-turn rewrite instruction. Skip structured output schemas and focus on whether the rewritten query resolves references correctly.
codeSystem: You are a query rewriter. Given the conversation history and the current user query, rewrite the query to be standalone and context-aware. History: [CONVERSATION_HISTORY] Current query: [USER_QUERY] Rewritten query:
Watch for
- Missing entity resolution when the user says "it" or "that"
- No handling of topic shifts—the rewrite may carry forward stale context
- Overly aggressive rewriting that changes the user's intent

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