Files
trinity-rl/envs/nemotron_tool_calling/tests/test_native.py
T
carsten 84d7fe4166 Trinity-Mini RL: envs, production recipe, and run scripts
Migrated from the rl-toolkit snapshot deployed for the 2026-09-15 production
run (toolkit e191cf1 plus uncommitted changes). PRIME-RL is now a submodule on
dphn/prime-rl@trinity; the v0 envs, parity tests, OPD experiment, and old
configs are not carried over.
2026-10-14 12:39:23 +00:00

367 lines
12 KiB
Python

import json
import pytest
from aiohttp import web
from nemotron_guard_v1 import AntiHackingConfig
from nemotron_tool_calling_v1 import (
NemotronToolCallingConfig,
NemotronToolCallingData,
NemotronToolCallingTask,
NemotronToolCallingTaskConfig,
)
from nemotron_tool_calling_v1.calls import predicted_calls, structural_call_score
from nemotron_tool_calling_v1.prompt import prepare_prompt
from nemotron_tool_calling_v1.taskset import build_row
from pydantic import ValidationError
from verifiers.v1 import Agent, AgentConfig
from verifiers.v1.clients import EvalClient
from verifiers.v1.graph import MessageNode
from verifiers.v1.loaders import default_harness_id
from verifiers.v1.trace import Trace, TraceTask
from verifiers.v1.types import AssistantMessage, ToolCall
GOLD = {"type": "function_call", "name": "book_flight", "arguments": {"dest": "Paris"}}
TOOL = {
"name": "book_flight",
"description": "Book a flight.",
"parameters": {
"type": "object",
"properties": {"dest": {"type": "string"}},
"required": ["dest"],
"additionalProperties": False,
},
}
CALL = '<tool_call>{"name":"book_flight","arguments":{"dest":"Paris"}}</tool_call>'
def task():
return NemotronToolCallingTask(
NemotronToolCallingData(
prompt="Book a flight to Paris.", expected_action=GOLD, tool_defs=[TOOL]
),
NemotronToolCallingTaskConfig(
guard=AntiHackingConfig(
enable_judges=False,
reasoning_required=True,
allow_renderer_stripped_tool_calls=True,
)
),
)
def trace_for(message):
t = task()
return t, Trace(
task=TraceTask(type=type(t).__name__, data=t.data),
nodes=[MessageNode(parent=None, message=message, sampled=True)],
)
@pytest.mark.parametrize(
"content",
[
json.dumps(GOLD),
"```json\n" + json.dumps(GOLD) + "\n```",
"```json\n[" + json.dumps(GOLD) + "]\n```",
CALL,
'<function name="book_flight">{"dest":"Paris"}</function>',
'_call:book_flight{"dest":"Paris"}',
'<|tool_call|>call:book_flight{dest: "Paris"}<|tool_call|>',
"No.",
],
)
@pytest.mark.asyncio
async def test_text_never_becomes_a_call_or_reward(content):
t, trace = trace_for(
AssistantMessage(
content=content, reasoning_content="Choose the requested action."
)
)
assert predicted_calls(trace.assistant_messages) == []
assert await t.guarded_reward(trace) == 0
assert await t.emitted_tool_call(trace) == 0
@pytest.mark.parametrize(
"arguments",
[
"{'dest':'Paris'}",
'{dest:"Paris"}',
"[]",
"null",
"42",
'"Paris"',
'{"dest":"Paris","dest":"London"}',
'{"dest":NaN}',
'{"dest":Infinity}',
'{"dest":"Paris"',
],
)
def test_invalid_native_arguments_invalidate_the_whole_action(arguments):
message = AssistantMessage(
tool_calls=[
ToolCall(id="good", name="book_flight", arguments='{"dest":"Paris"}'),
ToolCall(id="bad", name="book_flight", arguments=arguments),
]
)
assert predicted_calls([message]) == []
@pytest.mark.parametrize(
"calls,expected",
[
([{"name": "book_flight", "arguments": {"dest": "Paris"}}], 1),
([{"name": "book_flight", "arguments": {"dest": "London"}}], 0),
([{"name": "wrong", "arguments": {"dest": "Paris"}}], 0),
([GOLD, GOLD], 0),
([GOLD, {"name": "wrong", "arguments": {}}], 0),
],
)
def test_exactly_one_correct_action(calls, expected):
assert structural_call_score(calls, GOLD) == expected
def test_boolean_is_not_an_integer_argument():
assert (
structural_call_score(
[{"name": "f", "arguments": {"x": True}}],
{"name": "f", "arguments": {"x": 1}},
)
== 0
)
def test_message_targets_cannot_be_enabled():
with pytest.raises(ValidationError):
NemotronToolCallingConfig(exclude_message_actions=False)
row = {
"responses_create_params": {
"input": [{"role": "user", "content": "Hello"}],
"tools": [TOOL],
},
"expected_action": {"type": "message"},
}
assert build_row(row, "tool_use_pivot", None, True) is None
with pytest.raises(ValueError, match="exclude_message_actions"):
build_row(row, "tool_use_pivot", None, False)
def test_native_schema_and_history_are_separate_from_prompt_instructions():
payload = {
"input": [
{"role": "user", "content": "Book it."},
{
"type": "function_call",
"call_id": "old",
"name": "book_flight",
"arguments": '{"dest":"Paris"}',
},
{"type": "function_call_output", "call_id": "old", "output": "Booked."},
],
"tools": [{"type": "function", "function": TOOL}],
}
prompt, tools = prepare_prompt(payload, None)
assert tools == [TOOL]
assert [m["role"] for m in prompt] == ["user", "assistant", "tool"]
assert prompt[1]["tool_calls"][0]["name"] == "book_flight"
assert prompt[2]["tool_call_id"] == "old"
assert "available_actions" not in json.dumps(prompt)
assert "```" not in json.dumps(prompt)
assert default_harness_id("nemotron-tool-calling-v1") == "nemotron-tool-calling-v1"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"kind,reward", [("native", 1), ("fenced", 0), ("invalid", 0), ("length", 0)]
)
async def test_one_action_through_real_interception(kind, reward):
requests = []
async def completion(request):
requests.append(await request.json())
message = {
"role": "assistant",
"content": "",
"reasoning_content": "The requested destination is Paris.",
}
finish = "tool_calls"
if kind == "fenced":
message["content"] = "```json\n" + json.dumps(GOLD) + "\n```"
finish = "stop"
else:
message["tool_calls"] = [
{
"id": "call1",
"type": "function",
"function": {
"name": "book_flight",
"arguments": "[]" if kind == "invalid" else '{"dest":"Paris"}',
},
}
]
if kind == "length":
finish = "length"
return web.json_response(
{
"id": "test-completion",
"object": "chat.completion",
"created": 0,
"model": "test",
"choices": [{"index": 0, "message": message, "finish_reason": finish}],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 10,
"total_tokens": 20,
},
}
)
app = web.Application()
app.router.add_post("/v1/chat/completions", completion)
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, "127.0.0.1", 0).start()
client = EvalClient(
base_url=f"http://127.0.0.1:{runner.addresses[0][1]}/v1", api_key="test-only"
)
try:
config = AgentConfig(
model="test",
harness={
"id": "nemotron-tool-calling-v1",
"runtime": {"type": "subprocess"},
},
)
async with Agent(config, client=client) as agent:
trace = await agent.run(task())
assert trace.ok, trace.errors
assert trace.stop_condition == "agent_completed"
assert trace.num_turns == 1
assert len(trace.calls) == len(requests) == 1
assert trace.reward == reward
assert requests[0]["tools"] == [{"type": "function", "function": TOOL}]
assert requests[0]["tool_choice"] == "auto"
assert "expected_action" not in json.dumps(requests[0])
assert len(trace.tools) == 1 and trace.tools[0].name == "book_flight"
assert not any(node.message.role == "tool" for node in trace.nodes)
assert "unknown tool" not in trace.model_dump_json()
finally:
await client.close()
await runner.cleanup()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"kind,reward",
[
("native", 1),
("fenced", 0),
("reasoning_example", 0),
("unclosed_reasoning", 0),
("extra_call", 0),
],
)
async def test_training_client_with_real_tokenizer_and_token_capture(kind, reward):
from pathlib import Path
from huggingface_hub import hf_hub_download
from openai import AsyncOpenAI
from renderers.configs import DefaultRendererConfig
from transformers import AutoTokenizer
from verifiers.v1.clients import TrainClient
snapshot = str(
Path(
hf_hub_download(
"arcee-ai/Trinity-Mini",
"tokenizer_config.json",
revision="cdb81e8130815fec299cccc8f8700004b8366e1e",
)
).parent
)
tokenizer = AutoTokenizer.from_pretrained(snapshot, trust_remote_code=False)
outputs = {
"native": "The destination is Paris.</think>" + CALL,
"fenced": "The destination is Paris.</think>```json\n"
+ json.dumps(GOLD)
+ "\n```",
"reasoning_example": "An example would be " + CALL + ".</think>No.",
"unclosed_reasoning": "An example would be " + CALL,
"extra_call": "The destination is Paris.</think>" + CALL + CALL,
}
completion_ids = tokenizer.encode(outputs[kind], add_special_tokens=False)
requests = []
async def models(request):
return web.json_response(
{
"object": "list",
"data": [
{
"id": "test",
"object": "model",
"created": 0,
"owned_by": "test",
"max_model_len": 32768,
}
],
}
)
async def generate(request):
requests.append(await request.json())
return web.json_response(
{
"choices": [
{
"token_ids": completion_ids,
"finish_reason": "stop",
"logprobs": {
"content": [{"logprob": -0.1} for _ in completion_ids]
},
}
]
}
)
app = web.Application()
app.router.add_get("/v1/models", models)
app.router.add_post("/inference/v1/generate", generate)
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, "127.0.0.1", 0).start()
client = TrainClient(
AsyncOpenAI(
base_url=f"http://127.0.0.1:{runner.addresses[0][1]}/v1",
api_key="test-only",
),
config=DefaultRendererConfig(tool_parser="hermes", reasoning_parser="think"),
renderer_model_name=snapshot,
)
try:
config = AgentConfig(
model="test",
harness={
"id": "nemotron-tool-calling-v1",
"runtime": {"type": "subprocess"},
},
)
async with Agent(config, client=client) as agent:
trace = await agent.run(task())
assert trace.ok, trace.errors
assert trace.num_turns == len(trace.calls) == len(requests) == 1
assert trace.stop_condition == "agent_completed"
assert trace.reward == reward
assert trace.tools[0].name == "book_flight"
prompt = tokenizer.decode(requests[0]["token_ids"], skip_special_tokens=False)
assert "<tools>" in prompt and "book_flight" in prompt
assert "available_actions" not in prompt and "```json" not in prompt
sampled = [n for n in trace.nodes if n.sampled]
assert len(sampled) == 1
assert sampled[0].token_ids[-len(completion_ids) :] == completion_ids
assert len(sampled[0].logprobs) == len(completion_ids)
assert not any(n.message.role == "tool" for n in trace.nodes)
finally:
await client.close()
await runner.cleanup()