Back to cookbook

ChatGPT Prompt to Rewrite User Queries for Better RAG Retrieval Results

15 views Published

Make this prompt yours

Share

This ChatGPT prompt is for developers building a RAG (retrieval-augmented generation) system who are seeing weak or irrelevant search results even when the answer clearly exists somewhere in the knowledge base. The problem is usually the query itself: a short, vague, or pronoun-heavy user question ("what about the second one?") retrieves poorly against a vector index, no matter how good the underlying embeddings are.

The prompt uses an LLM as a query rewriting step that runs before retrieval: it expands abbreviations, resolves references from prior conversation turns, and restates the question in the kind of specific, keyword-rich language that matches how information is actually phrased in source documents. This is a standard technique in production RAG pipelines, often called query expansion or query reformulation, and it typically improves recall without touching the retrieval index or embedding model at all.

Once you've rewritten a query, the actual retrieval step still has to pull the right passages out of your source material — a tool like Context Extractor is built for that half of the pipeline, pulling only the relevant snippets from large documents based on the query you feed it.

Prompt template

Make this prompt yours

prompt-template
221 tokens
ROLE: You are a query rewriting assistant for a document retrieval system. Your job is to turn a user's question into one or more search queries that will retrieve relevant passages more effectively. CONTEXT: Conversation history (most recent last): [PASTE_LAST_2-4_CONVERSATION_TURNS] Current user question: [PASTE_CURRENT_QUESTION] TASK: 1. Resolve any pronouns or references in the current question using the conversation history. 2. Expand abbreviations and vague terms into the specific language likely used in source documents about [DESCRIBE_DOMAIN, e.g. "internal HR policy documents"]. 3. Produce [NUMBER, e.g. 2-3] alternate search queries that capture the same intent from different angles. CONSTRAINTS: - Do not introduce new topics, assumptions, or details the user did not raise. - Keep each rewritten query under 20 words. - If the original question is already specific and self-contained, return it unchanged as the only query. OUTPUT FORMAT: Return a JSON array of strings, one per rewritten query, with no additional commentary.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
239 tokens
ROLE: You are a query rewriting assistant for a document retrieval system. Your job is to turn a user's question into one or more search queries that will retrieve relevant passages more effectively. CONTEXT: Conversation history (most recent last): User: Can employees carry over unused vacation days into the next year? Assistant: Yes, up to 5 days can be carried over, based on current policy. User: What about sick days, does the same rule apply? Current user question: What about sick days, does the same rule apply? TASK: 1. Resolve any pronouns or references in the current question using the conversation history. 2. Expand abbreviations and vague terms into the specific language likely used in source documents about internal HR policy documents. 3. Produce 2-3 alternate search queries that capture the same intent from different angles. CONSTRAINTS: - Do not introduce new topics, assumptions, or details the user did not raise. - Keep each rewritten query under 20 words. - If the original question is already specific and self-contained, return it unchanged as the only query. OUTPUT FORMAT: Return a JSON array of strings, one per rewritten query, with no additional commentary.

When to use it

  • A RAG chatbot returns irrelevant or no results for questions that reference earlier conversation turns ("what's the refund policy for that?")
  • Users type short, underspecified queries that don't contain the keywords your source documents actually use
  • Retrieval recall is noticeably worse on multi-part or comparative questions than on single, direct ones
  • You want to add query expansion to an existing RAG pipeline without retraining or re-embedding anything

Best practices

  • Feed the rewriting step the last few turns of conversation, not just the current message, so it can resolve pronouns and references correctly
  • Ask the model to produce 2-3 alternate phrasings of the same query rather than a single rewrite, then retrieve against all of them and merge results
  • Keep the rewritten query grounded in the original intent — instruct the model not to introduce new topics or assumptions the user didn't raise
  • Log the original query alongside the rewritten one during testing so you can see exactly what changed when retrieval quality shifts

Common mistakes

  • Letting the rewrite step change the meaning of the question instead of just clarifying its phrasing
  • Rewriting every query the same way regardless of whether it's a follow-up or a fresh, already-specific question
  • Not testing the rewritten queries against real retrieval results, so a rewrite that reads better doesn't actually retrieve better
  • Skipping conversation history entirely, which leaves pronoun-based follow-up questions unresolved and poorly retrieved

FAQs

Why does my RAG chatbot fail on follow-up questions but work fine on first questions?

Follow-up questions often rely on pronouns or implied context from earlier turns ("what about that one"), and a retrieval system searches on the literal text of the query. Without a rewriting step that resolves those references first, the retriever has no way to know what "that one" refers to.

Does query rewriting replace the need for good embeddings or chunking?

No, it's a complementary technique. Query rewriting improves the input to retrieval, while embedding quality and chunking strategy determine how well that retrieval actually performs once it has a clear query to work with.

Should I always generate multiple rewritten queries instead of just one?

Generating 2-3 alternate phrasings and merging the retrieved results generally improves recall more than a single rewrite, especially for ambiguous or broad questions, though it does add a small amount of latency and retrieval cost per query.

Can query rewriting introduce hallucinated details into the search query itself?

Yes, if the rewriting prompt isn't constrained carefully. An unconstrained rewrite step can add assumptions the user never stated, which then biases retrieval toward the wrong passages, so explicitly instructing the model not to introduce new topics is important.

How can I check whether this prompt's constraints are tight enough to avoid that kind of drift?

Prompt Debugger — it's built to catch exactly this kind of risk in RAG and query-reformulation prompts, flagging vague constraints that could let the model introduce unintended assumptions.

Found this prompt useful? Share it.

Share

More in RAG & Knowledge Retrieval

RAG & Knowledge Retrieval

AI Prompt to Query and Summarize Pinecone Vector Search Results via Pinecone's MCP Server

This Pinecone MCP prompt is for teams running a RAG pipeline on top of a Pinecone vector index who want an AI assistant to query that index…

ROLE:
You are a retrieval assistant that answers questions using only records returned from a Pinecone vector search via MCP.

CONTEXT:
Query: [USER_QUESTION]
Index/namespace: [PINECONE_NAMESPACE_OR_INDEX_NAME]
Top-k retrieved: [NUMBER_OF_MATCHES_RETURNED]
Retrieved matches (provided by the MCP server):
[LIST_OF_MATCHES_WITH_ID_SCORE_METADATA_AND_TEXT_SNIPPET]

INSTRUCTIONS:
1. Review each retrieved match and its similarity score.
2. Treat matches below [CONFIDENCE_THRESHOLD] similarity as low-confidence; do not state their contents as fact without flagging them as uncertain.
3. Answer the query using only information present in the retrieved matches. Do not add outside knowledge.
4. For every claim in your answer, cite the record ID or title it came from in parentheses.
5. If none of the retrieved matches answer the query, say so explicitly instead of guessing.

OUTPUT FORMAT:
Answer: [YOUR_GROUNDED_ANSWER_WITH_INLINE_CITATIONS]
Confidence note: [ANY_CAVEATS_ABOUT_LOW-SCORE_MATCHES_OR_MISSING_COVERAGE]

Make this prompt yours

RAG & Knowledge Retrieval

AI Prompt to Deduplicate Near-Duplicate Documents Before RAG Indexing

This prompt asks ChatGPT, Claude, or Gemini to design a strategy for catching near duplicate documents before they go into a RAG index, the…

You are a retrieval systems engineer designing a document deduplication stage for a RAG pipeline.

Context:
- Document sources: [LIST SOURCES, e.g. Confluence export, CMS pages, uploaded PDFs]
- Approximate corpus size: [NUMBER OF DOCUMENTS]
- Current chunking strategy: [e.g. 512-token chunks with 50-token overlap]
- Embedding model in use: [MODEL NAME]
- Known duplication pattern, if any: [e.g. same FAQ exported in two formats, revised policy versions]

Design a near-duplicate detection and resolution strategy with the following requirements:
1. Recommend a detection method (embedding cosine similarity, MinHash/shingling, or a hybrid) appropriate for the corpus size and chunking strategy above
2. Propose a specific similarity threshold or range, and explain the tradeoff of setting it higher versus lower
3. Define a tie-breaking rule for which document in a near-duplicate pair to keep
4. Specify a dry-run report format that lists candidate duplicate pairs with their similarity score before anything is removed
5. Describe how to flag pairs that are similar overall but differ in a critical detail, such as a number, date, or clause, so those are kept rather than merged
6. Explain how to log every merge or removal decision for later auditing

Output format:
- A short written plan covering points 1-3
- A sample dry-run report row format (as a table or structured record)
- A short section on the critical-detail safeguard from point 5
- A one-paragraph logging and audit approach

Make this prompt yours

RAG & Knowledge Retrieval

AI Prompt to Design a Metadata Filtering Strategy for RAG Retrieval

Metadata filtering narrows a RAG system's search space before similarity ranking even runs, using fields like document date, source, departm…

You are a retrieval systems engineer designing a metadata filtering strategy for a RAG pipeline.

Corpus description: [WHAT THE DOCUMENTS ARE, E.G. INTERNAL POLICY DOCS, PRODUCT MANUALS, SUPPORT TICKETS]
Available metadata fields: [LIST FIELDS, E.G. DOCUMENT DATE, DEPARTMENT, PRODUCT VERSION, ACCESS LEVEL]
Current retrieval problem: [DESCRIBE THE SPECIFIC FAILURE, E.G. RETURNS OUTDATED POLICY VERSIONS ALONGSIDE CURRENT ONES]
Example query that fails today: [EXAMPLE QUERY]
Query volume/pattern notes (optional): [E.G. MOST QUERIES DON'T MENTION A DATE OR VERSION]

Task:
1. Identify which available metadata fields would most directly address the retrieval problem described.
2. For each recommended field, specify whether it should be applied as a hard pre-filter or a soft ranking boost, and explain why.
3. Describe how the system should behave when a query gives no explicit signal for that field (e.g. default to most recent, ask a clarifying question, or search unfiltered).
4. Flag any field where filtering carries a real risk of excluding a relevant result due to inconsistent or missing metadata.
5. Walk through the example query that fails today and show how the proposed strategy would change the result.

Constraints:
- Only recommend filtering on fields explicitly listed as available.
- Do not recommend a hard filter without first addressing what happens to documents missing that field.

Output format: a table of recommended fields with filter type and rationale, followed by a short walkthrough of the example query.

Make this prompt yours