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.
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
pgvectoron 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:
"BigOSlate Python course module count and prerequisites""BigOSlate SQL course module count and prerequisites"
- Run both searches in parallel (
asyncio.gather), deduplicate chunks bychunk_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 mslatency 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 Logs | Root Layer | Exact Fix |
|---|---|---|
Gold chunk wasn't in Top 50 at all (Low Context Recall) | 1. Indexing / Query Gap | Fix 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 Gap | Add 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 Bug | Shrink 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 Guard | Enforce 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
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" ]
5. Production SDK Code: Standalone Rewriter + Sub-Query Planner
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_parsed6. What Breaks in Production (War Stories)
- 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! UsingSearchPlanschema prevents that cleanly. - Unbounded Sub-Query Fan-Out (
12Sub-Queries): Letting an unconstrained planner emit 12 sub-queries multiplies embedding + database load 12×. Capsub_queriesstrictly at1–3(sub_queries[: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
Keep Exploring: Related Lessons & Tools
All Courses →Paste LeetCode-style level-order tree arrays, graph edge lists, or 2D matrices to render clean vector SVG diagrams and DFS traversals.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.