Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ The Dataset column links to publicly available datasets (e.g., on HuggingFace).
| Terminus Judge | agent | single-step terminal based task (simple judge prompt) | Improve on terminal-style tasks | ✓ | ✓ | Apache 2.0 | <a href='resources_servers/terminus_judge/configs/terminus_judge_simple.yaml'>terminus_judge_simple.yaml</a> | - |
| Terminus Judge | agent | single-step terminal based task (string similarity only) | Improve on terminal-style tasks | ✓ | ✓ | Apache 2.0 | <a href='resources_servers/terminus_judge/configs/terminus_judge_string_only.yaml'>terminus_judge_string_only.yaml</a> | - |
| Text To Sql | coding | Text-to-SQL generation with LLM-as-a-judge equivalence checking | Improve text-to-SQL capabilities across multiple dialects | - | - | - | <a href='resources_servers/text_to_sql/configs/text_to_sql.yaml'>text_to_sql.yaml</a> | - |
| Tool Call Multireward | agent | Single tool call scored on decoupled correctness / schema_valid / format rewards (multi-reward, for GDPO) | - | - | - | - | <a href='resources_servers/tool_call_multireward/configs/tool_call_multireward.yaml'>tool_call_multireward.yaml</a> | - |
| Ugphysics Judge | knowledge | Undergraduate physics QA verified by a TRUE/FALSE LLM judge with math-verify symbolic fallback | Score undergraduate-physics benchmarks (e.g. UGPhysics) where the judge is a TRUE/FALSE equivalence grader using a reference solution | - | - | - | <a href='resources_servers/ugphysics_judge/configs/ugphysics_judge.yaml'>ugphysics_judge.yaml</a> | - |
| Verifiers Agent | math | Prime intellect verifiers and environments hub integration, ace-reason math environment example. | Improve math reasoning capabilities. | ✓ | - | - | <a href='responses_api_agents/verifiers_agent/configs/acereason-math.yaml'>acereason-math.yaml</a> | - |
| Verifif | instruction_following | VerifIF instruction following validators with rule-based and LLM judge support | Improve instruction following capabilities with comprehensive validation | - | - | - | <a href='resources_servers/verifif/configs/verifif.yaml'>verifif.yaml</a> | - |
Expand Down
29 changes: 29 additions & 0 deletions resources_servers/tool_call_multireward/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Description

A single-tool-call environment that returns **multiple decoupled reward components**,
intended for multi-reward RL such as GDPO (https://arxiv.org/abs/2601.05242).

Each rollout asks the model to call `get_weather` for a city. The verifier scores the
response on three independent `{0, 1}` components:

- `correctness` — a predicted call matches the expected name and arguments.
- `schema_valid` — the call's arguments parse as a JSON object containing every required
parameter of the tool.
- `format` — exactly one tool call was emitted, with no extra assistant text.

These are returned in the `reward_components` field of the verify response (in addition
to the summed scalar `reward`). NeMo-RL's NeMo Gym bridge exposes them as
`reward1, reward2, ...` (ordered by component name: `correctness`, `format`,
`schema_valid`) for the GDPO advantage estimator. A GRPO baseline reads the summed
`reward` and therefore cannot distinguish responses with the same total but different
composition — the advantage collapse GDPO is designed to fix.

The example data can be found in `tool_call_multireward/data/example.jsonl` and is
regenerated with `python resources_servers/tool_call_multireward/create_examples.py`.

# Licensing information
Code: Apache 2.0
Data: Apache 2.0

Dependencies
- nemo_gym: Apache 2.0
157 changes: 157 additions & 0 deletions resources_servers/tool_call_multireward/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single-tool-call environment scored on three decoupled reward components.

This is a multi-reward environment intended for GDPO
(https://arxiv.org/abs/2601.05242). A single expected tool call is graded on three
independent {0, 1} components:

- ``correctness`` : a predicted call matches the expected name + expected arguments.
- ``schema_valid`` : the call's arguments parse as a JSON object containing every
required parameter of the tool.
- ``format`` : exactly one tool call was emitted and no extra assistant text.

These decouple: a response can be well-formed but wrong, correct but malformed, etc.
GDPO normalizes each component independently, so two responses with the same total
reward but different composition receive different advantages (whereas GRPO, which
normalizes the summed reward, collapses them).

The components are returned in ``reward_components``; NeMo-RL exposes them as reward1,
reward2, ... ordered by component name (correctness, format, schema_valid). ``reward``
is set to the sum so a single-reward (GRPO) baseline reads the same aggregate.
"""

import json
from typing import Any, Dict, List

from pydantic import Field

from nemo_gym.base_resources_server import (
BaseResourcesServerConfig,
BaseVerifyRequest,
BaseVerifyResponse,
SimpleResourcesServer,
)


class ToolCallMultiRewardResourcesServerConfig(BaseResourcesServerConfig):
pass


class ToolCallMultiRewardVerifyRequest(BaseVerifyRequest):
# The single tool call the model is expected to make, e.g.
# {"name": "get_weather", "arguments": {"city": "San Francisco"}}.
expected_call: Dict[str, Any] = Field(default_factory=dict)


class ToolCallMultiRewardVerifyResponse(BaseVerifyResponse):
# Per-component scores are also surfaced as top-level fields so the aggregate
# metrics endpoint profiles each one in addition to the combined reward.
# Decoupled per-component rewards (name -> score) for GDPO. NeMo-RL's NeMo Gym
# bridge reads this from the verify result and exposes the components as reward1,
# reward2, ... ordered by name. Defined here (not on BaseVerifyResponse) so other
# environments' verify responses are unchanged.
reward_components: Dict[str, float] | None = None
correctness: float = 0.0
schema_valid: float = 0.0
format: float = 0.0
predicted_calls: List[Dict[str, Any]] = Field(default_factory=list)


class ToolCallMultiRewardResourcesServer(SimpleResourcesServer):
config: ToolCallMultiRewardResourcesServerConfig

@staticmethod
def _parse_arguments(arguments: Any) -> tuple[Dict[str, Any], bool]:
"""Return (parsed_dict, is_valid_json_object)."""
if isinstance(arguments, dict):
return arguments, True
if isinstance(arguments, str):
try:
value = json.loads(arguments)
except json.JSONDecodeError:
return {}, False
return (value, True) if isinstance(value, dict) else ({}, False)
return {}, False

def _extract_function_calls(self, body: BaseVerifyRequest) -> List[Dict[str, Any]]:
calls = []
for output_item in body.response.output:
if output_item.type == "function_call":
calls.append({"name": output_item.name, "arguments": output_item.arguments})
return calls

@staticmethod
def _has_assistant_text(body: BaseVerifyRequest) -> bool:
return any(getattr(item, "type", None) == "message" for item in body.response.output)

def _required_params(self, body: BaseVerifyRequest, tool_name: str) -> List[str]:
tools = getattr(body.responses_create_params, "tools", None) or []
for tool in tools:
tool_dict = tool if isinstance(tool, dict) else tool.model_dump()
if tool_dict.get("name") == tool_name:
return tool_dict.get("parameters", {}).get("required", []) or []
return []

@staticmethod
def _call_matches(predicted: Dict[str, Any], expected: Dict[str, Any]) -> bool:
if not expected:
return False
if predicted.get("name") != expected.get("name"):
return False
predicted_args, _ = ToolCallMultiRewardResourcesServer._parse_arguments(predicted.get("arguments", {}))
expected_args = expected.get("arguments", {}) or {}
for key, value in expected_args.items():
if predicted_args.get(key) != value:
return False
return True

async def verify(self, body: ToolCallMultiRewardVerifyRequest) -> ToolCallMultiRewardVerifyResponse:
predicted_calls = self._extract_function_calls(body)

# format: exactly one tool call and no extra assistant prose.
format_score = 1.0 if len(predicted_calls) == 1 and not self._has_assistant_text(body) else 0.0

# schema_valid: the first call's arguments are a valid object with all required params.
schema_score = 0.0
if predicted_calls:
first = predicted_calls[0]
parsed, is_valid = self._parse_arguments(first["arguments"])
required = self._required_params(body, first["name"])
schema_score = 1.0 if is_valid and all(k in parsed for k in required) else 0.0

# correctness: some predicted call matches the expected name + arguments.
correctness_score = 1.0 if any(self._call_matches(c, body.expected_call) for c in predicted_calls) else 0.0

reward_components = {
"correctness": correctness_score,
"schema_valid": schema_score,
"format": format_score,
}

return ToolCallMultiRewardVerifyResponse(
**body.model_dump(),
reward=sum(reward_components.values()),
reward_components=reward_components,
correctness=correctness_score,
schema_valid=schema_score,
format=format_score,
predicted_calls=[
{"name": c["name"], "arguments": self._parse_arguments(c["arguments"])[0]} for c in predicted_calls
],
)


if __name__ == "__main__":
ToolCallMultiRewardResourcesServer.run_webserver()
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
tool_call_multireward:
Comment thread
cmunley1 marked this conversation as resolved.
Resolved
resources_servers:
tool_call_multireward:
entrypoint: app.py
domain: agent
verified: false
description: Single tool call scored on decoupled correctness / schema_valid / format rewards (multi-reward, for GDPO)
tool_call_multireward_simple_agent:
responses_api_agents:
simple_agent:
entrypoint: app.py
resources_server:
type: resources_servers
name: tool_call_multireward
model_server:
type: responses_api_models
name: policy_model
datasets:
- name: example
type: example
jsonl_fpath: resources_servers/tool_call_multireward/data/example.jsonl
75 changes: 75 additions & 0 deletions resources_servers/tool_call_multireward/create_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json

from nemo_gym.openai_utils import (
NeMoGymEasyInputMessage,
NeMoGymResponseCreateParamsNonStreaming,
)


# (user query, expected city argument)
queries = [
("what's the weather in San Francisco?", "San Francisco"),
("how hot is it in New York today?", "New York"),
("tell me the forecast for Seattle", "Seattle"),
("is it raining in London right now?", "London"),
("weather in Tokyo please", "Tokyo"),
]

base_response_create_params = NeMoGymResponseCreateParamsNonStreaming(
input=[
{
"role": "developer",
"content": (
"You are a helpful assistant. When the user asks about the weather, "
"respond with exactly one get_weather tool call and no other text."
),
},
],
tools=[
{
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city to get the weather for.",
},
},
"required": ["city"],
"additionalProperties": False,
},
"strict": True,
}
],
)

example_strs = []
for query, city in queries:
example = base_response_create_params.model_copy(
update={"input": base_response_create_params.input + [NeMoGymEasyInputMessage(role="user", content=query)]}
)
row = {
"responses_create_params": example.model_dump(exclude_unset=True),
"expected_call": {"name": "get_weather", "arguments": {"city": city}},
}
example_strs.append(json.dumps(row) + "\n")


with open("resources_servers/tool_call_multireward/data/example.jsonl", "w") as f:
f.writelines(example_strs)
5 changes: 5 additions & 0 deletions resources_servers/tool_call_multireward/data/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
*train.jsonl
*validation.jsonl
*train_prepare.jsonl
*validation_prepare.jsonl
*example_prepare.jsonl
Loading
Loading