Home/
Part XIII — Expert Mode: Systems, Agents, and Automation/41. Advanced RAG (Beyond the Basics)/41.3 Query rewriting and expansion
41.3 Query rewriting and expansion
Overview and links for this section of the guide.
On this page
Query Rewriting
User queries are often vague. Rewrite them for better retrieval:
async function rewriteQuery(originalQuery: string): Promise {
const response = await model.generate(`
Rewrite this query into 3 search-optimized versions:
"${originalQuery}"
Output JSON: ["version1", "version2", "version3"]
`);
return JSON.parse(response);
}
// Example: "How do I fix the login bug?"
// → ["login authentication error troubleshooting",
// "login bug fix solution code",
// "user authentication failure resolution"]
Query Expansion
// Add synonyms and related terms
async function expandQuery(query: string): Promise {
const expansions = await model.generate(`
Given: "${query}"
Add synonyms and related terms.
Output: expanded query string
`);
return `${query} ${expansions}`;
}