Expand queries with QueryExpander
Use QueryExpander when retrieval results are missing relevant documents because the user's query shares little surface-level wording with your indexed content — expanding the query into 3–5 alternative phrasings improves recall without changing your retrieval pipeline.
Prerequisites
- An Anthropic API key, or the
ANTHROPIC_API_KEYenvironment variable set in your shell attune_raginstalled in your Python environment
Expand a query
-
Import
QueryExpanderfromattune_rag.expander:from attune_rag.expander import QueryExpander -
Instantiate the expander. The constructor accepts three optional parameters:
model— the Claude model to use (default:'claude-haiku-4-5')api_key— your Anthropic API key; omit this if the key is already set as an environment variablecache— set toFalseto disable response caching (default:True)
expander = QueryExpander()To supply an API key explicitly or swap the model:
expander = QueryExpander(model='claude-haiku-4-5', api_key='sk-...', cache=True) -
Call
expandwith the user's original query. The method returns a list of alternative phrasings:variants = expander.expand("how do I set up pre-commit hooks")If you are working in an async context, call
expand_asyncinstead:variants = await expander.expand_async("how do I set up pre-commit hooks") -
Pass the returned list to your retrieval pipeline. Each string in
variantsis a standalone query you can use to broaden your keyword or vector search. If the API call fails,QueryExpanderfalls back to the original query automatically — no error handling is required on your end.
Verify the expansion worked
Print variants and confirm it contains between 3 and 5 strings, each rephrasing the original intent:
print(variants)
# ['how do I set up pre-commit hooks',
# 'configure git pre-commit automation',
# 'install pre-commit framework hooks',
# 'pre-commit hook setup workflow']
If the list contains exactly one entry that matches your original query, the API call fell back gracefully — check that your API key is valid and that the claude-haiku-4-5 model is accessible on your account.