Query rewriter
Users ask vague or ambiguous questions. The query rewriter analyzes intent, expands keywords, generates alternative phrasings, and structures queries for better retrieval, dramatically improving RAG accuracy.
Query rewriting pipeline
A user asks "why is my app slow?" The rewriter expands it to "application performance bottleneck diagnosis, latency troubleshooting, slow response time causes." These alternative phrasings match more relevant documents in the knowledge base.
class QueryRewriter:
def __init__(self):
self.llm = get_llm()
def analyze_query(self, query):
prompt = f"""Analyze this query:
Query: {query}
Determine: intent, complexity, domain, clarity, keywords"""
return self.llm.generate(prompt).content
def expand_query(self, query):
prompt = f"""Generate 3+ alternative phrasings for better retrieval:
Original: {query}
Include synonyms, related terms, and different perspectives."""
return self.llm.generate(prompt).content
def optimize_for_retrieval(self, query):
prompt = f"""Optimize this query for document retrieval:
Original: {query}
Add technical terms, structure the query, remove ambiguity."""
return self.llm.generate(prompt).content
def rewrite(self, query):
analysis = self.analyze_query(query)
expanded = self.expand_query(query)
optimized = self.optimize_for_retrieval(query)
return {"original": query, "optimized": optimized,
"alternatives": expanded}QueryRewriter analyzes, expands, and optimizes queries.
Quiz: Quiz
Loading practice…
Matching exercise: Match query rewriting techniques
Loading practice…
Flashcards: Flashcards
Loading practice…
Better queries lead to better retrieval. Next, we add a relevancy check to filter out documents that are not useful.