Zhanbo Chen
Back to home

Reproducing ToolRL with PyTRIO: Teaching a Small Model to Call Tools with Reward Design Alone

AI Agent
2026-11-29
33 min read
0 reads
Agentic RLToolRLGRPOTool CallingPyTRIO

In brief

Reproducing ToolRL on Qwen3.5-4B with PyTRIO: 20 GRPO steps (under ¥8) driven only by a format reward and tool-name / parameter-name / parameter-value correctness rewards lift format pass rate from 30% to 90%, exact match from 30% to 60%, and BFCL Non-Live AST average from 54.8% to 90.6%.

Want to skip the article and run the code? See the quick start: prepare data → train → evaluate.

Code and reproduction resources

Search-R1 and ReTool both apply RL to calls of a single fixed tool, while a real agent faces a different tool list every time. That is the setting ToolRL studies.

The conclusion first: after 20 steps of LoRA training on Qwen3.5-4B (costing less than ¥8), the format pass rate rises from 30% to 90% and the exact-match rate from 30% to 60%. On BFCL, which the model never saw during training, the Non-Live AST average also rises from 54.8% to 90.6%.

Model (greedy decoding)Mean rewardFormat pass rateExact matchBFCL Non-Live AST average
Base (Qwen3.5-4B)0.9530.0%30.0%54.8%
RL Step 102.6888.8%55.7%89.0%
RL Step 202.6890.0%60.0%90.6%

The first three columns come from 80 ToolRL test samples held out from the original dataset. The mean reward ranges over [-3, 4]. Exact match (EM) only counts the 70 samples whose ground truth contains tool calls: a sample scores 1 only if the model's list of tool calls (tool names, parameter names, parameter values and order) matches the ground truth exactly. The last column is the average accuracy over the four AST categories of BFCL v4 Non-Live; see "BFCL evaluation" below.

Where does ToolRL come from?

ToolRL was proposed in 2025 by Cheng Qian et al. at UIUC. Its full title is:

ToolRL: Reward is All Tool Learning Needs

ToolRL does not propose a new algorithm; it still uses GRPO. Its contribution is the reward design. In RL training, a tool call does not have a "single correct answer" the way a math problem does, so how the reward is designed strongly affects how well RL works. In its analysis, the paper also ablates rewards of different granularity and shows that fine-grained rewards matter for RL performance. Here we use PyTRIO to implement the finest-grained reward design from the paper.

How ToolRL trains

In ToolRL, each sample is a "single-step decision": given a tool list and the dialogue history (including the earlier <user>/<think>/<tool_call>/<response>/<obs>, all taken directly from the history in the dataset rather than sampled by the model), the model only has to generate the next reply.

ToolRL single-step tool-call rollout and the GRPO training loop

system: 可用工具列表(名称、描述、参数 schema)+ 输出格式要求
user:   **Dialogue Records History**
        <user> 用户的请求 </user>
        (多步轨迹中,之前的 <tool_call> 和 <obs> 也拼在这里)

The model's output format is fixed:

<think> 推理过程 </think>
<tool_call>
{"name": "工具名", "parameters": {...}}
{"name": "另一个工具", "parameters": {...}}
</tool_call>

Or, without calling a tool, it answers directly:

<think> 推理过程 </think>
<response> 给用户的回复 </response>

Two things are very different from Search-R1 and ReTool:

  1. Tools are not executed during training. The official data splits multi-step trajectories into single-step samples, and the dialogue history is concatenated into the prompt. The reward only compares "what the model wants to call" with "what the ground truth called". So this chapter has no sandbox, no search backend and no multi-turn rollout.
  2. Every sample has different tools. The tool list is written in each sample's own system prompt, so the model cannot score by memorizing a few tool names.

My own impression is that ToolRL's training method sits between ORM and PRM, with a bit of an SFT flavor.

Viewed over a whole task, it looks like PRM: a multi-step trajectory is split into many single-step samples, every step gets its own reward, and the signal is very dense. But at the level of a single sample, it is really ORM: only the tool call the step finally outputs is checked, the intermediate reasoning is not scored, let alone evaluated token by token.

The SFT flavor comes from its inputs. In Search-R1, the model's reasoning at the current step builds on the trajectory it sampled itself in earlier steps; in ToolRL, every single-step sample builds on the ground-truth dialogue history given by the dataset, somewhat like teacher forcing in SFT. And precisely because the history is fixed, the tool to call at every step has its own ground truth, so a reward can be computed step by step.

ToolRL's reward design

The reward design is the core of the paper. The total reward has two parts, a format reward and a correctness reward:

R = R_format + R_correct,   R_format ∈ [0, 1],  R_correct ∈ [-3, 3]

Worked example of ToolRL's format reward and correctness reward

Format reward

The paper's format reward is a 0/1 check: the model output must contain every special tag the ground truth requires, in the right order.

Rformat={1,all required fields are present and in the correct order0,otherwiseRformat∈{0,1}\mathcal{R}_{\text{format}} = \begin{cases} 1, & \text{all required fields are present and in the correct order} \\ 0, & \text{otherwise} \end{cases} \qquad \mathcal{R}_{\text{format}} \in \{0, 1\}

The code follows the official implementation: depending on which tags appear in the ground truth, a different regular expression is used.

Ground truth containsRequired output structureExtra check
Only <response><think>…</think> newline <response>…</response><response> appears exactly once
Only <tool_call><think>…</think> newline <tool_call> newline … newline </tool_call><tool_call> appears exactly once
BothThe two structures above, one after the otherEach tag appears exactly once
NeitherOnly <think>…</think>—

Implementation

The format reward is implemented in format_reward in reward.py, with the regular expressions ported verbatim from the official rlla.py:

RESPONSE_ONLY_PATTERN = re.compile(r"^<think>.*?</think>\n<response>.*?</response>$", re.DOTALL)
TOOL_ONLY_PATTERN = re.compile(r"^<think>.*?</think>\n<tool_call>\n.*?\n</tool_call>$", re.DOTALL)
TOOL_AND_RESPONSE_PATTERN = re.compile(
    r"^<think>.*?</think>\n<tool_call>\n.*?\n</tool_call>\n<response>.*?</response>$",
    re.DOTALL,
)
THINK_ONLY_PATTERN = re.compile(r"^<think>.*?</think>$", re.DOTALL)


def format_reward(response: str, ground_truth: str, config: RewardConfig) -> float:
    """按 ground truth 中出现的标签组合,检查回复是否符合对应的严格格式。"""
    has_tool = "<tool_call>" in ground_truth
    has_response = "<response>" in ground_truth
    if has_response and not has_tool:
        ok = (
            RESPONSE_ONLY_PATTERN.search(response) is not None
            and response.count("<response>") == 1
            and response.count("</response>") == 1
        )
    elif has_tool and not has_response:
        ok = (
            TOOL_ONLY_PATTERN.search(response) is not None
            and response.count("<tool_call>") == 1
            and response.count("</tool_call>") == 1
        )
    elif has_tool and has_response:
        ok = (
            TOOL_AND_RESPONSE_PATTERN.search(response) is not None
            and response.count("<tool_call>") == 1
            and response.count("</tool_call>") == 1
            and response.count("<response>") == 1
            and response.count("</response>") == 1
        )
    else:
        ok = THINK_ONLY_PATTERN.search(response) is not None
    return config.format_max if ok else 0.0

These regular expressions are stricter than the paper's description. Three points are worth noting:

  • Anchored with ^ and $: the output must start with <think> and end with a closing tag, with nothing extra before or after.

  • Exactly one newline: there may be only one \n between </think> and the next tag. Qwen3.5 tends to write two newlines here, so we normalize the newline before scoring (see "Step 4: score with the format and correctness rewards" below):

    if config.normalize_think_newline:
        response = response.replace("</think>\n\n", "</think>\n", 1)
  • All calls must go in a single <tool_call> block, one JSON object per line. Splitting them into several blocks scores 0 because <tool_call> appears more than once. The correctness reward also parses only the first <tool_call> block, so splitting loses both the format score and the correctness score of the later calls. This matches the format of the dataset's ground truth and the format the system prompt asks for.

Correctness reward

We write the predicted tool calls as P={P1,…,Pm}P = \{P_1, \dots, P_m\} and the ground-truth tool calls as G={G1,…,Gn}G = \{G_1, \dots, G_n\}. The paper splits the correctness reward into three levels, each scored separately.

Level 1: tool-name matching. NGN_G and NPN_P are the sets of tool names that appear in the ground truth and in the prediction:

rname=∣NG∩NP∣∣NG∪NP∣∈[0,1]r_{\text{name}} = \frac{|N_G \cap N_P|}{|N_G \cup N_P|} \in [0, 1]

Level 2: parameter-name matching. For each ground-truth call GjG_j and the predicted call paired with it, compute the Jaccard similarity of the two sets of parameter names (keys(PG)\text{keys}(P_G) and keys(PP)\text{keys}(P_P)), then sum over all ground-truth calls:

rparam=∑Gj∈G∣keys(PG)∩keys(PP)∣∣keys(PG)∪keys(PP)∣∈[0,∣G∣]r_{\text{param}} = \sum_{G_j \in G} \frac{|\text{keys}(P_G) \cap \text{keys}(P_P)|}{|\text{keys}(P_G) \cup \text{keys}(P_P)|} \in [0, |G|]

Level 3: parameter-value matching. For each parameter kk of a ground-truth call, a predicted value exactly equal to the ground-truth value scores 1:

rvalue=∑Gj∈G∑k∈keys(Gj)1[PG[k]=PP[k]]∈[0,∑Gj∈G∣keys(Gj)∣]r_{\text{value}} = \sum_{G_j \in G} \sum_{k \in \text{keys}(G_j)} \mathbb{1}\left[P_G[k] = P_P[k]\right] \in \left[0, \sum_{G_j \in G} |\text{keys}(G_j)|\right]

The three levels add up to the total match score. Its maximum Smax⁡S_{\max} has three parts: 1 point for tool names, 1 point for the parameter names of each ground-truth call, and 1 point for the value of each ground-truth parameter:

rmatch=rname+rparam+rvalue,Smax⁡=1+∣G∣+∑Gj∈G∣keys(Gj)∣r_{\text{match}} = r_{\text{name}} + r_{\text{param}} + r_{\text{value}}, \qquad S_{\max} = 1 + |G| + \sum_{G_j \in G} |\text{keys}(G_j)|

The paper looks for the pairing between PP and GG that maximizes the total match score, writes that total as Rmax⁡R_{\max}, and maps it linearly to [−3,3][-3, 3]:

Rcorrect=6⋅Rmax⁡Smax⁡−3∈[−3,3]\mathcal{R}_{\text{correct}} = 6 \cdot \frac{R_{\max}}{S_{\max}} - 3 \in [-3, 3]

The final reward is Rfinal=Rformat+Rcorrect∈[−3,4]\mathcal{R}_{\text{final}} = \mathcal{R}_{\text{format}} + \mathcal{R}_{\text{correct}} \in [-3, 4].

Implementation

The correctness reward is implemented in reward.py, ported line by line from the official rlla.py. The Jaccard scores for both tool names and parameter names are computed by match_score:

def match_score(list1: list[Any], list2: list[Any], strict: bool = False) -> float:
    """计算两个列表的多重集合 Jaccard 相似度(忽略顺序)。"""
    if list1 == list2:
        return 1.0
    if strict or not list1 or not list2:
        return 0.0
    count1, count2 = Counter(list1), Counter(list2)
    intersection = sum(min(count1[key], count2[key]) for key in count1.keys() & count2.keys())
    union = len(list1) + len(list2) - intersection
    return intersection / union if union > 0 else 0.0

The three levels of scoring, Smax⁡S_{\max} and the final linear mapping all live in tool_call_score (the type annotations and the intermediate / coarse / strict branches used for ablations are omitted below):

def tool_call_score(gt_tools, pd_tools, config) -> float:
    max_reward, min_reward = config.correct_max, -config.correct_max
    if gt_tools == pd_tools:
        return max_reward

    # 第一层:工具名匹配 r_name
    score = match_score(
        [tool["name"] for tool in gt_tools],
        [tool["name"] for tool in pd_tools],
    )
    max_possible = 1.0  # S_max 中工具名的 1 分
    used_indices: set[int] = set()

    for gt_tool in gt_tools:
        gt_name, gt_params = gt_tool["name"], gt_tool["parameters"]
        max_possible += 1.0 + len(gt_params)  # S_max 中参数名的 1 分 + 参数值的 |keys(G_j)| 分

        # 在同名、尚未被占用的预测调用里,找总分最高的一个与 G_j 配对
        best_index, best_score = -1, 0.0
        for index, pd_tool in enumerate(pd_tools):
            if index in used_indices or pd_tool["name"] != gt_name:
                continue
            pd_params = pd_tool["parameters"]
            # 第二层:参数名匹配 r_param
            param_score = match_score(list(gt_params.keys()), list(pd_params.keys()))
            # 第三层:参数值匹配 r_value
            value_score = sum(
                1.0 for key, value in gt_params.items() if key in pd_params and pd_params[key] == value
            )
            if param_score + value_score > best_score:
                best_index, best_score = index, param_score + value_score

        if best_index >= 0:
            used_indices.add(best_index)
            score += best_score

    # R_correct = (max - min) · score / S_max + min,默认即 6 · score / S_max − 3
    return (max_reward - min_reward) * score / max_possible + min_reward

Parsing of the predicted calls happens in the outer correctness_reward: only the first <tool_call> block is taken, and JSON is parsed line by line. Any parse failure (invalid JSON, a missing name / parameters field and so on) gets the minimum score of −3-3; when the ground truth has no tool call, the correctness reward is fixed at 0.

The code differs from the formulas in two places, and we follow the official code (Step 4 below lists the differences in detail):

  • Pairing: the paper uses the optimal matching that maximizes the total score, while the code goes through the ground-truth calls in order and greedily picks the highest-scoring predicted call with the same name.
  • Jaccard: the paper uses sets, while the code uses Counter to compute it over multisets, so repeated tool names are counted separately.

ToolRL's reward design is very detailed, and the fine granularity makes the signal the model receives much denser. In a typical 0/1 reward, "picked the right tool but got one parameter wrong" scores the same as "wrote complete nonsense". With a sparse 0/1 signal, the model cannot tell a rollout that is only slightly off from one that is completely wrong; only with a detailed, decomposed reward can the model really know how far it is from the correct answer.

Main findings of the paper

FindingEvidence from the paper (Qwen2.5 / Llama3.2, BFCL V3)
Cold-start GRPO works best3B: Raw 33.04 → GRPO 52.98; SFT followed by GRPO only reaches 46.42
Finer rewards are betterFine > intermediate > coarse (1.5B: 40.71 / 37.65 / 36.72)
A length reward hurts small modelsEncouraging longer thinking drops 1.5B from 46.20 to 33.23
PPO is less stable than GRPOWith the same reward, cold-start PPO on 3B reaches only 51.15

How did we reproduce it?

OfficialThis chapter
Training frameworkveRL, 2 × A100 80GBPyTRIO remote training
ModelQwen2.5-1.5B/3B/7B-Instruct and othersQwen3.5-4B (the smallest model PyTRIO can currently train)
Fine-tuningFull parameters, lr 1e-6LoRA rank 32, lr 4e-5
Questions per step51232
Group size44
KLNoneNone
Prompt ending<|im_start|>assistant\n, the model writes <think> itselfSame (the empty thinking block inserted by the Qwen3.5 template is removed); see "Step 2: put the tool list in the prompt" below
Rewardrlla.pyPorted line by line; see "Step 4: score with the format and correctness rewards" below
EvaluationBFCL / API-Bank / Bamboogle80 held-out test samples + BFCL v4 Non-Live (1,240 questions, our own AST checker)

From the models PyTRIO offers, we picked Qwen3.5-4B for the reproduction. Our absolute numbers cannot be compared directly with the paper, but comparing the same model before and after training still shows how useful the algorithm is.

Full pipeline of this reproduction: single-step rollout, format reward and correctness reward (greedy pairing as in the official code)

Code layout:

experiments/toolrl/
  prepare_data.py   下载官方 rlla_4k,固定 seed 切分 train/test
  data.py           读取 JSONL
  protocol.py       prompt 渲染与 completion 还原
  reward.py         格式 + 正确性奖励(移植自官方 rlla.py)
  train.py          GRPO 训练循环
  eval.py           test 集评测
  bfcl_eval.py      BFCL Non-Live 评测
  bfcl_checker.py   BFCL AST 检查(移植自官方 ast_checker)
  analysis.py       训练曲线与评测对比图
  start.md          快速启动指南

Step 1: prepare the questions and ground truth

The official rlla_4k data has three parts: ToolACE 2K, Hammer 1K and xLAM 1K. The Hammer part replaces tool names and parameter names with random strings (for example 5r2DApZIxAmzu8q), forcing the model to read the schema instead of memorizing names.

Following the official preprocessing script, we shuffle with seed 31415 and hold out 2% as the test split:

SamplesWith tool callsOnly <response>
train39203448 (88%)472
test807010

Number of calls per ground-truth answer: 1 call in 52%, 2 calls in 32%, 3 or more in 16%. The median prompt is about 800 tokens, and samples longer than 2048 tokens are filtered out before training (matching the official max_prompt_length).

Command to download the data:

uv run python experiments/toolrl/prepare_data.py

The script downloads dataset/rlla_4k_raw/rlla_rl.json (about 15 MB, 4,000 samples) from the official repository qiancheng0/ToolRL, shuffles it with a fixed seed, holds out 2% as the test split, and writes:

experiments/toolrl/datasets/train.jsonl   3920 条
experiments/toolrl/datasets/test.jsonl      80 条

Step 2: put the tool list in the prompt

Every ToolRL sample comes with its own system prompt containing the tool list and the output format (<think> / <tool_call> / <response>); multi-step trajectories have already been split into single steps by the official data, with the dialogue history concatenated into the user message. So instead of Qwen's native tools= argument, we pass the instruction unchanged as the system message. Unlike Search-R1, where we declare a single search tool ourselves, the tool list here differs from sample to sample.

Prompt rendering lives in protocol.py:

def build_messages(instruction: str, user_input: str) -> list[dict[str, str]]:
    return [
        {"role": "system", "content": instruction},
        {"role": "user", "content": user_input},
    ]


EMPTY_THINK_BLOCK = "<think>\n\n</think>\n\n"
GENERATION_PROMPT = "<|im_start|>assistant\n"


def render_prompt(tokenizer, instruction, user_input, think_prefill=False) -> str:
    text = tokenizer.apply_chat_template(
        build_messages(instruction, user_input),
        tokenize=False,
        add_generation_prompt=True,
        enable_thinking=think_prefill,
    )
    if think_prefill:                      # 消融:prompt 以 "<think>\n" 结尾
        return text
    if not text.endswith(GENERATION_PROMPT + EMPTY_THINK_BLOCK):
        raise ValueError(...)
    return text[: -len(EMPTY_THINK_BLOCK)]  # 默认:删掉空思考块,与官方 prompt 一致

The part that needs the most explanation is how <think> is handled, that is, why the prompt stops at <|im_start|>assistant\n:

ToolRL requires the model to write <think>...</think> itself. The most intuitive approach is to turn off Qwen3.5's native thinking (enable_thinking=False). In practice, however, the template then inserts an empty thinking block at the end of the prompt:

<|im_start|>assistant
<think>

</think>

The model sees that "the thinking is already done" and outputs <tool_call> directly, so the format reward is always 0.

Three possible approaches:

ApproachPrompt endingCharacteristics
Turn off thinkingEmpty thinking block <think>\n\n</think>\n\nThe model outputs <tool_call> directly; the format reward is always 0
Turn off thinking but remove the empty thinking block<|im_start|>assistant\nMatches the official setup; the model writes <think> itself
Turn on thinking<think>\nWaives the "write <think>" part of the format requirement

Of the three, "remove the empty thinking block" matches the official code. The official setup is based on Qwen2.5-Instruct, whose template has no <think>; the prompt ends with <|im_start|>assistant\n and the model must write <think> itself. The format reward's regular expression starts with ^<think>, so it checks this too.

Qwen3.5's chat template has only two forms: with thinking off, it ends with an empty thinking block; with thinking on, it ends with <think>\n. After removing the empty thinking block, the prompt ends with <|im_start|>assistant\n, a form the model has seen in neither mode, so we were initially worried that the first token might not be <think>. In practice the worry was unfounded: on all 80 test samples and all 1,240 BFCL questions, the base model's output starts with <think> on its own.

In the end we remove the empty thinking block: the prompt ends with <|im_start|>assistant\n, and no prefix needs to be added to the completion. Turning on thinking (prefilling <think>\n at the end of the prompt) is kept as the --think-prefill flag for an ablation; see "Ablation: prefilling <think>" below for the results.

Step 3: one sample is one complete trajectory

ToolRL does not execute tools during training, so the next reply the model generates is the whole trajectory: no multiple turns and no observation. There is therefore no need to branch trajectories after a search as in Step 3 of Search-R1; we simply draw 4 samples per question at once.

train.py submits the whole batch of 32 questions concurrently, drawing group_size samples per question in one request:

tasks = [
    sampling_client.sample_async(
        prompt=trio.ModelInput.from_ints(prompt),
        num_samples=group_size,
        sampling_params=params,
        return_text=True,
    )
    for prompt in prompts
]
results = await asyncio.gather(*tasks)

The samples must first be turned back into complete assistant replies before they can be scored (completion_to_response in protocol.py):

def completion_to_response(text: str, tokenizer, think_prefill=False) -> str:
    text = text.rstrip()
    stripped = True
    while stripped:                       # 去掉末尾的 <|im_end|> 等停止符
        stripped = False
        for stop in stop_sequences(tokenizer):
            if text.endswith(stop):
                text = text[: -len(stop)].rstrip()
                stripped = True
    return (ASSISTANT_PREFIX if think_prefill else "") + text  # 只有预填时才补回 "<think>\n"

The text PyTRIO returns includes the stop sequence it hit; without removing it, the $ in the format regex would never match. With the default (no prefill), the model writes <think> itself and the completion is already the full reply; only with --think-prefill is <think>\n part of the prompt, so it has to be added back to the start before scoring.

Step 4: score with the format and correctness rewards

The reward formulas were given above in "ToolRL's reward design"; this step only covers the trade-offs made in the implementation.

The reward is implemented in reward.py. The official code switches between ablation variants with environment variables; here we use an explicit RewardConfig instead:

@dataclass(frozen=True)
class RewardConfig:
    granularity: Granularity = "fine"   # fine / intermediate / coarse / strict
    correct_max: float = 3.0
    format_max: float = 1.0

The paper and the official code disagree in a few places, and this chapter follows the official code:

Paper descriptionActual behavior of the official code
Optimal matching between predicted and ground-truth callsGreedy matching by tool name
Set JaccardMultiset (Counter) Jaccard
Undefined when the ground truth has no tool callThe correctness reward is always 0
—Parameter values are compared with ==, so "5" and 5 are not equal

Even with a prompt that matches the official setup, the base model's format pass rate under the official strict format is only 1.2% (1 of 80), because Qwen3.5 tends to write two newlines after </think> while the official regular expression requires exactly one. If the double newline is normalized to a single one, the base model's format pass rate becomes 30%.

This chapter normalizes the double newline, so that the model's own output habit does not get in the way of training.

Step 5: compute the advantage within each question

Unlike the GRPO chapter of this repository, which only subtracts the mean, the formula in the ToolRL paper also divides by the within-group standard deviation:

Ai=ri−μσ+η,μ=14∑j=14rj,σ=14∑j=14(rj−μ)2A_i = \frac{r_i - \mu}{\sigma + \eta}, \qquad \mu = \frac{1}{4} \sum_{j=1}^{4} r_j, \qquad \sigma = \sqrt{\frac{1}{4} \sum_{j=1}^{4} \left(r_j - \mu\right)^2}

Here 4 is the group size (the number of samples per question), and η=10−6\eta = 10^{-6} prevents division by zero when every reward in the group is the same.

centered = rewards - rewards.mean()
if normalize_std:
    centered = centered / (rewards.std() + ADVANTAGE_EPS)

In my view, standardizing here makes sense: ToolRL's reward ranges over [-3, 4], and the within-group variance differs a lot between questions; samples with only <response> can score at most 1, while samples with a <tool_call> can score up to 4. Of course, an ablation is provided too: add --no-std-norm for the comparison run.

When every sample in a group has the same reward, the advantage is 0 and those samples are not uploaded for training. Early in training, samples with only <response> (about 12%) are almost always degenerate groups: their correctness reward is always 0, and almost none of them pass the format check (the base model passes only 1 of the 10 such samples in the test split).

Step 6: only the model-generated tokens enter the loss

The same idea as Step 6 of Search-R1, but ToolRL is single-step: there are only two segments, the prompt and the completion, with no observation returned by a tool.

build_datum in train.py packs one sample into the Datum that PyTRIO's ppo loss expects:

observation_len = len(sample.prompt_tokens) - 1
input_tokens = sample.prompt_tokens + sample.tokens[:-1]
target_tokens = [0] * observation_len + sample.tokens
logprobs = [0.0] * observation_len + sample.logprobs
advantages = [0.0] * observation_len + [sample.advantage] * len(sample.tokens)

We then set the advantage to 0 at every prompt position, so only the completion tokens generated by the model contribute to the loss.

Next, build the PyTRIO Datum:

datum = trio.Datum(
    model_input=trio.ModelInput.from_ints(input_tokens),
    loss_fn_inputs={
        "target_tokens": np.asarray(target_tokens, dtype=np.int64),
        "logprobs": np.asarray(logprobs, dtype=np.float32),
        "advantages": np.asarray(advantages, dtype=np.float32),
    },
)

input_tokens, target_tokens, logprobs and advantages must all go through the same autoregressive shift and have exactly the same length: the input at position t predicts token t+1, so the input drops the last completion token and the target drops the first prompt token (with 0 as a placeholder over the prompt). build_datum checks that all four lengths match and raises an error if they do not.

logprobs holds the old-policy probabilities in the PPO importance ratio, so they must come from the sampler used at rollout time: at every step a sampler is first exported from the current LoRA weights and then used for sampling (see Step 7), and the logprobs it returns are stored directly. They must not be recomputed after the model has been updated.

Step 7: update the policy with the whole batch of trajectories

Each step of train.py:

  1. Export the current LoRA weights and create a sampler, keeping training on-policy;
  2. Sample the whole batch of 32 questions concurrently, 4 samples per question;
  3. Score with reward.py and compute the standardized advantage per question;
  4. Skip samples whose advantage is 0, and pack the rest into micro-batches by padded area;
  5. Run forward_backward on each micro-batch, weighted by its share of the samples (PyTRIO's built-in ppo loss, clip ε=0.2);
  6. Call optim_step once for the whole batch.

A batch is packed into several micro-batches, and the gradients are accumulated after forward_backward on each one; the accumulated result equals the mean over all samples only if the advantage of the k-th micro-batch is multiplied by n_k / N.

weight = np.float32(len(micro_batch) / total_samples)
advantages = inputs["advantages"].to_numpy() * weight

Results

Smoke test

Before the real run, run 2 steps with 4 questions × 4 samples each to confirm that prompt assembly, reward scoring and remote training all work:

uv run python experiments/toolrl/train.py --max-steps 2 --questions-per-batch 4 --group-size 4 --save-every 0 --swanlab-mode disabled

Step 0 prints the end of the prompt and the first sample (most of the reasoning and the <response> are omitted below):

可用训练样本 3899 条(prompt ≤ 2048 tokens)
============================== prompt 末尾(含特殊符号)==============================
<user> Please fetch the drivers from the 2019 F1 season and the next set of supported coins using the cursor 'next_page'. </user><|im_end|>
<|im_start|>assistant

============================== 第一条采样 ==============================
<think>
...
Let me make both tool calls simultaneously.
</think>

<tool_call>
{"name": "drivers", "parameters": {"season_id": 2019}}
</tool_call>
<tool_call>
{"name": "get_supported_coins_handler", "parameters": {"cursor": "next_page"}}
</tool_call>
<response>
Sure! Here are the results for your requests:
...
</response>
stop_reason='stop' reward=RewardResult(reward=0.0, format_reward=0.0, correct_reward=0.0, exact_match=False)
========================================================================
step=1/2 time=20.4s loss=0.0549 datums=16 reward=1.764 format=0.500 correct=1.264 exact=0.500 degenerate=0.00
step=2/2 time=27.2s loss=0.1941 datums=12 reward=2.250 format=0.625 correct=1.625 exact=0.438 degenerate=0.25
Saved sampler weights: trio://run_ediuxk7gmpwi/sampler_weights/toolrl-qwen35-4b-final-weights

This output confirms three things:

  • The prompt ends with <|im_start|>assistant\n, and the first sample writes <think> on its own;
  • Sampling, scoring, forward_backward and saving weights all work, at about 24 seconds per step; datums is the number of samples actually used for training after dropping those with zero advantage (16 at most);
  • With the </think> newline normalization on, the format reward is no longer always 0: the format pass rate is 50% and 62.5% in the two steps, so the model gets a format signal from the very first step.

The first sample also shows the two most typical problems of the base model: the two calls are written as two <tool_call> blocks, and a <response> is made up after the tool calls, so its format reward is 0. RL training fixes both problems; see "Test-set evaluation" below.

Smoke-test cost: ¥0.15.

20-step training

Training curves

Format pass rate, exact match, generation length and degenerate group rate over 20 training steps

The format pass rate rises above 90% around step 4, so the model learns the correct format very quickly; the exact-match rate is noisy but trends upward; the generation length falls from about 195 to about 130 tokens; and the degenerate group rate gradually climbs to about 0.75, which means most questions provide no training signal late in training.

Test-set evaluation

Format pass rate and exact match of the base model, Step 10 and Step 20 on the 80 test samples

The format pass rate goes from 30% before training to 90% after; exact match goes from 30% to 60% (Step 20 weights: 22 newly correct and 1 lost among the 70 samples). On the 10 samples that only need a reply (ground truth with only <response>), the format pass rate only goes from 10% to 20% (1 → 2 samples). It stays low: the model prefers calling a tool over writing a text reply.

Counts of format problems and average generation length for the base model, Step 10 and Step 20

Outputs with several <tool_call> blocks fall from 32 to 0, so the model learns to put all calls in a single <tool_call>; made-up <response> text after a tool call falls from 24 to 0, so the output becomes cleaner; and the average generation length steadily drops from 272 to 142.

BFCL evaluation

BFCL v4 Non-Live subset, greedy decoding, scored with our own AST checker (see bfcl_checker.py); the results cannot be compared directly with the official leaderboard:

CategoryQuestionsBaseStep 10Step 20
simple_python40091.0%91.0%90.2%
multiple20092.0%93.5%94.0%
parallel20023.0%87.0%89.5%
parallel_multiple20013.0%84.5%88.5%
Non-Live AST average54.8%89.0%90.6%
irrelevance24087.1%82.5%82.5%
Average generation length (tokens)278161147

Accuracy of the base model, Step 10 and Step 20 on each BFCL Non-Live category

Almost all of the gain comes from the two parallel categories. The base model splits several calls into several <tool_call> blocks in 349 outputs; the official handler parses only the last block, so 322 of them are marked as having the wrong number of calls. Step 20 produces no multi-block outputs. Simple and multiple were already above 90% and barely change. Irrelevance drops from 87.1% to 82.5%, with errors of the "called a tool when it should not have" kind rising from 31 to 42, consistent with the "prefers calling a tool" behavior on the test split. This shows that these 20 training steps mainly fix the output protocol rather than the ability to pick functions and fill in parameters.

Ablation: prefilling <think>

The main experiment's prompt matches the official setup: it stops at <|im_start|>assistant\n and the model writes <think> itself. The alternative is to turn on Qwen3.5's thinking rendering so the prompt ends with <think>\n and the model continues straight into its reasoning, which waives the "write <think>" part of the format reward. With the --think-prefill flag and all other arguments unchanged, we trained 20 steps as a comparison:

MetricBase, no prefillBase, prefillStep 20, no prefill (main)Step 20, prefill
Test format pass rate30.0%31.2%90.0%88.8%
Test exact match30.0%30.0%60.0%61.4%
BFCL Non-Live AST average54.8%55.0%90.6%90.5%
BFCL irrelevance87.1%86.7%82.5%86.2%
BFCL average generation length (tokens)278283147218

Accuracy and average generation length with and without prefilling <think>, on the test split and BFCL

  • Without prefill, every output of the base model on both the test split and BFCL starts with <think> on its own, so "write <think>" is no obstacle for Qwen3.5.
  • Tool-calling accuracy is essentially the same on both sides: of the 70 tool-call samples in the test split, both versions get the same 41 right, only the no-prefill version gets 1 more, and only the prefill version gets 2 more; the BFCL AST average differs by only 0.1 percentage points.
  • After training, the prefill version thinks longer: its average BFCL generation length is 218 tokens versus 147 without prefill. Irrelevance accuracy is 86.2% with prefill and 82.5% without (of the 240 questions, 10 are right only with prefill and 1 only without), and almost all of the extra errors without prefill are tool calls where none should be made. Because each setting was trained only once, this gap may also come from training randomness.

The comparison shows that prefilling does not affect tool-calling accuracy. In this experiment, prefilling kept the reasoning longer and did better on irrelevance, but the main experiment still stays consistent with the official setup.

Cost

All costs come from the hourly bills in the PyTRIO console, and durations come from the start and end times recorded by SwanLab.

ItemScaleDurationCost
20-step training + base-model test evaluation (main: no <think> prefill, newline normalization)20 steps × 32 questions × 4 samples; 80 samplesTraining about 12 minutes¥7.72
Step 10 / Step 20 test evaluation + BFCL Non-Live evaluation × 3 (main)80 samples × 2; 1,240 questions × 3—¥7.17
2-step smoke test (main settings)2 steps × 4 questions × 4 samplesAbout 1 minute¥0.15
20-step training (ablation: <think> prefill)20 steps × 32 questions × 4 samplesAbout 26 minutes¥7.90
Step 10 / Step 20 test evaluation (ablation)80 samples × 2—¥0.33
BFCL Non-Live evaluation × 3 (ablation)1,240 questions × 3—¥7.69
20-step training (official strict format, control)20 steps × 32 questions × 4 samplesAbout 17 minutes¥9.63
2-step smoke test (ablation settings)2 steps × 4 questions × 4 samplesAbout 1 minute¥0.15
Base evaluation, <think> handling comparison, 2-step smoke tests (early debugging)80 test samples × several runs—¥0.58

The bills are aggregated by hour, and tasks within the same hour cannot be separated, so the main experiment's training and base-model evaluation share one row, and the Step 10 / Step 20 evaluations and the BFCL evaluations share another. The main experiment's training and all of its evaluations total ¥14.89 (excluding the smoke test). One 20-step training run costs about ¥7.5–10, or about ¥0.4–0.5 per step. At this price, a full 200-step run would cost about ¥80–100; raising the group size from 4 to 8 doubles both the sampled and trained tokens, so the cost roughly doubles too.

Which metrics matter most during training?

MetricWhat question does it answer?
reward/meanIs the total reward going up?
reward/format_pass_rateHas the model learned the required output format (especially a single <tool_call> block and no made-up <response> after a tool call)?
reward/correctAre tool names, parameter names and parameter values getting more accurate?
reward/exact_matchHow many replies are completely correct?
train/degenerate_group_rateHow many questions provide no within-group training signal?
rollout/gen_lenIs the reasoning getting longer or shorter? The paper found that encouraging long reasoning hurts
rollout/truncated_rateAre any replies cut off by max_tokens?

What are the limits of this reproduction?

First, the model is Qwen3.5-4B, fine-tuned with LoRA, with only 1/16 of the official questions per step, so the absolute numbers cannot be compared with the tables in the paper.

Second, out-of-distribution evaluation covers only the Non-Live subset of BFCL v4 (1,240 questions); Live, Multi-turn, API-Bank and Bamboogle were not tested. Scoring uses our own AST checker (bfcl_checker.py) rather than the official leaderboard pipeline, so the scores cannot be compared directly with the paper or the leaderboard.

Third, training was run only once, without multiple random seeds.

Summary

ToolRL leaves GRPO itself unchanged and instead splits the tool-calling reward into a format reward and a correctness reward, with correctness further broken down into tool names, parameter names and parameter values, so the model can compare which of several samples for the same question calls tools more accurately. This chapter reproduces it on PyTRIO with Qwen3.5-4B and LoRA, with a prompt that matches the official setup (the model writes <think> itself) and a reward function ported line by line from the official code; the only change is that the double newline Qwen3.5 tends to write after </think> is normalized to a single newline before scoring.

After 20 training steps, the format pass rate and exact-match rate on the test split rise clearly, and so does the BFCL Non-Live AST average, but the gain comes mainly from the parallel categories: the model learns to put several calls into one <tool_call> block, while its ability to pick functions and fill in parameters changes little. At the same time, the model tends to call a tool in every case: the format pass rate on samples that only need a reply stays low, and BFCL irrelevance drops from 87.1% to 82.5%. A single training run, 80 test samples and our own BFCL scoring are not enough to show a stable gain; for longer runs, we suggest raising the group size from 4 to 8 to reduce degenerate groups that carry no training signal.

References

Paper and official implementation

  1. Cheng Qian et al. ToolRL: Reward is All Tool Learning Needs, 2025.
  2. qiancheng0/ToolRL

Data and model

  1. ToolRL rlla_4k data
  2. Qwen/Qwen3.5-4B

This implementation

  1. Full ToolRL PyTRIO code
  2. PyTRIO documentation
  3. SwanLab documentation
ZB

Zhanbo Chen

Java Backend & AI Agent Developer

Back to home
Comments