This prompt is for agent builders and conversational AI engineers who maintain a structured dialogue state during a session and need to convert that state into a retrieval query. Unlike simple anaphora resolution or decontextualization prompts that operate on raw conversation history, this prompt assumes you already have a machine-readable dialogue state containing confirmed slots, user goals, open questions, and constraint flags. The prompt translates that structured state into a single, self-contained query string optimized for vector, keyword, or hybrid retrieval backends. Use this when your dialogue manager tracks slots explicitly and you need retrieval to reflect what the system has confirmed, not just what the user last said.
Prompt
Dialogue State to Query Rewrite Prompt Template

When to Use This Prompt
Determines the right conditions for converting a structured dialogue state into a retrieval query, and when a simpler approach is safer.
The ideal user has a dialogue state object with fields like intent, confirmed_slots, open_questions, constraints, and user_goal. This prompt is not a substitute for building that state tracker. If you only have raw conversation history, use a decontextualization or anaphora resolution prompt instead. This prompt adds value when the dialogue manager has already resolved ambiguities and confirmed critical details with the user—retrieval should honor those confirmed facts rather than re-deriving them from the latest utterance. The prompt also helps when the retrieval backend expects a single dense query but the dialogue state contains multiple active constraints that must be fused into one coherent string.
Do not use this prompt when the dialogue state is empty, unconfirmed, or stale. If the system has not yet confirmed a slot, including it in the query rewrite can poison retrieval with incorrect assumptions. Similarly, if the user has just contradicted a previously confirmed slot, the dialogue state must be updated before this prompt runs. A common failure mode is treating every slot as equally relevant to the current retrieval need—the prompt must be instructed to prioritize slots that align with the active user goal and deprioritize background context. Before wiring this into production, add a validation step that checks whether the generated query contradicts any confirmed slot in the input state, and log mismatches for review.
Use Case Fit
Where the Dialogue State to Query Rewrite prompt works and where it introduces risk. Use these cards to decide if this template fits your architecture before integrating it into a retrieval pipeline.
Good Fit: Structured Slot-Filling Agents
Use when: Your agent maintains a confirmed dialogue state with slots like destination, date_range, or budget. The prompt converts these structured slots into a single, dense retrieval query. Guardrail: Validate that every slot in the state appears in the rewritten query or is explicitly marked as unused to prevent silent information loss.
Bad Fit: Open-Ended Chitchat
Avoid when: The conversation has no structured state or the user's goal is exploratory browsing rather than constrained retrieval. Applying this prompt to casual dialogue produces overfitted queries that hallucinate constraints. Guardrail: Gate execution behind a dialogue act classifier that only triggers the rewrite when intent is search or lookup.
Required Input: Validated Dialogue State
Risk: Feeding unvalidated or incomplete state into the prompt produces queries that contradict the user's actual constraints. Guardrail: Run a state consistency check before calling the rewrite prompt. Reject states with conflicting slots or confidence scores below your threshold, and escalate to a clarification turn instead.
Operational Risk: State-Query Drift
Risk: The model may add terms, drop constraints, or reorder priorities in ways that silently change retrieval results. Guardrail: Implement a post-rewrite validator that extracts the implied constraints from the generated query and diffs them against the input state. Log any mismatch as a warning and block retrieval if critical slots are missing.
Operational Risk: Stale State Poisoning
Risk: A slot confirmed five turns ago may no longer be relevant after a topic shift, but the state still includes it. The rewritten query will carry forward an obsolete constraint. Guardrail: Attach a turn-age or confidence-decay marker to each slot. Prune slots older than your session window before passing state to the rewrite prompt.
Bad Fit: Single-Turn Retrieval Without State
Avoid when: Your system does not maintain dialogue state across turns. This prompt requires accumulated slots and goals. Using it on isolated queries wastes tokens and risks the model inventing phantom constraints. Guardrail: Use a simpler query expansion prompt for single-turn systems. Reserve this template for architectures with a confirmed state object.
Copy-Ready Prompt Template
A reusable prompt that converts accumulated dialogue state into a structured query rewrite for retrieval.
This template transforms a structured dialogue state object into a standalone retrieval query. It resolves confirmed slots, user goals, and open questions into a single search string that reflects everything the system knows so far. The prompt expects a JSON dialogue state as input and produces a query rewrite plus a confidence score and a list of unresolved slots that may require clarification before retrieval.
textYou are a dialogue-state-to-query rewriter for a retrieval system. Your job is to convert the current dialogue state into a single, self-contained search query that captures the user's confirmed intent, filled slots, and any open questions that need evidence. INPUT DIALOGUE STATE: [DOCUMENT] INSTRUCTIONS: 1. Review the confirmed slots, user goal, and open questions in the dialogue state. 2. Produce a rewritten query that: - Incorporates all confirmed slot values as explicit search terms. - Reflects the user's stated goal. - Includes terms for open questions that can be resolved through retrieval. - Is self-contained and does not rely on prior conversation context. - Uses the domain terminology provided in [TERMINOLOGY_MAP] when available. 3. If the dialogue state is missing critical slots required for a meaningful query, set confidence to LOW and list those slots in unresolved_slots. 4. If the dialogue state contains contradictory slot values, flag the conflict in the notes field and use the most recently confirmed value. OUTPUT SCHEMA: { "rewritten_query": "string", "confidence": "HIGH | MEDIUM | LOW", "unresolved_slots": ["slot_name"], "notes": "string" } CONSTRAINTS: - Do not invent slot values not present in the dialogue state. - Do not resolve open questions by guessing; only include them as search terms. - If the dialogue state is empty or contains only a greeting, return an empty query and set confidence to LOW. - Preserve any [NEGATION_SIGNALS] from the dialogue state in the rewritten query. [EXAMPLES]
Wire the [DOCUMENT] placeholder with your serialized dialogue state JSON. Populate [TERMINOLOGY_MAP] with domain-specific term mappings when users may use different language than your knowledge base. Supply [NEGATION_SIGNALS] as a list of terms or phrases that indicate the user has rejected a slot value. The [EXAMPLES] block should contain at least two few-shot examples showing a dialogue state and its correct rewritten query, including one example with unresolved slots and one with a full state. Before sending this prompt to production, validate that the output conforms to the schema using a JSON validator in your harness. For high-risk domains, route LOW-confidence outputs to a human reviewer or a clarification prompt before retrieval executes.
Prompt Variables
Inputs the prompt needs to work reliably. Validate each before calling the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DIALOGUE_STATE] | Accumulated dialogue state object containing confirmed slots, user goals, open questions, and session entities | {"confirmed_slots": {"destination": "Paris"}, "open_questions": ["budget"], "user_goal": "book_flight"} | Must be valid JSON. Check that confirmed_slots and open_questions keys exist. Reject if state is empty or null when conversation has prior turns. |
[CURRENT_TURN] | The user's most recent utterance that needs to be rewritten for retrieval | What about hotels there next month? | Must be a non-empty string. Check for minimum length of 2 characters. Reject if identical to prior turn without new information. |
[CONVERSATION_HISTORY] | Prior turns in the conversation, formatted as ordered list of speaker-utterance pairs | [{"speaker": "user", "text": "I need a flight to Paris"}, {"speaker": "assistant", "text": "What is your budget?"}] | Must be an array of objects with speaker and text fields. Validate speaker values are user or assistant. Check that history is not empty when dialogue state has confirmed slots. |
[OUTPUT_SCHEMA] | Expected structure for the rewritten query output, including fields for rewritten query, confidence, and unresolved references | {"rewritten_query": "string", "confidence": 0.0-1.0, "unresolved_references": ["string"], "state_consistency_check": true|false} | Must be a valid JSON schema object. Validate that rewritten_query is required and confidence is a float between 0 and 1. Reject schemas missing state_consistency_check field. |
[RETRIEVAL_BACKEND] | Target retrieval system type that influences query formulation style | hybrid_vector_keyword | Must be one of: dense_vector, sparse_keyword, hybrid_vector_keyword, graph_traversal. Reject unknown backend types. Check that rewrite style matches backend expectations. |
[ENTITY_CATALOG] | Canonical entity identifiers and their surface forms from the knowledge base | [{"canonical_id": "LOC_PAR", "surface_forms": ["Paris", "City of Light", "CDG area"]}] | Must be an array of entity objects with canonical_id and surface_forms. Validate that canonical_id is non-empty. Null allowed if no entity catalog is configured. |
[STATE_QUERY_CONSISTENCY_RULES] | Rules for checking that the rewritten query does not contradict or drop confirmed dialogue state | ["confirmed_slots must appear in rewritten query as explicit constraints", "open_questions must not be treated as resolved"] | Must be a non-empty array of rule strings. Each rule must be actionable. Reject if rules are vague or cannot be programmatically checked. |
[MAX_QUERY_LENGTH] | Maximum token or character length for the rewritten query to prevent over-expansion | 256 | Must be a positive integer. Check that rewritten query length does not exceed this value. Reject if set below 50 tokens for complex dialogue states. |
Implementation Harness Notes
How to wire the dialogue state to query rewrite prompt into a production RAG or agent application with validation, retries, and state-consistency checks.
This prompt is designed to sit between your dialogue state tracker and your retrieval system. The application harness should call this prompt only when the dialogue state has been updated with new user input and confirmed slots. Do not call it on every turn if the state is unchanged; instead, cache the last rewrite and invalidate it when slots, goals, or open questions are modified. The harness must serialize the dialogue state into a structured object matching the [DIALOGUE_STATE] placeholder, typically a JSON blob containing confirmed_slots, user_goal, open_questions, and conversation_history_summary. Avoid passing raw transcript logs directly—pre-summarize turns into a compact state representation to keep token usage predictable and latency low.
Validation is the most critical part of the harness. After receiving the rewritten query, validate it against the input dialogue state: every confirmed slot should be reflected in the query's constraints, and no hallucinated constraints should appear that weren't in the state. Implement a state-query consistency check that diffs the confirmed slots against the query's filter clauses. If the check fails, log the mismatch with the dialogue state version, the generated query, and the specific slots that were dropped or invented. Then retry with a stricter [CONSTRAINTS] block that explicitly lists the slots that must appear. Set a maximum of 2 retries before falling back to a simpler query constructed programmatically from the confirmed slots alone. For high-stakes domains like healthcare or finance, route consistency failures to a human review queue rather than silently serving a degraded query.
Model choice matters here. Use a model with strong instruction-following and JSON manipulation capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set temperature to 0 or a very low value (0.1) to minimize creative drift in constraint translation. The harness should log every rewrite attempt with: the dialogue state version hash, the generated query, the consistency check result, the retry count, and the final query served to retrieval. This audit trail is essential for debugging retrieval failures—when a user says 'it didn't find what I asked for,' you need to trace whether the rewrite dropped a constraint, the retrieval index missed it, or the answer generator ignored it. Wire these logs into your existing observability stack (e.g., Datadog, Grafana, or custom trace storage) with the dialogue state version as the primary correlation key.
Expected Output Contract
Validation rules for the structured query rewrite object returned by the Dialogue State to Query Rewrite prompt. Use this contract to parse, validate, and reject malformed outputs before forwarding to retrieval.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
rewritten_query | string | Must be non-empty. Must not contain unresolved slot placeholders or raw dialogue state tokens. Parse check: string length > 0. | |
resolved_slots | array of objects | Each object must include slot_name (string), slot_value (string), and source_turn (integer). Array may be empty. Schema check: validate each object against required sub-fields. | |
open_questions | array of strings | Each string must be a non-empty question. Array may be empty. If dialogue state indicates unresolved intents, this array must contain at least one entry. Consistency check: cross-reference with [DIALOGUE_STATE] unresolved flags. | |
state_query_consistency | boolean | Must be true or false. If false, the output must be rejected and the prompt retried. Retry condition: consistency == false triggers a retry with explicit state contradiction highlighted. | |
confidence_score | float between 0.0 and 1.0 | Must be a number. If below 0.7, route output for human review before retrieval. Threshold check: confidence < 0.7 triggers approval required. | |
applied_filters | object | If present, must include metadata_filters (array of key-value pairs) and temporal_range (object with start_date and end_date in ISO 8601 format). Null allowed. Schema check: validate temporal_range format if provided. | |
excluded_entities | array of strings | Each string must match an entity explicitly negated or excluded in [DIALOGUE_STATE]. Null allowed. Consistency check: no entity in this array should appear in resolved_slots slot_value fields. | |
rewrite_rationale | string | If present, must be a brief explanation of the rewrite strategy applied. Null allowed. Used for debugging and trace analysis only; not forwarded to retrieval. |
Common Failure Modes
What breaks first when converting dialogue state into retrieval queries and how to guard against it.
Stale Slot Contamination
What to watch: Confirmed slots from earlier turns persist in the dialogue state and leak into the rewritten query even after the user changes topics or contradicts them. The retrieval system searches for outdated constraints, returning irrelevant results. Guardrail: Implement a slot freshness check that compares the last-updated timestamp of each slot against the current turn boundary. Expire or deprioritize slots not reconfirmed within a configurable window. Log expired-slot exclusions for observability.
Over-Resolution of Open Questions
What to watch: The prompt treats unresolved slots or open questions as confirmed facts, generating a query that assumes information the user hasn't provided yet. This produces confident but wrong retrieval results based on hallucinated constraints. Guardrail: Add an explicit open_questions field to the dialogue state schema. Require the rewrite prompt to mark any query clause derived from an open question with a confidence flag. Validate that no open-question-derived constraint appears as a hard filter in the final query without human or heuristic approval.
Dialogue State Drift Under Topic Shifts
What to watch: The accumulated dialogue state retains entities, filters, and goals from a prior topic after the user pivots to a completely new subject. The rewritten query mixes constraints from both topics, producing a nonsensical hybrid retrieval that matches neither intent. Guardrail: Run a topic-shift detector on each new user turn before state-to-query conversion. When a topic boundary is detected, reset non-persistent slots and generate a fresh query from only the current-turn state. Log topic-shift events with the slots that were cleared.
Implicit Goal Contradiction
What to watch: The user's stated goal in the dialogue state conflicts with the constraints they've confirmed. For example, a goal of 'find budget options' paired with confirmed slots for premium features. The rewritten query silently resolves the contradiction by dropping one side, usually the goal, leading to retrieval that misses user intent. Guardrail: Add a consistency validator that checks goal-slot alignment before query generation. When a contradiction is detected, either generate two candidate queries (one goal-prioritized, one slot-prioritized) or flag for clarification rather than silently resolving.
Missing Slot Default Injection
What to watch: The prompt fills unconfirmed slots with system defaults or model-inferred values to produce a complete query, but those defaults don't match the user's actual needs. The retrieval returns results biased toward the default assumptions rather than the user's unspecified intent. Guardrail: Distinguish between 'unset' and 'defaulted' in the dialogue state schema. For unset slots, generate queries that explicitly leave those dimensions open (e.g., broad date ranges, no filter clause) rather than injecting defaults. Log every default injection with a reason for auditability.
State-to-Query Hallucination Under Sparse State
What to watch: When the dialogue state contains only one or two confirmed slots, the model over-extrapolates and fabricates additional query terms, entities, or constraints to make the query 'look complete.' This produces retrieval results that appear relevant but drift from the actual sparse user intent. Guardrail: Constrain the rewrite prompt to generate queries using only explicitly confirmed slots, with a strict rule against adding ungrounded terms. Validate the output query against the input state by extracting all query clauses and mapping each back to a confirmed slot or an explicit 'open' marker. Reject queries with unmapped clauses.
Evaluation Rubric
Score each criterion on a 0-3 scale before shipping the Dialogue State to Query Rewrite prompt. A score of 2 or higher is required for production deployment.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Slot-to-Query Consistency | Every confirmed slot in [DIALOGUE_STATE] appears as a constraint or term in the rewritten query | A confirmed slot is missing from the output query or is contradicted by a query term | Diff [DIALOGUE_STATE] slots against extracted query constraints; flag missing or contradictory slots |
Open Question Preservation | All open questions from [DIALOGUE_STATE] are reflected as query intent without premature resolution | An open question is answered in the query rewrite or dropped entirely | Parse [DIALOGUE_STATE] open questions list; verify each maps to a query clause or sub-query intent |
State-Query Hallucination Check | No entity, constraint, or intent appears in the query that is absent from [DIALOGUE_STATE] and [CURRENT_TURN] | The query introduces a filter, date range, or entity not present in state or current turn | Extract all query entities and constraints; cross-reference against [DIALOGUE_STATE] and [CURRENT_TURN]; flag additions |
Anaphora and Reference Resolution | All pronouns and referring expressions from [CURRENT_TURN] are replaced with explicit entities from [DIALOGUE_STATE] | A pronoun or vague reference survives in the output query without explicit resolution | Scan output for pronouns and demonstratives; confirm each has an explicit antecedent from state |
Structured Output Schema Compliance | Output matches [OUTPUT_SCHEMA] exactly: all required fields present, no extra fields, correct types | Missing required field, extra field, or type mismatch in JSON output | Validate output against [OUTPUT_SCHEMA] with a JSON schema validator; fail on any violation |
Intent Alignment | The rewritten query targets the same user goal recorded in [DIALOGUE_STATE] intent field | The query shifts intent from lookup to comparison, or from factual to procedural, without state justification | Classify output query intent; compare to [DIALOGUE_STATE] intent label; flag mismatches |
Temporal Constraint Normalization | Relative time expressions from [CURRENT_TURN] are resolved to absolute ranges using [DIALOGUE_STATE] temporal anchors | A relative time expression remains unresolved or is resolved to an incorrect absolute range | Extract temporal expressions from output; verify each is absolute and consistent with state anchors |
Negation Handling | Negation signals from [CURRENT_TURN] and [DIALOGUE_STATE] are preserved as exclusion constraints in the query | A negation is dropped or converted to an affirmative constraint | Parse output for exclusion operators; cross-reference with negation signals in state and current turn |
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 lightweight dialogue state object. Use a frontier model with minimal output constraints to test whether the rewrite captures confirmed slots and open questions. Skip strict schema validation initially; focus on semantic correctness.
Watch for
- The model dropping confirmed slots from the rewrite
- Open questions being treated as resolved facts
- Overly verbose rewrites that reintroduce conversational filler

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