Query Rewriting: Letting the Agent Improve Its Own Search Terms

A pattern where the model rewrites a bad query based on the first round of weak results.

How it works

Rather than treating the first search query as final, a query-rewriting loop evaluates whether the returned results actually look relevant (via the model's own judgment, or a simple heuristic like result count or snippet keyword overlap) and, if not, has the model generate a revised query — often broader, narrower, or using different terminology — before trying again, up to a small retry cap.

Example

First query AI search tool returns generic, unhelpful results. The agent, evaluating the snippets as too broad, rewrites to LLM function calling search API tool schema — a more specific reformulation informed by what the first round's weak results revealed was missing — and the second call returns materially more relevant hits.

Pitfalls

Related reading