Lab: Decomposing Multi-Hop Questions
Turn multi-hop questions into a validated plan of tool steps with explicit dependencies, run independent steps together, carry values found in one step into the arguments of the next, rewrite a failed step once, and abstain with what is known when a hop cannot be resolved.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Write the plan and check it
- Step 2: Run the waves and carry values forward
- Step 3: Run five questions
- Step 4: Prove the answers come from the data
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Agentic RAG
- When Single-Pass RAG Is Not Enough Concept · 15 min
- Retrieval Tools: Index, SQL and Web Search Worked example · 20 min
- Lab: Decomposing Multi-Hop Questions Lab · 25 min
- Grading Evidence and Retrying Lab · 25 min
- Single-Pass Versus Agentic: A Measured Comparison Worked example · 20 min
- Check: Design an Agentic Retriever Knowledge check · 8 questions
What you will learn
- Implement query decomposition and rewriting for multi-hop questions.
Prerequisites: RAG Foundations, Agent Loops & ReAct
01. Goal and setup
In lesson 1 a question was multi-hop when one lookup needs the result of another. HotpotQA, a widely used multi-hop benchmark, names the two common shapes. In a bridge question an entity found in the first hop (the bridge) is needed to ask the second: where is the lead of the team that owns nightly-report based? In a comparison question two independent lookups are made and then combined: how many failed runs did billing-sync and nightly-report each have?
Query decomposition turns such a question into steps. Query rewriting appears in three places around it:
- before planning, a follow-up such as and where is she based? becomes a standalone question (you built this in the RAG Foundations rewriting lab);
- while running, each dependent query is rewritten with the values found so far, so the lead of {s1.owner} becomes the lead of Payments;
- after a failure, a sub-query that found nothing is rewritten once, for example by correcting a misspelt name, and run again.
In this lab you build the second and third kinds of rewriting, together with a plan format and its validator, an executor that runs steps in dependency order, and a stopping rule that abstains instead of guessing. The planner is a FAKE function with fixed patterns, so the runs are reproducible; a real planner is a model call that returns the same JSON, and the validator treats both the same.
You need: the agentic-lab folder from lesson 2, with ops.db and docs.json built by make_fixture.py. Python 3.12 or later, no libraries.
agentic-lab/
├── planner.py step 1: plan format, FAKE planner, validator
├── decompose.py step 2: executor, rewrite, abstain, synthesis
└── break_fixture.py step 4: change the data on purpose02. Step 1: Write the plan and check it
A plan is a list of steps. Each step names a tool from lesson 2 and its arguments, lists the steps it depends_on, and says which values to extract from the result. A dependent step refers to an earlier value with a slot such as {s1.owner}. The plan also carries an answer template with slots, which the final step fills from the evidence.
validate_plan() runs before any tool does. It rejects duplicate step ids, unknown tools and a slot that points at a step not listed in depends_on, because such a step would run too early with the slot text as its argument. It then orders the steps with Kahn's algorithm, one layer at a time: each layer, or wave, holds the steps whose dependencies are all done, and a plan that leaves steps over has a cycle. A plan written by a model is untrusted output, exactly like a tool argument, so it gets the same treatment.
"""Turn a question into a plan of tool steps, then check the plan before running it."""
import re
from search import terms
from tools import TOOLS
MONTHS = {m: f"{i:02d}" for i, m in enumerate(
"january february march april may june july august september october"
" november december".split(), start=1)}
SLOT = re.compile(r"\{(s\d+)\.(\w+)\}") # {s1.owner}: a value from step s1
def fake_plan(question: str) -> dict:
"""FAKE, NOT A LANGUAGE MODEL: six question shapes written as patterns.
A real planner is a model call that returns this same JSON."""
q = question.lower().rstrip("?")
if m := re.search(r"lead of the team that owns ([\w-]+)", q):
return {"steps": [
{"id": "s1", "tool": "search_docs", "args": {"query": f"{m[1]} owner"},
"check": [m[1]], "extract": ["job", "owner"], "depends_on": []},
{"id": "s2", "tool": "team_lead", "args": {"team": "{s1.owner}"},
"extract": ["name", "office"], "depends_on": ["s1"]}],
"answer": "{s2.name} leads the {s1.owner} team, which owns {s1.job},"
" and works in {s2.office}."}
if m := re.search(r"did ([\w-]+) and ([\w-]+) each have in (\w+) (\d{4})", q):
month = f"{m[4]}-{MONTHS[m[3]]}"
return {"steps": [
{"id": f"s{i}", "tool": "failed_runs", "extract": ["failed"],
"args": {"job": job, "month": month}, "depends_on": []}
for i, job in ((1, m[1]), (2, m[2]))],
"answer": f"In {month}, {m[1]} had {{s1.failed}} failed runs and {m[2]}"
" had {s2.failed}."}
if m := re.search(r"did the job that (.+) fail in (\w+) (\d{4})", q):
month = f"{m[3]}-{MONTHS[m[2]]}"
return {"steps": [
{"id": "s1", "tool": "search_docs", "args": {"query": m[1]},
"check": terms(m[1]), "extract": ["job"], "depends_on": []},
{"id": "s2", "tool": "failed_runs",
"args": {"job": "{s1.job}", "month": month},
"extract": ["failed"], "depends_on": ["s1"]}],
"answer": f"{{s1.job}} had {{s2.failed}} failed runs in {month}."}
if m := re.search(r"how many ([\w-]+) runs failed in (\w+) (\d{4})", q):
month = f"{m[3]}-{MONTHS[m[2]]}"
return {"steps": [{"id": "s1", "tool": "failed_runs", "extract": ["failed"],
"args": {"job": m[1], "month": month}, "depends_on": []}],
"answer": f"{m[1]} had {{s1.failed}} failed runs in {month}."}
if m := re.search(r"who leads the (\w+) team", q):
team = m[1].capitalize()
return {"steps": [{"id": "s1", "tool": "team_lead", "args": {"team": team},
"extract": ["name"], "depends_on": []}],
"answer": f"{{s1.name}} leads the {team} team."}
if m := re.search(r"which office is (\w+ \w+) in", q):
name = m[1].title().replace("'", "''") # a model writing SQL must escape too
sql = f"SELECT office FROM people WHERE name = '{name}'"
return {"steps": [{"id": "s1", "tool": "query_db", "args": {"sql": sql},
"extract": ["office"], "depends_on": []}],
"answer": f"{m[1].title()} works in {{s1.office}}."}
raise ValueError("no plan for this question")
def validate_plan(plan: dict) -> list[list[str]]:
"""Reject a malformed plan; return the steps grouped into waves."""
steps = {s["id"]: s for s in plan["steps"]}
if len(steps) != len(plan["steps"]):
raise ValueError("duplicate step ids")
for s in steps.values():
if s["tool"] not in TOOLS:
raise ValueError(f"{s['id']}: unknown tool {s['tool']}")
used = {m[0] for v in s["args"].values() for m in SLOT.findall(str(v))}
if not used <= set(s["depends_on"]) <= set(steps) - {s["id"]}:
raise ValueError(f"{s['id']}: slots and depends_on do not match")
waves, done = [], set()
while len(done) < len(steps): # Kahn's algorithm, one layer at a time
ready = [i for i, s in steps.items()
if i not in done and set(s["depends_on"]) <= done]
if not ready:
raise ValueError("the steps depend on each other in a cycle")
waves.append(ready)
done.update(ready)
return waves
if __name__ == "__main__": # self-check: one valid plan, one broken on purpose
plan = fake_plan("Where is the lead of the team that owns nightly-report based?")
print("waves:", validate_plan(plan))
plan["steps"][0]["depends_on"] = ["s2"] # s1 now waits for s2, which waits for s1
try:
validate_plan(plan)
except ValueError as exc:
print("rejected:", exc)Run the file on its own. Its self-check validates one plan, then makes s1 and s2 wait for each other and confirms that the validator refuses the cycle.
python planner.pywaves: [['s1'], ['s2']]
rejected: the steps depend on each other in a cycleLook at what each pattern produces. The bridge question has two steps in two waves. The comparison question has two steps with no dependencies, so they form one wave. The third shape bridges through a description: the first step finds which job copies card payments into the ledger, the second counts that job's failures.
Values from earlier steps go into tool arguments, never into SQL text. team_lead is a template with a ? placeholder, so a team name taken from a passage cannot change the query. Only the last pattern writes SQL, from the question, and that SQL runs behind the guard from lesson 2.
03. Step 2: Run the waves and carry values forward
decompose.py runs a plan wave by wave. Within a wave, asyncio.gather starts every step at once, and asyncio.to_thread moves each blocking tool call onto a worker thread, so slow tools overlap in time. Each step:
- fills its slots from the values of finished steps;
- calls the tool through
fetch()from lesson 2, so argument checks, scope and caching still apply; - extracts the values it needs. Rows give values by column name. For passages,
checklists words that the passage must contain, so a bridge value comes only from a passage about the right entity; - if nothing usable came back, asks
fake_rewrite()for one new query and tries once more; if that fails too, the step fails.
When a step fails, the run stops and abstains. It names the failed step and reports what it did find, with sources, so the reader sees how far it got. When every step succeeds, the answer template is filled and the sources are cited. Each step also counts its calls: one tool call and one model call to read the result per attempt, plus one for a rewrite. The run adds the planning and answer calls and reports how many calls had to happen one after another.
"""Run a plan: independent steps together, dependent steps with earlier values."""
import asyncio
import difflib
import json
import re
import sys
import textwrap
from planner import SLOT, fake_plan, validate_plan
from tools import DOCS, fetch
SCOPE = "acme:staff" # from the session
JOBS = [d["id"].split("#")[1] for d in DOCS.docs if d["id"].startswith("handbook#")]
def say(text: str) -> None:
for line in text.splitlines():
print(textwrap.fill(line, 86, subsequent_indent=" "))
FIELDS = {"job": r"^([a-z]+(?:-[a-z]+)+) ", "owner": r"Owner: (\w+) team"}
def extract(step: dict, payload: dict) -> dict | None:
"""FAKE extractor: a model would read the result and quote the values."""
if payload.get("rows"):
row = dict(zip(payload["columns"], payload["rows"][0]))
if all(row.get(f) is not None for f in step["extract"]):
return {"values": {f: row[f] for f in step["extract"]},
"source": step["tool"]}
for hit in payload.get("hits", []):
if all(word in hit["text"].lower() for word in step.get("check", [])):
found = {f: re.search(FIELDS[f], hit["text"]) for f in step["extract"]}
if all(found.values()):
return {"values": {f: m[1] for f, m in found.items()},
"source": hit["id"]}
return None
def fake_rewrite(step: dict) -> dict | None:
"""FAKE rewriter: link a misspelt job name to a known one, as a model would."""
def link(word: str) -> str:
return (difflib.get_close_matches(word, JOBS, n=1, cutoff=0.8) or [word])[0]
if step["tool"] != "search_docs":
return None
query = " ".join(link(w) for w in step["args"]["query"].split())
if query == step["args"]["query"]:
return None # nothing to rewrite: give up on this step
return {**step, "args": {"query": query},
"check": [link(w) for w in step.get("check", [])]}
async def run_step(step: dict, done: dict) -> tuple[dict | None, list[str], int]:
"""Run one step; return its evidence (or None), log lines and calls made."""
def fill(value):
return SLOT.sub(lambda m: str(done[m[1]]["values"][m[2]]), value) \
if isinstance(value, str) else value
step = {**step, "args": {k: fill(v) for k, v in step["args"].items()}}
log, calls = [], 0
for attempt in (1, 2): # the first try, then at most one rewrite
args = json.dumps(step["args"])
payload = await asyncio.to_thread(fetch, step["tool"], step["args"], SCOPE)
calls += 2 # the tool call, then a model call that extracts the values
if found := extract(step, payload):
log.append(f" {step['id']} {step['tool']} {args} -> {found['values']}")
return found, log, calls
log.append(f" {step['id']} {step['tool']} {args} -> no usable evidence")
if attempt == 2 or not (step := fake_rewrite(step)):
return None, log, calls
calls += 1 # the rewrite is a model call too
async def answer(question: str, log=say) -> dict:
plan = fake_plan(question)
waves = validate_plan(plan)
steps = {s["id"]: s for s in plan["steps"]}
log(f"Q: {question}\nwaves: {waves}")
done: dict[str, dict] = {}
calls = serial = 1 # the planning call
for wave in waves:
outcomes = await asyncio.gather(*(run_step(steps[i], done) for i in wave))
calls += sum(n for _, _, n in outcomes)
serial += max(n for _, _, n in outcomes) # a wave waits for its slowest step
for step_id, (found, lines, _) in zip(wave, outcomes):
log("\n".join(lines))
if found is None:
known = "; ".join(f"{k}: {v['values']} [{v['source']}]"
for k, v in done.items()) or "nothing"
return {"answer": f"ABSTAIN: step {step_id} found no evidence."
f" Known: {known}", "calls": calls, "serial": serial}
done[step_id] = found
text = SLOT.sub(lambda m: str(done[m[1]]["values"][m[2]]), plan["answer"])
sources = dict.fromkeys(v["source"] for v in done.values()) # unique, in order
text += " " + " ".join(f"[{source}]" for source in sources)
return {"answer": text, "calls": calls + 1, "serial": serial + 1} # + synthesis
QUESTIONS = [
"Where is the lead of the team that owns nightly-report based?",
"How many failed runs did billing-sync and nightly-report each have in October"
" 2026?",
"How many times did the job that copies card payments into the ledger fail in"
" October 2026?",
"Where is the lead of the team that owns billingsync based?",
"Where is the lead of the team that owns support-digest based?",
]
if __name__ == "__main__":
for q in sys.argv[1:] or QUESTIONS:
result = asyncio.run(answer(q))
say(f"{result['answer']}\n calls: {result['calls']}, in sequence:"
f" {result['serial']}")
print()Two functions are fakes. extract() uses two regular expressions where a model would read the result and quote the values. fake_rewrite() uses difflib to link a misspelt job name to a known one, where a model would rewrite the query; a real system often does the same linking against a catalogue of names, which is cheaper and easier to test than a model call.
Check the executor on a one-step question before the full run:
python decompose.py "Who leads the Platform team?"Q: Who leads the Platform team?
waves: [['s1']]
s1 team_lead {"team": "Platform"} -> {'name': 'Ana Lima'}
Ana Lima leads the Platform team. [team_lead]
calls: 4, in sequence: 404. Step 3: Run five questions
python decompose.pyQ: Where is the lead of the team that owns nightly-report based?
waves: [['s1'], ['s2']]
s1 search_docs {"query": "nightly-report owner"} -> {'job': 'nightly-report',
'owner': 'Analytics'}
s2 team_lead {"team": "Analytics"} -> {'name': 'Chen Wei', 'office': 'Singapore'}
Chen Wei leads the Analytics team, which owns nightly-report, and works in Singapore.
[handbook#nightly-report] [team_lead]
calls: 6, in sequence: 6
Q: How many failed runs did billing-sync and nightly-report each have in October 2026?
waves: [['s1', 's2']]
s1 failed_runs {"job": "billing-sync", "month": "2026-10"} -> {'failed': 3}
s2 failed_runs {"job": "nightly-report", "month": "2026-10"} -> {'failed': 1}
In 2026-10, billing-sync had 3 failed runs and nightly-report had 1. [failed_runs]
calls: 6, in sequence: 4
Q: How many times did the job that copies card payments into the ledger fail in
October 2026?
waves: [['s1'], ['s2']]
s1 search_docs {"query": "copies card payments into the ledger"} -> {'job':
'billing-sync'}
s2 failed_runs {"job": "billing-sync", "month": "2026-10"} -> {'failed': 3}
billing-sync had 3 failed runs in 2026-10. [handbook#billing-sync] [failed_runs]
calls: 6, in sequence: 6
Q: Where is the lead of the team that owns billingsync based?
waves: [['s1'], ['s2']]
s1 search_docs {"query": "billingsync owner"} -> no usable evidence
s1 search_docs {"query": "billing-sync owner"} -> {'job': 'billing-sync', 'owner':
'Payments'}
s2 team_lead {"team": "Payments"} -> {'name': 'Ben Okafor', 'office': 'Manchester'}
Ben Okafor leads the Payments team, which owns billing-sync, and works in Manchester.
[handbook#billing-sync] [team_lead]
calls: 9, in sequence: 9
Q: Where is the lead of the team that owns support-digest based?
waves: [['s1'], ['s2']]
s1 search_docs {"query": "support-digest owner"} -> {'job': 'support-digest',
'owner': 'Support'}
s2 team_lead {"team": "Support"} -> no usable evidence
ABSTAIN: step s2 found no evidence. Known: s1: {'job': 'support-digest', 'owner':
'Support'} [handbook#support-digest]
calls: 5, in sequence: 5Read the five runs:
- Bridge. Step s1 finds that the Analytics team owns nightly-report; s2 asks for that team's lead, Chen Wei in Singapore. Six calls, all in sequence, because s2 had to wait for s1.
- Comparison. Both counts run in one wave. Six calls in total, but only four had to wait for each other: the planning call, the parallel wave (a tool call and a model call) and the answer.
- Bridge through a description. Search finds the job from what it does, then the template counts its failures.
- Rewrite. billingsync is in no passage, so the first attempt finds no evidence. Without the
check, every handbook passage contains Owner: and the top hit could have supplied the wrong team. The rewrite links the name to billing-sync, the second attempt succeeds and the run continues. Three extra calls. - Abstain. The Support team has no lead on record, so s2 returns no rows and has nothing to rewrite. The run stops, says which hop failed and reports the owner it did find, instead of inventing a lead.
05. Step 4: Prove the answers come from the data
If an answer stays the same when the data changes, it probably did not come from the data. break_fixture.py changes the fixture on purpose. First move Ben Okafor to another office and ask about billing-sync; then remove the handbook passage that is the bridge for the same question.
"""Change the fixture on purpose: the answers must change with it."""
import json
import sqlite3
import sys
from pathlib import Path
if sys.argv[1] == "office": # Ben Okafor moves office
with sqlite3.connect("ops.db") as db:
db.execute("UPDATE people SET office = 'Leeds' WHERE name = 'Ben Okafor'")
print("Ben Okafor now works in Leeds")
else: # remove one passage from the index, e.g. handbook#billing-sync
path = Path("docs.json")
docs = json.loads(path.read_text())
path.write_text(json.dumps([d for d in docs if d["id"] != sys.argv[1]]))
print(f"{len(docs) - 1} passages left")python break_fixture.py office
python decompose.py "Where is the lead of the team that owns billing-sync based?"Ben Okafor now works in Leeds
Q: Where is the lead of the team that owns billing-sync based?
waves: [['s1'], ['s2']]
s1 search_docs {"query": "billing-sync owner"} -> {'job': 'billing-sync', 'owner':
'Payments'}
s2 team_lead {"team": "Payments"} -> {'name': 'Ben Okafor', 'office': 'Leeds'}
Ben Okafor leads the Payments team, which owns billing-sync, and works in Leeds.
[handbook#billing-sync] [team_lead]
calls: 6, in sequence: 6python break_fixture.py handbook#billing-sync
python decompose.py "Where is the lead of the team that owns billing-sync based?"13 passages left
Q: Where is the lead of the team that owns billing-sync based?
waves: [['s1'], ['s2']]
s1 search_docs {"query": "billing-sync owner"} -> no usable evidence
ABSTAIN: step s1 found no evidence. Known: nothing
calls: 3, in sequence: 3The office in the answer follows the database. Without the bridge passage, s1 cannot find an owner, the rewrite has nothing to correct, and the run abstains before it calls the database at all: three calls instead of six. Restore the fixture before the next lesson.
python make_fixture.pydocs: 14 passages, web: 2 pages
people 3
teams 4
runs 93
payroll 206. Troubleshooting
07. Check your understanding
08. Apply it
For the practice project:
- Take the five multi-hop questions you labelled in lesson 1 and write the plan for each by hand in this JSON format. Mark which steps can run together.
- Replace
fake_plan()with a model call. Give the model the tool descriptions from lesson 2 and the plan format, ask for JSON only, and keepvalidate_plan()between the model and the executor. Log every plan it rejects. - Replace
extract()with a model call that returns the values and quotes the sentence or row they came from, and reject a value that is not in the quote. - Add a test that changes one fixture value and checks that the answer changes, and one that removes a bridge record and checks that the run abstains.
09. Review prompt
Without looking back:
- What is the difference between a bridge question and a comparison question, and how does it show in the waves?
- Name three places where a query is rewritten around decomposition.
- What does
validate_plan()reject, and why must a plan be validated even when a capable model wrote it? - Why do values from earlier steps go into tool arguments and not into SQL text?
- When should a decomposed run abstain, and what should its answer contain?
References
- HotpotQA: A Dataset for Diverse, Explainable Multi-hop Question Answering (Yang et al., 2018)
- Measuring and Narrowing the Compositionality Gap in Language Models (self-ask, Press et al., 2022)
- Python documentation: Coroutines and Tasks (asyncio.gather, asyncio.to_thread)
- Python documentation: difflib (get_close_matches)
- Agentic Retrieval-Augmented Generation: A Survey (Singh et al., 2025)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.