Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,13 @@ NeMo Gym includes a curated collection of environments for training and evaluati
Purpose: Demonstrate NeMo Gym patterns and concepts.

<!-- START_EXAMPLE_ONLY_SERVERS_TABLE -->
| Name | Demonstrates | Config | README |
| -------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| Multi Step | Multi-step tool calling | <a href='resources_servers/example_multi_step/configs/example_multi_step.yaml'>example_multi_step.yaml</a> | <a href='resources_servers/example_multi_step/README.md'>README</a> |
| Multi Turn Gymnasium | Example multi-turn environment using Gymnasium | <a href='resources_servers/example_multi_turn_gymnasium/configs/example_multi_turn_gymnasium.yaml'>example_multi_turn_gymnasium.yaml</a> | <a href='resources_servers/example_multi_turn_gymnasium/README.md'>README</a> |
| Session State Mgmt | Session state management (in-memory) | <a href='resources_servers/example_session_state_mgmt/configs/example_session_state_mgmt.yaml'>example_session_state_mgmt.yaml</a> | <a href='resources_servers/example_session_state_mgmt/README.md'>README</a> |
| Single Tool Call | Basic single-step tool calling | <a href='resources_servers/example_single_tool_call/configs/example_single_tool_call.yaml'>example_single_tool_call.yaml</a> | <a href='resources_servers/example_single_tool_call/README.md'>README</a> |
| Name | Demonstrates | Config | README |
| --------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| Multi Step | Multi-step tool calling | <a href='resources_servers/example_multi_step/configs/example_multi_step.yaml'>example_multi_step.yaml</a> | <a href='resources_servers/example_multi_step/README.md'>README</a> |
| Multi Turn Gymnasium | Example multi-turn environment using Gymnasium | <a href='resources_servers/example_multi_turn_gymnasium/configs/example_multi_turn_gymnasium.yaml'>example_multi_turn_gymnasium.yaml</a> | <a href='resources_servers/example_multi_turn_gymnasium/README.md'>README</a> |
| Session State Mgmt | Session state management (in-memory) | <a href='resources_servers/example_session_state_mgmt/configs/example_session_state_mgmt.yaml'>example_session_state_mgmt.yaml</a> | <a href='resources_servers/example_session_state_mgmt/README.md'>README</a> |
| Single Tool Call | Basic single-step tool calling | <a href='resources_servers/example_single_tool_call/configs/example_single_tool_call.yaml'>example_single_tool_call.yaml</a> | <a href='resources_servers/example_single_tool_call/README.md'>README</a> |
| Tool Call Multireward | Single tool call scored on decoupled correctness / schema_valid / format rewards (multi-reward, for GDPO) | <a href='resources_servers/example_tool_call_multireward/configs/example_tool_call_multireward.yaml'>example_tool_call_multireward.yaml</a> | <a href='resources_servers/example_tool_call_multireward/README.md'>README</a> |
<!-- END_EXAMPLE_ONLY_SERVERS_TABLE -->

### Environments for Training & Evaluation
Expand Down
29 changes: 29 additions & 0 deletions resources_servers/example_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 `example_tool_call_multireward/data/example.jsonl` and is
regenerated with `python resources_servers/example_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/example_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,22 @@
example_tool_call_multireward:
resources_servers:
example_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)
Comment thread
cmunley1 marked this conversation as resolved.
Resolved
value: Reference pattern for multi-reward (GDPO) agentic RL with decoupled per-objective rewards
example_tool_call_multireward_simple_agent:
responses_api_agents:
simple_agent:
entrypoint: app.py
resources_server:
type: resources_servers
name: example_tool_call_multireward
model_server:
type: responses_api_models
name: policy_model
datasets:
- name: example
type: example
jsonl_fpath: resources_servers/example_tool_call_multireward/data/example.jsonl
75 changes: 75 additions & 0 deletions resources_servers/example_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/example_tool_call_multireward/data/example.jsonl", "w") as f:
f.writelines(example_strs)
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{"responses_create_params": {"input": [{"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.", "role": "developer"}, {"content": "what's the weather in San Francisco?", "role": "user"}], "tools": [{"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "The city to get the weather for."}}, "required": ["city"], "additionalProperties": false}, "strict": true, "type": "function", "description": "Get the current weather for a city."}]}, "expected_call": {"name": "get_weather", "arguments": {"city": "San Francisco"}}}
{"responses_create_params": {"input": [{"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.", "role": "developer"}, {"content": "how hot is it in New York today?", "role": "user"}], "tools": [{"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "The city to get the weather for."}}, "required": ["city"], "additionalProperties": false}, "strict": true, "type": "function", "description": "Get the current weather for a city."}]}, "expected_call": {"name": "get_weather", "arguments": {"city": "New York"}}}
{"responses_create_params": {"input": [{"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.", "role": "developer"}, {"content": "tell me the forecast for Seattle", "role": "user"}], "tools": [{"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "The city to get the weather for."}}, "required": ["city"], "additionalProperties": false}, "strict": true, "type": "function", "description": "Get the current weather for a city."}]}, "expected_call": {"name": "get_weather", "arguments": {"city": "Seattle"}}}
{"responses_create_params": {"input": [{"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.", "role": "developer"}, {"content": "is it raining in London right now?", "role": "user"}], "tools": [{"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "The city to get the weather for."}}, "required": ["city"], "additionalProperties": false}, "strict": true, "type": "function", "description": "Get the current weather for a city."}]}, "expected_call": {"name": "get_weather", "arguments": {"city": "London"}}}
{"responses_create_params": {"input": [{"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.", "role": "developer"}, {"content": "weather in Tokyo please", "role": "user"}], "tools": [{"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "The city to get the weather for."}}, "required": ["city"], "additionalProperties": false}, "strict": true, "type": "function", "description": "Get the current weather for a city."}]}, "expected_call": {"name": "get_weather", "arguments": {"city": "Tokyo"}}}
Loading
Loading