Course
AI · Module 05: Production RAG SystemsTutorial 15 of 21
AI Course·~1.5 hrs

5.3 Query Rewriting, Multi-Query RAG & Debugging Retrieval

Fix the #1 killer of multi-turn chat RAG ('What about on Linux?'): master conversational query rewriting, multi-hop sub-query fan-out, HyDE, and a systematic 4-metric playbook to debug any RAG failure.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. The Multi-Turn RAG Killer: "What About on Windows?"

Watch how 90% of naive RAG chatbots break on Turn 2 of a completely normal conversation:

  • Turn 1 User: "How do I install pgvector on macOS?" → Retrieves macOS Homebrew docs → Great answer!
  • Turn 2 User: "What about on Windows?"
  • Naive Bug: Your backend embeds the raw string "What about on Windows?"! Because "pgvector" isn't in Turn 2's text, vector search returns generic Windows 11 wallpaper & WSL docs — 0% relevance!

Fix #1: Conversational Query Contextualization (Standalone Rewriter)

Whenever len(chat_history) > 0, run a fast 150 ms Flash/Mini call (temperature=0) to rewrite the latest user message into a self-contained, pronoun-free search query before hitting Hybrid Search:

  • Raw Turn 2: "What about on Windows?"
  • Rewritten Search Query: "How to install PostgreSQL pgvector extension on Windows" → 100% Retrieval Hit!

2. Query Decomposition & HyDE (Solving Multi-Hop & Vocabulary Gaps)

Fix #2: Multi-Query Fan-Out for Comparison Questions

Suppose a user asks: "Compare BigOSlate's Python course vs SQL course module counts and prerequisites." No single 300-token chunk contains both courses! If top_k=5 happens to pull 5 Python chunks and 0 SQL chunks, half the comparison fails!

  • Solution: Have a fast query planner decompose comparative/multi-hop questions into 2–3 parallel sub-queries:
    1. "BigOSlate Python course module count and prerequisites"
    2. "BigOSlate SQL course module count and prerequisites"
  • Run both searches in parallel (asyncio.gather), deduplicate chunks by chunk_id, rerank, and synthesize!

Fix #3: HyDE (Hypothetical Document Embeddings) — Use Sparingly!

When users type ultra-vague 3-word symptoms ("app feels sluggish"), query-to-document similarity can lag because user phrasing looks nothing like engineering runbooks. HyDE asks a fast LLM to draft a short hypothetical technical paragraph first, then embeds that paragraph to find real runbooks with matching technical vocabulary.

  • Tradeoff: Adds +250 ms latency and risks steering toward a wrong hypothesis if the domain is proprietary — prefer Query Expansion (generating 2–3 keyword/semantic search variants) in latency-sensitive apps!

3. The Senior Engineer's RAG Debugging Playbook (Never Guess!)

When a stakeholder reports "The RAG bot gave a bad answer on Question #42", never blindly tweak chunk sizes, prompts, and models all at once! Isolate whether the bug happened in Retrieval or Generation using the 4-Quadrant RAG Triad:

Symptom Observed in Trace LogsRoot LayerExact Fix
Gold chunk wasn't in Top 50 at all (Low Context Recall)1. Indexing / Query GapFix broken PDF/table chunking, add [Doc > H1 > H2] breadcrumbs, enable Query Rewriting + Hybrid BM25
Gold chunk was #18 in RRF, missed Top 5 (Low Context Precision)2. Ranking GapAdd a Cross-Encoder Reranker (rerank-v3.5 / voyage-rerank-2) + metadata date boost
Gold chunk WAS #1 in prompt, yet LLM answered wrong! (Low Faithfulness)3. Synthesis / Prompt BugShrink noisy top_k (30 → 6), move instructions + top chunk to Recency Zone, lower T=0.0
Answer was right, but leaked a nuance from outside docs (Hallucination)4. Abstention GuardEnforce strict "ONLY use <sources>; reply INSUFFICIENT_CONTEXT if missing" + span-quote verification

Golden Rule of RAG Engineering: Log {raw_query, rewritten_queries, retrieved_chunk_ids, rerank_scores, final_answer} on every single production request! Looking at 20 real failed retrieval traces for 30 minutes teaches you more than 3 weeks of guessing.


4. Wire-Level Trace: Multi-Turn Rewrite + Parallel Fan-Out Retrieval

Tracing Conversational Rewrite & Parallel Sub-Query Retrieval
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Ambiguous Pronoun ('that') Resolved Into Standalone Question)
Wire Telemetry:in=160 tokout=38 toklatency=170mscost=$0.00003
1→# History: Turn 1 asked about HNSW index build memory
2→user_msg = "And how does that compare to IVFFlat at query time?"
3→plan = rewrite_and_decompose(history, user_msg) # 170ms Flash call
4# Parallel Hybrid Search across decomposed sub-queries!
5chunks = await asyncio.gather(*[hybrid_search(sq, k=10) for sq in plan.queries])
6top_6 = rerank_deduplicated(plan.standalone_question, flatten(chunks), top_n=6)
Structured Query Plan Output2 SUB-QUERIES
standalone: "How does HNSW compare to IVFFlat at query time in pgvector?"
queries: [
  "pgvector HNSW query latency recall ef_search",
  "pgvector IVFFlat query latency recall probes"
]
What's Happening: 'that' is resolved to 'HNSW in pgvector', and the comparison splits cleanly into one HNSW query and one IVFFlat query!

5. Production SDK Code: Standalone Rewriter + Sub-Query Planner

SDK:
import asyncio
from openai import AsyncOpenAI
from pydantic import BaseModel, Field

client = AsyncOpenAI()

class SearchPlan(BaseModel):
  standalone_question: str = Field(description="Self-contained question with all pronouns resolved")
  sub_queries: list[str] = Field(description="1 to 3 focused search queries covering all entities")

async def build_search_plan(history: list[dict], latest_user_msg: str) -> SearchPlan:
  if not history:
      # Fast path on Turn 1 if single-entity question, or decompose comparisons!
      pass
  convo = "\n".join(f"{m['role']}: {m['content']}" for m in history[-4:])
  resp = await client.responses.parse(
      model="gpt-4o-mini",
      temperature=0.0,
      instructions=(
          "Rewrite the user's latest message into a self-contained question resolving all pronouns "
          "from conversation history, and emit 1–3 concise search queries (max 3)."
      ),
      input=f"<history>\n{convo}\n</history>\nLatest message: {latest_user_msg}",
      text_format=SearchPlan,
  )
  return resp.output_parsed

6. What Breaks in Production (War Stories)

  1. The Rewriter Answering the Question Instead of Rewriting It! Without Strict Structured Outputs (SearchPlan) or a hard "Do NOT answer the question" instruction, small models love answering "How do I reset 2FA?" with a 200-word hallucinated tutorial inside the search query string! Using SearchPlan schema prevents that cleanly.
  2. Unbounded Sub-Query Fan-Out (12 Sub-Queries): Letting an unconstrained planner emit 12 sub-queries multiplies embedding + database load 12×. Cap sub_queries strictly at 1–3 (sub_queries[:3]).
  3. Asking RAG to Aggregate Counting / Math Questions ("How many open P0 bugs did we have in October?"): Top-5 vector search can never count 437 rows in a table! Route aggregation/counting questions to a read-only SQL / Analytics Tool (Module 06 — Agents & Tool Calling!), and reserve RAG for unstructured document retrieval!

Module 5.3 Mastery Check — Query Rewriting & Debugging RAG

Q1.Why do multi-turn RAG chatbots fail on follow-up questions like `'Does it support SSO?'` when you embed the user's raw message directly?
Q2.A user asks `'Compare Redis Sentinel vs Redis Cluster failover.'` Why does decomposing this into 2 parallel sub-queries beat a single Top-5 search?
Q3.Your trace logs show the exact answer-bearing paragraph WAS ranked `#1` inside `<sources>`, yet the LLM still gave an inaccurate answer. Where is the bug?
Q4.A user asks your assistant: `'What was our average order value across all 84,000 orders last month?'` Why is vector RAG the WRONG tool for this query?

Keep Exploring: Related Lessons & Tools

All Courses →