Retrieval is Cheap, Show Me the Code: Executable Multi-Hop Reasoning for Retrieval-Augmented Generation

Jiashuo Sun, Jimeng Shi, Yixuan Xie, Saizhuo Wang, Jash Rajesh Parekh, Pengcheng Jiang, Zhiyi Shi, Jiajun Fan, Qinglong Zheng, Peiran Li, Shaowen Wang, Ge Liu, Jiawei HanarXiv 2026

TL;DR

PyRAG reformulates multi-hop Retrieval-Augmented Generation (RAG) as a program synthesis and execution task rather than a free-form natural language narrative. By representing the reasoning process as an executable Python program, it introduces explicit state tracking, deterministic compiler feedback for self-repair, and execution-driven adaptive retrieval, significantly outperforming traditional text-based RAG baselines.

What Problem Does This Paper Address?

While standard Retrieval-Augmented Generation (RAG) excels at answering single-hop questions ("When was Jed Hoyer born?"), it frequently breaks down on complex, multi-hop questions ("Who is older, Jed Hoyer or John William Henry II?"). Answering the latter requires chaining multiple retrieval and reasoning steps together.

Existing multi-hop RAG systems typically rely on free-form natural language trajectories (like Chain-of-Thought or iterative search loops). The authors identify three major flaws in this approach:

  1. Implicit State Tracking: Intermediate reasoning states are buried in unstructured text, making them hard to track and verify.
  2. Entity Drift: Errors accumulate across steps, causing subsequent search queries to drift away from the intended entities.
  3. Unreliable Self-Reflection: Systems often ask the same LLM that generated an error to detect and fix it, creating an unreliable, ungrounded feedback loop.
Figure 1: Comparison across Vanilla RAG, Search Agents, and PyRAG (Ours). Given the multi-hop question “Who is older, Jed Hoyer or John William Henry II?”, (a) Vanilla RAG performs single-shot retrieval and is prone to incomplete or noisy evidence; (b) Search Agents follow an unstructured iterative trajectory where vague queries and entity drift (e.g., retrieving “Henry II of England” instead of “John William Henry II”) accumulate errors across steps; (c) PyRAG decomposes the question into atomic sub-queries and generates an executable program that retrieves, answers, and composes intermediate results through explicit variables, yielding a controllable, inspectable, and accurate reasoning process.

Methods

The authors introduce PyRAG, a framework that treats multi-hop reasoning as a step-by-step programmatic computation. Instead of generating a paragraph of thoughts, PyRAG synthesizes a Python program that explicitly manages data flow using variables and tool calls.

The framework consists of three specialized agents:

  • Decompose Agent: Breaks down the complex user prompt into atomic, independently answerable sub-queries.
  • Plan Agent: A code-specialized LLM that translates these sub-queries into an executable Python program using two primary tool APIs: retrieve(query, topk) and answer(query, docs).
  • Answer Agent: Extracts short answers from the retrieved text snippets during program execution.
Figure 2: The PyRAG framework. Given a multi-hop question, PyRAG proceeds in three stages: (1) Decompose: an LLM breaks the question into atomic, independently answerable sub-queries; (2) Plan: a code-specialized LLM synthesizes an executable Python program over two tool primitives, retrieve(query, topk) and answer(query, docs), where intermediate results are bound to variables and composed through explicit data dependencies; (3) Execute: the program is run step- by-step in a Python interpreter, producing an inspectable trace and a grounded final answer. Two execution-guided refinement mechanisms refine this pipeline: (A) Compiler-Grounded Self-Repair, which uses runtime exceptions (e.g., SyntaxError, NameError) as deterministic signals for the plan- ner to revise and re-execute the program; and (B) Execution-Driven Adaptive Retrieval, which boosts the top-k retrieval budget for sub-steps whose answer indicates insufficient evidence. Both mecha- nisms are training-free and rely on grounded execution feedback rather than LLM self-reflection.

Crucially, PyRAG leverages the Python interpreter to enable two training-free, execution-guided refinement loops:

  • Compiler-Grounded Self-Repair: If the generated code throws a runtime exception (e.g., SyntaxError, NameError), the traceback is fed back to the Plan Agent as a deterministic signal to fix the code.
  • Execution-Driven Adaptive Retrieval: If the Answer Agent returns a sentinel value indicating insufficient evidence (like "unknown"), the system automatically boosts the top-k retrieval budget for that specific step and re-executes it.

PyRAG can be used entirely training-free or fine-tuned using Reinforcement Learning (specifically GRPO) via a curriculum schedule that sequentially trains the Answer, Plan, and Decompose roles.

Datasets

The authors evaluated PyRAG across five open-domain QA benchmarks spanning single-hop and multi-hop reasoning:

  • PopQA (Single-hop, evaluated out-of-domain)
  • HotpotQA (Multi-hop, used as the in-domain training set for RL variants)
  • 2WikiMultihopQA (Multi-hop, evaluated out-of-domain)
  • MuSiQue (Multi-hop, evaluated out-of-domain)
  • Bamboogle (Multi-hop, evaluated out-of-domain)

For the RL training phase, a mixture of Natural Questions (NQ) and HotpotQA was utilized.

Key Insights and Ideas

  • The Task-Interface Co-design: One of the paper's most compelling findings is that code-specialized models do not inherently outperform standard instruction models in traditional text-based RAG. Their superior reasoning capabilities only emerge when the problem is explicitly framed as program synthesis.
  • Decoupling Logic from Language: By offloading operations like date arithmetic, boolean conjunctions (all()), and conditional branching to Python, the LLM is freed from performing mental arithmetic, eliminating a notorious source of hallucination.
  • Grounded Feedback Beats Self-Reflection: Relying on concrete interpreter errors or explicit sentinel strings provides a much more stable and reliable correction mechanism than asking an LLM to judge its own text.
Ablation studies showing progressive gains and the effect of model specialization

Key Results

PyRAG consistently outperformed strong iterative and agentic baselines under both training-free and RL-trained settings.

Training-Free Settings (7B Scale)

Using Qwen2.5-7B-Instruct as the backbone, PyRAG achieved an average Exact Match (EM) score of 30.8%, outperforming Vanilla RAG (19.0%) and the strongest iterative baseline, ITER-RETGEN (26.2%).

  • The gains were most dramatic on highly compositional datasets like Bamboogle, where PyRAG saw a +25.5% EM jump over Vanilla RAG.

Scalability (72B Scale)

When scaled to Qwen2.5-72B-Instruct, PyRAG reached an average EM of 40.9%, maintaining a substantial lead over all baselines.

Exact Match results for Qwen2.5-7B-Instruct

Efficiency

PyRAG achieved these accuracy gains with a better cost-to-performance trade-off. It matched or exceeded the accuracy of unstructured search agents (like Search-R1) while requiring significantly fewer average LLM calls per query (3.7 calls vs. Search-R1's higher iterative overhead).

Limitations and Future Work

Despite its success, the authors highlight several areas for improvement:

  • Upstream Retrieval Bottleneck: Around half of PyRAG's failures are caused by the retriever failing to surface the necessary documents in the first place.
  • Sentinel Propagation: The adaptive retrieval mechanism relies on string-matching sentinel values like "unknown". If the model accidentally passes "unknown" into a downstream query as actual content, it can cause silent error propagation.
  • Under-Decomposition: Occasionally, the Plan Agent generates a single retrieve() call for a question that clearly requires multiple hops, bypassing the benefits of the framework entirely.

Future work will focus on integrating more robust structured return types, optimizing aggregation prompts, and improving upstream retrieval recall.

Summary updated

BibTeX
@misc{sun2026retrieval,
  author = {Jiashuo Sun and Jimeng Shi and Yixuan Xie and Saizhuo Wang and Jash Rajesh Parekh and Pengcheng Jiang and Zhiyi Shi and Jiajun Fan and Qinglong Zheng and Peiran Li and Shaowen Wang and Ge Liu and Jiawei Han},
  title = {{Retrieval is Cheap, Show Me the Code: Executable Multi-Hop Reasoning for Retrieval-Augmented Generation}},
  year = {2026},
  eprint = {2605.12975},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2605.12975},
}
Figure