Sub topic 8
Rewriting and decomposing queries
This chapter assumes you have read the earlier chapters of this tutorial. You should be comfortable with Python and know what a search_docs tool looks like. You should also understand the agent loop that runs tool calls until the model gives a final answer. Here we focus on the argument the model passes to the search tool: the query.
Why the user's words make a poor query
Classic RAG embeds the user's message and searches with it. That works when the question is short, self-contained and about one thing. Three kinds of question break it:
- Follow-ups. "What about the pro plan?" has no subject once it leaves the conversation. The embedding of that sentence matches almost nothing useful.
- Conversational or vague phrasing. "Hey, I was wondering if there's any way to make it not time out so much" carries little of the vocabulary the documentation uses, such as "request timeout" or "retry".
- Multi-part questions. "Compare the free and pro plan limits and tell me how billing works" mixes several topics. One vector lands between them and retrieves chunks that match none well.
In agentic RAG the model writes the query argument itself. Query rewriting and decomposition are therefore things the model does when it calls the tool. They are not separate pipeline stages.
Rewriting: make the query stand alone
A rewritten query should be short and self-contained. It should use the words the documents are likely to use. The schema from the previous chapter already asks for this: "A short, self-contained search query. Do not rely on earlier messages for meaning." That sentence is a prompt, and the model reads it each time it decides what to pass in.
| User message | Weak query | Rewritten query |
|---|---|---|
| "What about the pro plan?" (after a question on project limits) | `what about the pro plan` | `pro plan project limit` |
| "It keeps timing out" | `it keeps timing out` | `request timeout configuration retry` |
| "Does v2 still support that?" | `does v2 still support that` | `API v2 webhook signature support` |
Rewriting has risks:
- Lost constraints. A rewrite can drop a version number, a product name or a date. Tell the model to keep every named entity and every number from the user's message.
- Invented vocabulary. The model may add terms the user never implied. Those terms pull in plausible but wrong chunks.
- Over-polishing. Natural-language questions often embed fine. Rewriting matters most when the raw message depends on context or uses different words from the documents.
Decomposing: split what cannot be answered at once
Decomposition breaks one question into several smaller searches. There are two shapes, and they need different handling.
Independent sub-questions. "Compare the free and pro plan limits" needs two searches that do not depend on each other. The model can request both in the same reply. Your loop already handles this: it runs every item in tool_calls and appends one tool message per call.
Dependent (multi-hop) sub-questions. "Which region hosts the service that sends our invoices?" first needs the name of the invoicing service. The second query can only be written once the first result is read. The model must search, observe, then search again. This is why a loop is needed and a one-time upfront query planner is not enough.
You can steer this behavior in the system prompt. For example: "If a question has several parts, search for each part separately. If one part depends on another, search for the first part before the second." Keep the instruction short. Long planning instructions raise cost, and the model rarely follows them better.
A search tool that supports multi-query behavior
Once the model issues several queries, the tool has to cope with overlap. Sub-queries often return the same chunk. The model may also repeat a query word for word. The tool below tracks both. It marks chunks the model has already seen so the model does not treat them as new evidence. It also refuses an exact repeat of an earlier query. The toy retriever at the bottom makes the example runnable.
def normalize(text):
return " ".join(text.lower().replace(".", "").split())
def make_search_tool(retriever, max_calls=6):
seen_queries = set()
seen_ids = set()
calls = 0
def search_docs(query, top_k=4):
nonlocal calls
top_k = max(1, min(int(top_k), 8))
key = normalize(query)
if key in seen_queries:
return {"note": "You already ran this query. Change the wording or answer now.", "results": []}
if calls >= max_calls:
return {"note": "Search budget used. Answer with what you have.", "results": []}
calls += 1
seen_queries.add(key)
results = []
for chunk in retriever(query, top_k):
results.append({
"id": chunk["id"],
"text": chunk["text"][:1200],
"already_seen": chunk["id"] in seen_ids,
})
seen_ids.add(chunk["id"])
return {"results": results}
return search_docs
DOCS = [
{"id": "limits-1", "text": "The free plan allows 3 projects."},
{"id": "limits-2", "text": "The pro plan allows 50 projects."},
{"id": "bill-1", "text": "Pro plan costs 20 dollars per month."},
]
def toy_retriever(query, k):
words = set(normalize(query).split())
scored = [(len(words & set(normalize(d["text"]).split())), d) for d in DOCS]
scored = [s for s in scored if s[0] > 0]
scored.sort(key=lambda s: -s[0])
return [d for _, d in scored[:k]]
search = make_search_tool(toy_retriever)
print(search("pro plan project limit"))
print(search("Pro plan project LIMIT")) # same query after normalizing
print(search("pro plan price")) # limits-2 comes back flagged already_seenReturning a note instead of raising an error matters. The note goes back to the model as a tool result, and the model can react to it. An exception would end the loop.
Edge cases and failure modes
- Over-decomposition. A model told to "break the question down" may split a simple question into five searches. Each one adds latency and tokens. Count tool calls per question when you evaluate, and look at the distribution.
- Query drift. In multi-hop work, each rewrite is based on the previous results. One bad first hop sends every later query in the wrong direction. A grading step, covered in a later chapter, is the usual defense.
- Near-duplicate queries. Wording changes such as "pro plan limit" and "limit of pro plan" slip past exact-match checks. Normalization catches case and spacing only. If repeats are costly, compare the results rather than the query strings. When two queries return the same top chunk ids, the second search added nothing.
- Merge order. If you merge results from several queries for display or citation, keep the chunk id and drop later duplicates. Do not average scores across queries. Scores from different queries are not comparable.
- Unanswerable parts. Decomposition can show that one part of a question has no evidence while the others do. The final answer should say which part is missing. It should not blend the parts into one confident reply.
When to rewrite and when to leave the query alone
Rewrite when the message depends on earlier turns, uses vocabulary far from the corpus, or mixes topics. Skip it when the question is already short, specific and self-contained. A rewrite that changes nothing still costs a model call if you run it as a separate step. When the model writes the tool argument directly, the extra cost is zero for simple questions. That is a strong reason to prefer the tool-argument approach over a fixed rewrite stage.
Exercise
A user asks, "Compare the free and pro plans, and say which region hosts the service that sends invoices." Which parts can be searched in parallel, which must wait for an earlier result, and what should the agent do if the invoicing search returns no passage that names the service?
Show answer
The free-plan and pro-plan lookups are independent, so the model can request both in one reply. The region lookup is dependent: it needs the name of the invoicing service, so it must wait for that result and run as a later step. If no passage names the service, the agent should not guess a region. It should try one differently worded query, such as billing or invoice service, and if that also fails, answer the plan comparison and state that the hosting region could not be found in the documentation.