This prompt is designed for search engineers and RAG developers who need to perform a surgical diagnosis on a single production trace to determine whether a query rewriting step improved or degraded retrieval quality. The core job-to-be-done is comparing the retrieval precision of the original user query against the rewritten queries. You should use this prompt when you have captured a complete trace in your observability platform that includes the original user query, the set of rewritten queries generated by your system, the final list of retrieved document chunks with their ranking scores, and the final generated answer. The prompt's value is in isolating the rewrite step's specific contribution to the overall outcome, separating it from generation or ranking issues.
Prompt
Retrieval Query Rewrite Trace Prompt

When to Use This Prompt
Defines the precise job-to-be-done, ideal user, required inputs, and boundaries for the Retrieval Query Rewrite Trace Prompt.
To use this prompt effectively, you must provide a structured trace object. The required inputs are: the [ORIGINAL_QUERY], a list of [REWRITTEN_QUERIES], a list of [RETRIEVED_CHUNKS] with their associated scores, and the [FINAL_ANSWER]. The prompt is designed to produce a structured assessment that identifies specific failure modes such as synonym drift (where a rewrite term has a different meaning in the target domain), over-expansion (where the rewrite broadens the query so much that it retrieves irrelevant results), or missed intent (where a critical constraint from the original query is dropped). The output is not a simple pass/fail; it's a qualitative diagnostic report with actionable recommendations for adjusting your rewrite prompt or strategy.
Do not use this prompt for aggregate pipeline monitoring, real-time alerting, or as a replacement for offline evaluation metrics like Mean Reciprocal Rank (MRR) or Normalized Discounted Cumulative Gain (NDCG). It is not designed to process batches of traces or to trigger automated rollbacks. Its strength is in isolated, human-in-the-loop trace inspection during specific workflows: incident response, where a retrieval failure has been escalated; QA review, where you are manually auditing a sample of production sessions; or rewrite-prompt iteration, where you are A/B testing a new rewriting strategy and need to understand why one variant underperformed on a specific case. For continuous monitoring, you should implement a separate evaluation harness that uses this prompt's rubric as a scoring function, but the prompt itself is a manual diagnostic tool.
Use Case Fit
Where the Retrieval Query Rewrite Trace Prompt delivers value and where it introduces risk or noise.
Good Fit: RAG Pipeline Tuning
Use when: you are actively tuning a RAG system and need to isolate whether poor answer quality originates from retrieval or generation. Guardrail: Run this trace prompt on a statistically significant sample of queries before changing rewrite logic to avoid overfitting to a single trace.
Bad Fit: Real-Time Guardrails
Avoid when: you need a low-latency, inline check to block a bad rewrite before retrieval executes. This prompt is designed for post-hoc trace analysis, not synchronous decision-making. Guardrail: Use a lightweight classifier or regex-based validation for real-time rewrite quality checks.
Required Inputs
What you need: a complete trace containing the original user query, all rewritten queries, the final retrieved chunks, and the generated answer. Guardrail: If your tracing system samples or truncates spans, validate trace completeness before running this prompt to avoid false negatives in the assessment.
Operational Risk: Confirmation Bias
What to watch: engineers may use this prompt only on traces where they already suspect a rewrite failure, skewing the perceived failure rate. Guardrail: Schedule regular, randomized trace audits using this prompt to establish a baseline rewrite quality metric independent of incident-driven reviews.
Operational Risk: Prompt Drift in the Trace Prompt
What to watch: the trace analysis prompt itself can drift over time, changing how rewrite quality is scored and making historical comparisons invalid. Guardrail: Version this prompt alongside your application prompts and run it against a golden set of annotated traces to detect scoring drift before it affects your dashboards.
Copy-Ready Prompt Template
A ready-to-use prompt for analyzing a single RAG trace to evaluate query rewriting effectiveness.
This prompt is designed to be pasted directly into your LLM playground, internal diagnostics console, or trace review tool. It instructs the model to act as a search quality analyst, comparing the original user query against the rewritten queries, the documents they retrieved, and the final answer generated. The goal is to produce a structured assessment of whether the rewrite improved, degraded, or had no effect on retrieval precision and answer quality. Before execution, you must replace every square-bracket placeholder with actual data extracted from your production trace spans.
textYou are a search quality analyst reviewing a single Retrieval-Augmented Generation (RAG) trace. Your task is to evaluate the effectiveness of a query rewriting step by comparing the original user query against the rewritten queries, the documents each query retrieved, and the final answer produced. ## INPUT DATA ### Original User Query [ORIGINAL_QUERY] ### Rewritten Queries [REWRITTEN_QUERIES] ### Documents Retrieved by Original Query [ORIGINAL_RETRIEVED_DOCUMENTS] ### Documents Retrieved by Rewritten Queries [REWRITTEN_RETRIEVED_DOCUMENTS] ### Final Answer Generated [FINAL_ANSWER] ### Expected or Ground Truth Answer (Optional) [GROUND_TRUTH_ANSWER] ## ANALYSIS INSTRUCTIONS 1. **Intent Preservation**: Did the rewritten queries preserve the core intent, entities, and constraints of the original query? Note any intent drift, over-specification, or critical omissions. 2. **Retrieval Precision Comparison**: Compare the relevance of documents retrieved by the original query versus the rewritten queries. Identify if the rewrite surfaced more relevant documents, introduced more noise, or missed key documents that the original query found. 3. **Answer Quality Impact**: Trace how the difference in retrieved documents affected the final answer. Did the rewrite enable a more accurate, complete, or well-cited answer, or did it cause a hallucination or omission? 4. **Rewrite Strategy Assessment**: Classify the rewrite strategy used (e.g., decomposition, synonym expansion, abstraction, metadata filtering) and judge if it was the appropriate strategy for this query type. ## OUTPUT FORMAT You must respond with a valid JSON object conforming to this schema: { "rewrite_quality_assessment": { "intent_preserved": boolean, "intent_drift_notes": "string explaining any drift detected", "retrieval_precision_change": "improved" | "degraded" | "no_change", "retrieval_comparison_details": "string comparing key documents found or missed", "answer_quality_impact": "positive" | "negative" | "neutral", "answer_impact_details": "string linking document changes to answer changes", "rewrite_strategy_used": "string describing the strategy", "strategy_appropriateness": "appropriate" | "inappropriate" | "uncertain", "overall_verdict": "rewrite_helped" | "rewrite_hurt" | "rewrite_neutral", "recommendation": "string with actionable advice for the prompt engineer" } } ## CONSTRAINTS - Base your analysis strictly on the provided trace data. Do not invent documents or queries. - If the final answer contains a hallucination not supported by any retrieved document, you must flag it in the `answer_impact_details`. - If the [GROUND_TRUTH_ANSWER] is provided, use it to validate the final answer's correctness, but do not penalize the rewrite for retrieval gaps if the ground truth was not in the document store.
To adapt this template, replace the placeholders with raw trace data. For [ORIGINAL_RETRIEVED_DOCUMENTS] and [REWRITTEN_RETRIEVED_DOCUMENTS], include the document ID, rank, and a snippet of the text. If your trace does not capture what the original query would have retrieved in isolation, you may need to run a separate retrieval step to populate that field. The [GROUND_TRUTH_ANSWER] is optional but highly recommended for high-stakes evaluations; when omitted, the model will rely solely on internal consistency and document relevance. After generating the JSON output, you should validate it against the schema programmatically before accepting the assessment. For regulated or customer-facing search applications, always have a human review the intent_drift_notes and recommendation before changing the rewrite prompt in production.
Prompt Variables
Each placeholder required by the Retrieval Query Rewrite Trace Prompt. Use this table to prepare trace data before running the prompt, and to validate that required fields are present and well-formed.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ORIGINAL_USER_QUERY] | The exact user query as received by the system, before any rewriting or expansion. | What are the latency requirements for the new inference API? | Must be a non-empty string. Validate that this matches the user input recorded in the trace span. Null or empty input should abort the prompt. |
[REWRITTEN_QUERIES] | The list of queries generated by the query rewriter, including any decompositions or expansions. | ['latency requirements inference API', 'inference API SLA latency p95', 'new API latency spec'] | Must be a JSON array of strings. Validate that at least one rewritten query exists. An empty array signals a rewriter failure and should be flagged in the output. |
[RETRIEVED_CHUNKS] | The top-k document chunks returned by the retrieval system for each rewritten query, including metadata. | [{'query': 'latency requirements inference API', 'chunks': [{'id': 'doc_12', 'text': '...', 'score': 0.92}]}] | Must be a JSON array of objects, each containing a 'query' and 'chunks' array. Validate that chunk 'id' and 'text' fields are present. Missing chunks for a query indicate a retrieval gap. |
[FINAL_ANSWER] | The final synthesized answer generated by the model from the retrieved context. | The new inference API requires a p95 latency under 200ms for standard tier and under 80ms for priority tier. | Must be a non-empty string. Validate that the answer is present in the trace. A null or empty answer indicates a generation failure and should be noted as a critical gap. |
[REWRITER_MODEL_ID] | Identifier for the model or configuration used to rewrite the original query. | gpt-4o-rewriter-v2 | Must be a non-empty string matching a known model ID pattern. Validate against an allowlist of deployed rewriter models. An unknown ID should trigger a warning. |
[RETRIEVAL_SYSTEM_ID] | Identifier for the retrieval system, index, or collection queried. | prod-docs-v3-hybrid | Must be a non-empty string. Validate against an allowlist of active retrieval backends. A mismatch between the trace and the expected production index is a critical finding. |
[TRACE_ID] | Unique identifier for the production trace being analyzed. | trace_8a7b3c2d_2025-01-15T14:22:10Z | Must be a non-empty string matching the organization's trace ID format. Validate using a regex pattern. A malformed or missing trace ID prevents trace correlation. |
Implementation Harness Notes
How to wire the Retrieval Query Rewrite Trace Prompt into a trace review workflow or automated diagnostics pipeline.
This prompt is designed to be a single step in a larger trace review harness, not a standalone chat. The harness should extract the required inputs—the original user query, the rewritten queries, the retrieved results, and the final answer—from your observability platform's trace data before invoking the model. Because the prompt's value depends on complete input data, the harness must first validate that all required trace segments are present. If the trace is missing the rewritten query or the retrieval payload, the harness should abort and flag the trace as incomplete rather than running the prompt on partial data.
The implementation should follow a structured pipeline: Extract → Validate → Prompt → Parse → Evaluate. In the Extract phase, pull the relevant spans from your tracing system (e.g., LangSmith, Arize, Datadog, or custom trace store) using the trace ID. In the Validate phase, confirm that the original query, rewritten query list, retrieved document set with scores, and final generated answer are all non-null. If validation fails, log a trace_incomplete event and skip the prompt. In the Prompt phase, populate the template's placeholders with the extracted data and send it to a capable model (GPT-4o, Claude 3.5 Sonnet, or equivalent). In the Parse phase, enforce the output schema—the model must return valid JSON matching the RewriteQualityAssessment structure. If parsing fails, retry once with a stricter schema instruction; if it fails again, log a parse_failure and escalate for human review. In the Evaluate phase, run automated checks: verify that the retrieval_precision_before and retrieval_precision_after fields are numeric and within 0–1, that the rewrite_quality_score is an integer 1–5, and that the failure_mode field is not null when the score is below 3.
For production use, wrap this prompt in a versioned function with structured logging. Log the trace ID, the model version used, the prompt template version, the raw model output, the parsed assessment, and any parse or validation errors. This log becomes the audit trail for query rewrite quality over time. If you're running this prompt across many traces for aggregate analysis, batch the evaluations and write the structured outputs to a database or metrics store. Avoid the temptation to use this prompt for real-time query rewriting during user requests—it is a diagnostic tool for offline trace review, not a runtime rewriter. The next step after implementing this harness is to connect the structured output to a dashboard that tracks rewrite quality trends, retrieval precision deltas, and failure mode distributions across your production traffic.
Expected Output Contract
Fields, data types, and validation rules for the JSON response produced by the Retrieval Query Rewrite Trace Prompt. Use this contract to parse, validate, and integrate the rewrite quality assessment into downstream retrieval evaluation pipelines.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
trace_id | string | Must match the input trace ID exactly. Non-empty and no whitespace trimming allowed. | |
original_query | string | Must be a non-empty string. If missing from trace, set to null and flag in errors array. | |
rewritten_queries | array of strings | Must contain at least one string element. Empty array allowed only if no rewrite occurred; must be accompanied by rewrite_applied: false. | |
rewrite_applied | boolean | Must be true if rewritten_queries differs from [original_query]; false if identical or empty. Schema rejects null. | |
retrieval_precision_before | number | Must be a float between 0.0 and 1.0 inclusive. Calculated as relevant_chunks / total_retrieved_chunks from the original query retrieval step. | |
retrieval_precision_after | number | Must be a float between 0.0 and 1.0 inclusive. If rewrite_applied is false, this field must equal retrieval_precision_before. | |
precision_delta | number | Must equal retrieval_precision_after minus retrieval_precision_before. Range -1.0 to 1.0. Null not allowed. | |
rewrite_quality_assessment | string | Must be one of: 'improved', 'degraded', 'unchanged', 'not_applicable'. 'not_applicable' only valid when rewrite_applied is false. | |
final_answer_quality_flag | string | Must be one of: 'acceptable', 'degraded', 'unacceptable'. Determined by comparing answer grounding score against a configurable threshold (default 0.7). | |
errors | array of objects | Each object must have 'field' (string) and 'message' (string). Empty array if no validation errors. Must be present even if empty. |
Common Failure Modes
What breaks first when analyzing retrieval query rewrite traces and how to guard against it.
Rewritten Query Drifts from Intent
What to watch: The rewritten query changes the semantic meaning of the original user query, causing retrieval of irrelevant documents. This often happens when the rewrite model over-expands, adds incorrect synonyms, or drops critical constraints. Guardrail: Compare the original and rewritten queries side by side in the trace output. Add a semantic similarity threshold check—if cosine similarity between original and rewritten embeddings falls below 0.7, flag the rewrite for human review before trusting downstream retrieval quality.
Retrieval Precision Drops After Rewrite
What to watch: The rewritten query retrieves more documents but with lower relevance than the original query would have achieved. This creates a false sense of improvement because recall appears higher while precision collapses. Guardrail: Always include a baseline comparison in the trace analysis—run the original query against the same retrieval pipeline and compare precision@k scores. If the rewritten query's precision is lower, the rewrite is harming quality even if more documents are returned.
Missing Context from Dropped Query Terms
What to watch: The rewrite model drops domain-specific terms, entity names, or temporal constraints that were essential for accurate retrieval. The trace shows rewritten queries that are cleaner but semantically incomplete. Guardrail: Extract named entities and key noun phrases from the original query before rewriting. After the rewrite, verify that all extracted entities appear in the rewritten query or are explicitly handled through metadata filters. Flag any rewrite that drops entities without justification.
Over-Expansion Causes Noise Overload
What to watch: The rewrite model generates too many query variants or adds overly broad synonyms, flooding the retrieval pipeline with low-quality candidates. The context window fills with irrelevant passages, pushing out useful evidence. Guardrail: Cap the number of rewritten query variants at 3-5. After retrieval, measure the relevance distribution of returned documents—if more than 50% fall below a relevance threshold, the rewrite expansion is too aggressive and should be constrained.
Metadata Filter Conflicts with Rewritten Query
What to watch: The rewritten query introduces terms that conflict with applied metadata filters, causing zero results or contradictory retrieval constraints. For example, a rewrite adds a date range that contradicts a hard filter on document recency. Guardrail: Log all active metadata filters alongside the rewritten query in the trace. Add a validation step that checks for logical conflicts between query terms and filter values before execution. If a conflict is detected, fall back to the original query with filters intact.
Final Answer Ignores Retrieved Context
What to watch: The trace shows that rewriting and retrieval worked correctly, but the generation model ignored the retrieved documents and hallucinated an answer. The rewrite quality assessment becomes misleading because the failure is downstream. Guardrail: Separate the trace analysis into distinct stages—rewrite quality, retrieval quality, and generation faithfulness. Add a grounding check that compares each claim in the final answer against the retrieved context. If grounding fails but retrieval succeeded, the problem is in generation, not rewriting.
Evaluation Rubric
Use this rubric to test the quality of the Retrieval Query Rewrite Trace Prompt's output before relying on it for production diagnosis. Each criterion targets a specific failure mode common in rewrite analysis.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Original Query Preservation | The [ORIGINAL_QUERY] field in the output exactly matches the input [USER_QUERY] string, with no added or removed characters. | The output paraphrases, truncates, or corrects the user's original query. | Exact string match between input [USER_QUERY] and output [ORIGINAL_QUERY]. |
Rewrite Sequence Completeness | Every rewritten query from the [REWRITE_LOG] is listed in the output's [REWRITE_SEQUENCE] array in the order it was generated. | A rewrite step present in the trace log is missing from the output array, or the order is reversed. | Count and order validation: length of output [REWRITE_SEQUENCE] must equal length of input [REWRITE_LOG], and each element must match by index. |
Retrieval Precision Delta Calculation | The [PRECISION_DELTA] field is a numeric value equal to (post-rewrite precision - pre-rewrite precision), calculated from the provided [RETRIEVAL_METRICS]. | The delta is a text description, a percentage string, or a number that does not match the arithmetic difference of the provided precision scores. | Parse [PRECISION_DELTA] as a float and assert it equals (input [RETRIEVAL_METRICS].post_rewrite_precision - input [RETRIEVAL_METRICS].pre_rewrite_precision) within a tolerance of 0.001. |
Root-Cause Classification Validity | The [REWRITE_QUALITY_ASSESSMENT] field contains exactly one of the allowed enum values: 'improved', 'degraded', 'no_change', or 'inconclusive'. | The assessment field contains a free-text explanation, a null value, or a value not in the allowed enum list. | Validate the field against the enum set. If the field is missing or invalid, the test fails. |
Evidence Grounding for Assessment | The [ASSESSMENT_RATIONALE] field cites at least one specific piece of evidence from the trace, such as a retrieved document ID, a precision score, or a query term change. | The rationale is generic (e.g., 'the rewrite helped') or repeats the assessment label without referencing trace data. | Check that [ASSESSMENT_RATIONALE] contains at least one reference to a field present in the input trace, such as a doc ID from [RETRIEVED_DOCS] or a term from [REWRITE_LOG]. |
Final Answer Alignment Check | The [ANSWER_QUALITY_NOTE] correctly identifies if the final answer used information from pre-rewrite or post-rewrite retrieval based on the provided [CITATION_MAP]. | The note claims the answer used post-rewrite context when citations only map to pre-rewrite documents, or vice versa. | Cross-reference the doc IDs in [CITATION_MAP] against the [RETRIEVED_DOCS] lists for pre- and post-rewrite stages to verify the note's claim. |
Schema Compliance | The output is valid JSON that parses without errors and contains all required fields: [ORIGINAL_QUERY], [REWRITE_SEQUENCE], [PRECISION_DELTA], [REWRITE_QUALITY_ASSESSMENT], [ASSESSMENT_RATIONALE], [ANSWER_QUALITY_NOTE]. | The output is missing a required field, contains an extra field not in the schema, or fails to parse as JSON. | Parse the output with a JSON validator. Check for the presence of all required keys and the absence of unexpected keys. Fail on any parsing error. |
Hallucinated Metric Resistance | All numeric metrics in the output (e.g., [PRECISION_DELTA]) are derived from the input [RETRIEVAL_METRICS] and not invented by the model. | The output contains a precision score, recall score, or other metric that is not present in the input [RETRIEVAL_METRICS] object. | Extract all numeric values from the output and assert that each one can be found in or calculated from the input [RETRIEVAL_METRICS]. Flag any novel numbers. |
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 single trace and lighter validation. Focus on getting a readable rewrite quality assessment without strict schema enforcement. Replace [OUTPUT_SCHEMA] with a simple markdown table format. Skip the retrieval precision harness and rely on manual review of the rewritten queries against the original.
Watch for
- The model may produce narrative prose instead of structured assessment
- Rewrite quality scores may be inconsistent without calibration examples
- No automated comparison of pre-rewrite vs. post-rewrite retrieval results

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