Advanced RAG: Query Rewriting, GraphRAG, Agentic Retrieval

Basic RAG answers "how do I restart checkout?" well. It struggles with what on-call actually asks: vague questions, two questions in one, and "what breaks if payments-db goes down?". Advanced RAG adds three layers to fix that. By the end you will rewrite and split queries, walk a dependency graph built from traces, and let a model choose its sources within a budget.
How advanced RAG fits together
This post builds on the retriever from RAG chunking, embeddings and hybrid search and reuses its retrieve(query, service, env) function. The architecture below shows where each new layer sits.
Transforms run before any search. The agent then picks sources, and each one returns evidence with an ID that the answer can cite. You need Python 3.10+, a Prometheus holding Tempo's service-graph metrics, and an Anthropic API key in ANTHROPIC_API_KEY. Install the libraries with pip install anthropic networkx requests.
Query rewriting, HyDE and multi-hop decomposition
Engineers type things like "chkout p99 bad after 14:00 deploy, payments or redis?". BM25 misses the abbreviation, and one embedding of two questions retrieves a blur of both. Three cheap calls to a small model fix the input first.
Rewriting expands abbreviations but keeps error codes exact. HyDE (Hypothetical Document Embeddings, from Gao et al.) embeds a fake runbook paragraph instead of the question, because a fake answer looks more like a runbook. Decomposition splits a multi-hop question, one needing facts from several documents, into standalone sub-questions. Save this as transforms.py:
import json
import anthropic
client = anthropic.Anthropic()
FAST = "claude-haiku-5-5" # small, fast model
def ask(prompt, max_tokens=300):
msg = client.messages.create(model=FAST, max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}])
return msg.content[0].text.strip()
def rewrite(q):
return ask("Rewrite as one precise runbook search query. Expand abbreviations; "
f"keep error codes and flags exactly. Reply with the query only.\n\n{q}")
def hyde(q): # embed this instead of q
return ask(f"Write the short runbook paragraph that answers: {q}", 200)
def decompose(q):
out = ask("Split into 1-4 standalone sub-questions. Reply with a JSON array "
f"of strings only.\n\n{q}")
try:
return json.loads(out)
except json.JSONDecodeError:
return [q] # a bad rewrite must never break retrieval
Open it with python -i transforms.py and call decompose() on the question above. Model output varies, but expect something like:
['What changed in the checkout deploy at 14:00?',
'Has payments latency risen since 14:00?',
'Has redis latency or error rate risen since 14:00?']
Retrieve each sub-question separately, sending rewrite(sub) to BM25 and hyde(sub) to the vector half. Every call adds latency, so run them in parallel and count them in your latency SLO. The usual failure is a rewrite that "corrects" an error code, so keep the original words in the BM25 query too.
GraphRAG over a service-dependency graph
No runbook says what breaks when payments-db fails: that depends on who calls it, and who calls them. GraphRAG retrieves by walking a graph. Microsoft's GraphRAG uses an LLM to extract one from documents (the project is now in maintenance mode). For services, skip extraction: your traces already hold the graph.
Edges point from caller to callee, so the blast radius is every service that can reach the failed node. Search, catalog and inventory never reach payments-db, so they stay out of the answer.
Grafana Tempo's service graphs export traces_service_graph_request_total with client and server labels, and databases appear as nodes too. Save this as graph.py:
import networkx as nx
import requests
PROM = "http://prometheus:9090/api/v1/query"
EDGES = "sum by (client, server) (rate(traces_service_graph_request_total[7d])) > 0"
def prom(query): # read-only instant query
r = requests.get(PROM, params={"query": query}, timeout=10)
return r.json()["data"]["result"]
def dependency_graph():
g = nx.DiGraph()
for row in prom(EDGES): # one row per caller -> callee
g.add_edge(row["metric"]["client"], row["metric"]["server"])
return g
def blast_radius(g, down, max_hops=4):
if down not in g: # no traffic seen for it
return []
# BFS over reversed edges: {service: hops}
hops = nx.single_source_shortest_path_length(g.reverse(), down, cutoff=max_hops)
return sorted((h, s) for s, h in hops.items() if s != down)
if __name__ == "__main__":
for h, svc in blast_radius(dependency_graph(), "payments-db"):
print(h, svc)
The [7d] window catches nightly jobs that a one-hour window would miss, and cutoff bounds the walk on deep graphs. For the graph above, python graph.py prints (illustrative):
1 payments
2 checkout
3 mobile-bff
3 web-frontend
4 api-gateway
For the RAG half, call retrieve() for each impacted service and give the model the hop list plus those chunks, so it explains impact with citations instead of guessing topology. If a caller shows up as user, it is uninstrumented: Tempo uses that name for unknown clients.
Agentic retrieval: the model decides when and where to search
In agentic retrieval the model, not your code, picks the retriever: each source becomes a tool, and the model calls one, reads the result and decides whether it needs more. That suits investigations, where each search depends on the last. It is the loop behind the Slack bot I built that investigates incidents with documentation search, metric plugins and log APIs.
The flowchart shows the guardrails, which matter more than the prompt. Every tool is read-only, and an exhausted step budget escalates to a human instead of producing a guess. Create agent.py and register three tools; search.py is the file from the hybrid search post:
import json
from transforms import client
from graph import prom, dependency_graph, blast_radius
from search import retrieve
def tool(name, desc, arg): # one required string argument
return {"name": name, "description": desc, "input_schema": {"type": "object",
"properties": {arg: {"type": "string"}}, "required": [arg]}}
TOOLS = [tool("search_docs", "Runbooks: procedures and known fixes.", "query"),
tool("blast_radius", "Services impacted if this one fails.", "service"),
tool("query_metrics", "Read-only PromQL instant query.", "promql")]
HANDLERS = {"search_docs": lambda query: retrieve(query, "checkout", "prod"),
"blast_radius": lambda service: blast_radius(dependency_graph(), service),
"query_metrics": lambda promql: prom(promql)}
The model sees only each tool's name, description and schema, so the description is your routing logic: say what the source is good for. Add search_tickets or search_code the same way, one read-only function each. Now the loop:
def investigate(question, max_steps=6):
messages = [{"role": "user", "content": question}]
for step in range(max_steps): # hard step budget
resp = client.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
system="Use tools for every claim and cite them.", tools=TOOLS, messages=messages)
print(step, resp.stop_reason, resp.usage.input_tokens, resp.usage.output_tokens)
if resp.stop_reason != "tool_use":
return "".join(b.text for b in resp.content if b.type == "text")
messages.append({"role": "assistant", "content": resp.content})
messages.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": b.id,
"content": json.dumps(HANDLERS[b.name](**b.input), default=str)[:4000]}
for b in resp.content if b.type == "tool_use"]})
return "Step budget exhausted: escalate to the on-call engineer."
When the model wants data, stop_reason is tool_use; you run every requested tool and return each result under its tool_use_id. The print line is your cost log (illustrative):
0 tool_use 1184 96
1 tool_use 2410 141
2 end_turn 4302 388
Input tokens grow every step because the whole conversation is resent, which is why results are cut to 4,000 characters. Check the answer against log, metric and trace correlation before anyone acts on it.
When advanced RAG is worth the complexity
Every layer adds latency, tokens and failure modes, so add one only when your eval set (like the recall@4 set from the hybrid search post) shows a category of questions failing.
| Technique | Worth it when | Skip it when | Extra cost |
|---|---|---|---|
| Query rewriting | Vague or slang-heavy questions | Questions come from alerts | 1 small call |
| HyDE | Low vector recall | Queries are error codes | 1 call, 1 embedding |
| Decomposition | Questions span services | Single-document lookups | 1 call, N retrievals |
| GraphRAG | Impact or "who calls X?" | A handful of services | 1 PromQL query |
| Agentic retrieval | Open-ended investigations | Sub-second latency SLOs | 2-6 large-model calls |
A small system gains little from a graph; microservices vs monoliths covers when dependency counts start to matter.
Common pitfalls
- Stale graphs. Rebuild per question; a deploy can add an edge.
- Unbounded loops. Cap steps, truncate tool results and track tokens per investigation.
- Write-capable tools. Retrieval only reads. Restarts belong in reviewed automation, as in auto-remediation with guardrails.
- Unversioned prompts. Version prompts and model IDs together; re-run evals when either changes.
Key takeaways
- Fix the question first: rewriting, HyDE and decomposition are cheap small-model calls.
- For impact questions, walk the dependency graph your traces already contain.
- Give the agent read-only tools and a hard step budget.
- Add each layer only when evals show a category of questions failing.
Related articles

Claude Code Multi-Model Setup: Opus, Sonnet and Fable
Stop spending Opus tokens on routine work. Run Opus 5.5 as the planner, Sonnet 5.5 subagents on medium effort and Fable 5.2 as an advisor: the four files to edit, the exact keys, and what silently turns the advisor off.

Rolling Out a JDK Upgrade to 2,000+ Jenkins Agents
A JDK upgrade reached most of a client's 2,000+ Jenkins agents in half an hour and broke builds with a misleading error. How the client's rollouts work, how Claude Code found the deleted JDK, and how they roll out now.

Kubernetes Auto-Remediation: Self-Healing with Guardrails
Wire Alertmanager to a remediation worker that grows full PVCs, rolls back stuck rollouts and evicts leaky pods, guarded by a kill switch, blast-radius and rate limits, and a circuit breaker. Then measure auto-closed alerts and MTTR.