ReTool: Reinforcement Learning for Strategic Tool Use in LLMs

Paper · arXiv 2504.11536 · Published April 15, 2025
Reinforcement Learning

While reasoning models (e.g., DeepSeek R1) trained with reinforcement learning (RL), excel in textual reasoning, they struggle in scenarios requiring structured problem-solving, such as geometric reasoning, concise computation, or complex equation solving—areas where computational tools like code interpreters (CI) demonstrate distinct advantages. To bridge this gap, we propose ReTool, which enhances long-form reasoning with tool-integrated learning, including two key features: (1) dynamic interleaving of real-time code execution within natural language reasoning processes, and (2) an automated RL paradigm that allows policy rollouts with multi-turn real-time code execution and teaches the model in learning when and how to invoke tools based on outcome feedback. ReTool employs a systematic training framework, beginning with synthetic cold-start data generation to produce code-augmented long-form reasoning traces for fine-tuning base models. Subsequent RL training leverages task outcomes as rewards to iteratively refine the model’s tool use strategy, enabling autonomous discovery of optimal tool invocation patterns without human priors. Experiments on the challenging MATH Olympiad benchmark AIME demonstrate ReTool’s superiority: Our 32B model achieves 67% accuracy with 400 training steps, outperforming text-based RL baseline (40% accuracy, 1080 steps) in efficiency and performance. Remarkably, ReTool-32B attains 72.5% accuracy in extended settings, surpassing OpenAI’s o1-preview by 27.9%. Further analysis reveals emergent behaviors such as code self-correction, signaling an “aha moment” in which the model autonomously masters adaptive tool use. These findings highlight the promise of outcome-driven tool integration for advancing complex mathematical reasoning and offer new insights into hybrid neuro-symbolic systems.

Introduction. Reinforcement learning (RL) has recently become a popular paradigm for enhancing the reasoning capabilities of large language models (LLMs), enabling them to explore and refine long chains of thought (CoT) [9, 26, 32, 34]. Reasoning models such as OpenAI o1 [12] and DeepSeek R1 [4] demonstrate strong performance in pure textbased reasoning tasks by learning to self-correct and engage in more deliberate, analytical thinking [3, 20, 23]. These advances suggest early signs of metacognitive control, where models not only reason, but also monitor and revise their reasoning process.

Despite these advances, reasoning LLMs equipped with long chains of textual reasoning processes [13] still show notable limitations in tasks that require precise numerical calculation or symbolic manipulation, such as geometric reasoning, precise computation, or complex equation solving. In contrast, computational tools, such as code interpreters (CI), can empower models with symbolic computation capabilities that go far beyond pure text-based reasoning. Unlike textual CoT [27] methods that rely solely on internal language patterns, code interpreters provide a formal and executable interface for enumeration, verification, and precise computation. This not only enables exact numeric validation of intermediate steps—dramatically reducing the ambiguity and compounding error often seen in textual reasoning [1, 25], but also allows models to expand their solution search space via programmable exploration.

Recent works have explored prompting and supervised fine-tuning methods [2, 14] to equip LLMs with tool-use capabilities. However, these approaches are limited to imitating the specifically-curated data distribution, often failing to generalize beyond seen patterns or adaptively decide when and how to invoke external tools. As a result, models may misuse tools or fall back on brittle heuristics that are not robust across diverse problem settings. To overcome these limitations, RL offers a principled solution: it enables models to explore flexible reasoning trajectories and learn tool-use strategies guided by outcome-based feedback. This paradigm not only incentivizes correct solutions, but also allows the model to discover nuanced behavioral patterns—such as how to recover from tool execution mistakes via self-correction, decide when to effectively invoke tool execution during the long-chain reasoning process.

In this work, we embrace the RL paradigm and introduce ReTool, a Tool-augmented Reinforcement learning framework explicitly designed to guide LLMs towards optimal strategies for leveraging external computational tools during reasoning. ReTool consists of two key components: First, we develop a data construction pipeline to curate a high-quality cold-start dataset that explicitly demonstrates when and how to invoke the code interpreter. This teaches the model an initial competency in tool usage and execution result analysis. Then, we apply tool-enhanced reinforcement learning to train the model in discovering the optimal tool manipulation reasoning strategy and adjusting its behavior through outcome-based rewards, going beyond what can be captured by supervised learning alone. During long-chain reasoning, the policy model rolls out by flexibly writing code blocks and achieving real-time execution results from a sandbox-style code interpreter to assist subsequent thinking.

We evaluate ReTool on the challenging MATH Olympiad benchmarks AIME2024 and AIME2025. Building on Qwen2.5-32B-Instruct [30], our model achieves 67.0% accuracy on AIME2024 with only 400 training steps, significantly outperforming the text-based RL baseline, which achieves 40.0% accuracy with 1080 training steps. These substantial gains highlight that explicitly modeling tool-use as part of the decision process not only pushes the limits of model reasoning but also enhances training efficiency. Furthermore, when trained on DeepSeek-R1-Distill-Qwen-32B [4], our model demonstrates further improvements, surpassing competitive baselines such as QwQ-32B-Preview [23], s1-32B [10], and OpenAI o1-preview [11]. This suggests that the RL training process inspires more efficient problem-solving strategies. Additionally, our cold-start model based on Qwen2.5-32B-Instruct achieves an accuracy of 40.9% on AIME2024, comparable to the text-based RL baseline based on same backbone (40.0%), and significantly surpasses the non-trained Qwen2.5-32B-Instruct (26.7%). These results demonstrate that our curated dataset effectively captures tool usage patterns within executable reasoning traces, and that CI-integrated training positively contributes to reasoning performance.

Related work. Recent advancements in large language models (LLMs) [3, 4, 9, 12, 19, 20, 26, 28, 30, 32] indicate significant progress toward cognitive abilities similar to human metacognition through Chain-of-Thought (CoT) prompting. CoT prompting, first introduced by Wei et al. [27], enhances the reasoning capabilities of LLMs by leveraging step-by-step natural language descriptions, significantly improving performance on various reasoning tasks. Building upon this foundation, recent research has shifted focus from train-time scaling to test-time scaling [17], where additional computational resources are allocated during inference to enable the generation of intermediate reasoning steps. Techniques such as stepwise preference optimization [7], Monte Carlo Tree Search (MCTS) [29], and reinforcement learning [9] have been employed to improve multi-step and long-form mathematical reasoning. Advanced models like OpenAI-o1 [12] and DeepSeek-R1 [4] exemplify the effectiveness of CoT-based reasoning. Complementing CoT, Program-of-Thought (PoT) reasoning, introduced by Chen et al. [1] and Gao et al. [5], integrates external computational tools—such as Python interpreters—to simplify and validate complex reasoning steps, resulting in enhanced accuracy.

Tool-integrated reasoning was first introduced to help LLMs solve computationally intensive mathematical problems with the integration of programming strategies [1, 6, 18, 24, 33]. Building on this foundation, Wang et al. [25] proposed an iterative approach that combines textual reasoning with code execution to mutually verify and enhance reasoning accuracy. More recently, Chen et al. [2] integrated code execution into the reasoning process by performing supervised fine-tuning on self-curated code-integrated CoT data. However, this approach is inherently limited by its reliance on the specific data distribution, and cannot learn adaptive strategies for tool use—such as determining when and how to invoke tools—through reinforcement learning. A concurrent work [8] applied reinforcement learning to learn tool usage strategies on Qwen2.5-Math models [31] at 1.5B and 7B scales, but the performance remained suboptimal. We further scale up this line of research and propose ReTool, a framework that leverages reinforcement learning to strategically determine when and how to invoke the code interpreter. Our method outperforms Qwen-Math-72B-TIR [31] and o1-preview [11] significantly on AIME2024 and AIME2025. We also present a comprehensive analysis of the learned tool-use behaviors and highlight several key findings regarding the model’s cognitive patterns in code invocation after ReTool training.

Method. Our methodology consists of two primary stages: cold-start supervised fine-tuning followed by reinforcement learning with interleaved code execution rollout. Firstly, we collect data through our designed pipeline for cold-start supervised fine-tuning (SFT), which provides a robust initialization for the reinforcement learning phase. To enhance our model’s tool utilization capabilities, we introduce a specialized tool-using reinforcement learning pipeline that enhances the model’s ability to appropriately select and apply tools during the reasoning process.

We designed a pipeline for collecting and curating high-quality data. Specifically, we begin by gathering existing mathematical reasoning data from diverse sources, including open-source datasets such as Open- Thoughts [22]. Subsequently, we implement a dual-verification approach combining human expert curation and Deepseek-R1 [4] evaluation to filter invalid data. Through these steps, we collect a high-quality text-based reasoning dataset, denoted as Dinit.

Based on Dinit, we further construct code-integrated reasoning data in an automatic manner. We first utilize a structured prompt template (detailed in Figure 8) for transformation, which modifies the original thinking process by replacing manual calculation steps that can benefit from code execution with the corresponding code snippets and their interpreter’s execution results. Following this initial transformation, we apply a two-stage verification protocol. The first stage focuses on format verification, which improves readability and ensures consistent syntax that that enables the efficient detection of computational tool invocation triggers during subsequent reinforcement learning phases. The second stage entails answer verification, where we eliminate data samples whose final outputs do not align with the correct solutions to the mathematical problems. Finally, we collect a dataset DCI that consist of code-augmented long-form reasoning traces.

ReTool employs supervised fine-tuning to learn when and how to invoke the code interpreter from the aforementioned dataset DCI, thereby enhancing the model’s capability to appropriately utilize computational tools.

We train ReTool based on PPO algorithm [16], it updates policy with the following objective: where πθ is policy model, πθold is reference model, πθ(ot | q, o<t; CI) represents the rollouts with interleaved code execution and feedback from code interpreter.

We modify PPO to better adopt tool integrated reasoning. During training, the policy LLM will collaborate with a code sandbox to generate rollouts with multi-turn real-time code execution for solving given problems. We implement a rule-based outcome reward to enable the model with the flexibility to autonomously explore and develop strategies for code usage awareness, code selection, timing of code invocation, and further diverse behaviors.

Reward Design To teach the model in learning when and how to invoke tools, we implement a rule-based accuracy reward to optimize the model. The accuracy reward evaluates response correctness. We require the model to present final answers in a specified format (e.g., within \boxed{}), enabling reliable rule-based verification. The reward is formulated as: where a and ˆa represent the ground-truth answer and the predicted answer, respectively. We simplify the reward design aim to alleviate reward hacking and promote more diverse problem-solving behaviors based on mere outcome feedback without considering code executability reward.

Rollout with Interleaved Code Execution To facilitate the integration of reasoning and executable code within the model, we propose a rollout approach that dynamically supports interleaved real-time code execution with natural language reasoning processes. As depicted in Figure 2 (b), our rollout process differs from the conventional approach, which typically generates only text-based reasoning (as shown in Figure 2 (a)). By contrast, our rollout approach integrates the collaboration of a policy LLM with an external code sandbox, enabling the production of hybrid content that combines text, code snippets, and real-time interpreter feedback.

Discussion. We present a comprehensive analysis and highlight several key findings from our exploration, including: (1) The dynamics of code interpreter (CI)-related behaviors throughout the RL process; (2) The emergence of self-correcting capabilities; (3) Differences in code purpose before and after RL; (4) Distinctions between CI-powered reasoning and text-based reasoning.

CI-related Behavior Evolution. To gain deeper insights into the RL process of ReTool, we systematically evaluated CI-related metrics. Specifically, we computed these metrics by analyzing model-generated outputs on the AIME2024 and AIME2025 datasets based on each saved checkpoint during RL training. The results are illustrated in Figure 3, and our analysis comprises:

• Response Length (Figure 3 (a)): We calculated the average response length and observed a distinct trend: the generated response length initially declines sharply, later followed by a relatively gentle increase. We attribute the initial decline to the replacement of complex computational processes with more concise code, while the subsequent rise is likely due to the emergence of more diverse and complex code behaviors during RL training. Notably, the final average response length remains 40% shorter than that before RL training (i.e., from 10k to 6k). This suggests that the CI-powered reasoning approach potentially enhances efficiency of reasoning token utilization ratio by replacing intricate computational processes with code.

• Code Ratio (Figure 3 (b)): The ratio of responses that contain code are also calculated. Analysis reveals that throughout the RL training process, the average code ratios exhibit a total upward trend and end with covering nearly 98% percent of all questions. This suggests that the model’s proficiency in code utilization improved progressively during the RL process, facilitating strategic tool usage development.

• Code Lines (Figure 3 (c)): The lines of generated code reflects its complexity to some extent. Observations show that the average code lines in responses exhibits a consistent upward trend throughout training. By the end of RL training, the final average code lines is nearly fivefold higher than that before RL training. This trend suggests that the model has learned more complex code strategies during the RL phase.

• Total Test Set Correct Code Counts (Figure 3 (d)): The number of total correct code counts on test set exhibits an overall upward trend during RL training, increasing from 1k to 5k. This improvement indicates the enhanced proficiency in leveraging code tools.

• Code Pass Rate (Figure 3 (e)): The CI-powered reasoning process involves generating intermediate code that may initially be incorrect, followed by iterative refinement based on interpreter feedback to produce executable code, so we report the average pass rate of last code in incorrect responses. Our analysis reveals that the code pass rate for correct responses remains consistently high, approaching 100%, while the code pass rate for incorrect responses exhibits a declining trend. This pattern suggests that code executability impacts the reasoning process and final result.

• Code Invocation Timing (Figure 3 (f)): We also calculate the code invocation timing, which is determined by dividing the start position of code by the total length of the response. This metric reflects the timing of code invocation within the response. The results show that the code invocation timing advances during the RL training process, indicating that the model learns to determine the timing for tool usage.

“Aha Moment” of Code Self-correction. Interestingly, our model exhibits an emergent ability to self-correct non-executable code, despite the absence of explicit training data for code self-correction.

Conclusion. In this paper, we propose ReTool, a novel reinforcement learning framework that empowers large language models to self-enhance their mathematical reasoning capabilities through effective Code Interpreter utilization. Our comprehensive experiments on AIME2024 and AIME2025 demonstrate that ReTool not only achieves superior accuracy compared to conventional text-based RL approaches, but also converges with significantly fewer training steps. Through careful data curation and our specialized tool-using pipeline, ReTool enables models to develop sophisticated computational intervention strategies, paving the way for more efficient and powerful tool-augmented reasoning in LLMs.

Lines of inquiry this paper opens 24

Research framings built by reading the notes related to this paper — the questions it feeds into.

Does chain-of-thought reveal genuine reasoning or merely imitate learned behavior? Can visual rendering-based rewards effectively improve code and layout quality? How can reward models overcome their inherent blindspots and biases? Can agents learn from feedback and experience to improve behavior? How important is reward engineering relative to pretraining for reasoning? How does task-specific training affect model generalization and capability transfer? Can agent-created code become persistent, reusable infrastructure that improves over time? How does policy entropy collapse constrain the scaling of reasoning RL? What trajectory qualities should agent evaluation measure beyond task success? Can AI systems formally evaluate design quality and taste? How reliably do benchmark metrics reflect actual model capability? How should inference-time compute be optimally allocated for reasoning? What persistent memory architectures best support learning across sessions? How do structural differences between diffusion and autoregressive models affect capabilities? Do base models contain latent reasoning that training can unlock?