Sub topic 3
Rewriting and Expanding Queries
Assume you know basic Python, prompting, vectors, dot products, APIs, and JSON. This chapter focuses on improving retrieval before the language model writes an answer.
Rewriting and Expanding Queries
A user query may be short, ambiguous, or depend on earlier conversation. Rewrite it into a self-contained search query. Query expansion creates several related queries so retrieval can match different terms.
def expand_query(question):
return [
question,
question.replace("RAG", "retrieval augmented generation"),
f"technical explanation: {question}",
]
for query in expand_query("How does RAG reduce hallucinations?"):
print(query)Retrieve passages for every query, remove duplicate documents, and combine their rankings. Preserve important filters such as dates, product names, and user permissions. A rewrite that changes the meaning can reduce retrieval quality.
Building the Augmented Prompt
An augmented prompt combines the user question with retrieved context. Number each passage so the model can cite its evidence. Tell the model to use only that context and to acknowledge missing information.
def build_prompt(question, passages):
context = "\n\n".join(
f"[{i}] {passage}" for i, passage in enumerate(passages, start=1)
)
return (
"Answer using only the context below. Cite passages like [1]. "
"If the context is insufficient, say you don't know.\n\n"
f"Context:\n{context}\n\n"
f"Question: {question}\nAnswer:"
)Generating Grounded Answers with Citations
Grounding means connecting each claim to retrieved evidence. Citations improve inspection, but they do not prove that the answer is correct. The application should validate that cited passage identifiers exist and should avoid passing unauthorized passages to the model.
Evaluating a RAG System
Measure retrieval and generation separately. Recall at k is the fraction of known relevant documents found in the first k results. Also test answer correctness, citation correctness, completeness, and refusal when evidence is missing.
def recall_at_k(retrieved_ids, relevant_ids, k):
relevant = set(relevant_ids)
if not relevant:
return 0.0
return len(set(retrieved_ids[:k]) & relevant) / len(relevant)Diagnosing Common Failures
| Symptom | Likely cause | Useful check |
|---|---|---|
| Relevant text is absent | Bad rewrite or chunking | Inspect top-k passages |
| Correct passage is present, answer is wrong | Prompt or generation failure | Test with context only |
| Citations do not support claims | Unsupported generation | Compare claims with cited text |
Running RAG in Production
Track index freshness, access-control filtering, latency, token usage, and search cost. Re-embed changed documents, version indexes, and log query, retrieved IDs, latency, and evaluation results without storing sensitive text unnecessarily.
Exercise
Retrieval returns the right passage, but the answer invents an uncited policy detail. What should you inspect first?
Show answer
Inspect the augmented prompt and generation instructions, then test whether the model follows a context-only rule and admits missing information.