Files
trinity-rl/envs/nemotron_tool_calling/nemotron_tool_calling_v1/calls.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

256 lines
8.7 KiB
Python

"""Native tool-call extraction and deterministic reference-action scoring."""
from __future__ import annotations
import json
from typing import Any
def _reject_constant(value: str) -> None:
raise ValueError(f"Non-JSON numeric constant: {value}")
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f"Duplicate JSON key: {key}")
result[key] = value
return result
def _normalize_args(args: Any) -> dict[str, Any]:
if args is None:
return {}
if isinstance(args, str):
args = json.loads(
args, parse_constant=_reject_constant, object_pairs_hook=_unique_object
)
if not isinstance(args, dict):
raise TypeError("Tool arguments must be a JSON object")
# Reject non-finite numbers even on already-decoded provider objects.
json.dumps(args, allow_nan=False)
return args
def predicted_calls(assistant_messages: list[Any]) -> list[dict[str, Any]]:
"""Read only structured tool_calls; content and reasoning are never scraped.
An invalid call invalidates the action set rather than disappearing while a
different valid call receives credit.
"""
predicted = []
for message in assistant_messages:
for call in message.tool_calls or []:
if (
not isinstance(call.name, str)
or not call.name.strip()
or call.arguments is None
):
return []
try:
arguments = _normalize_args(call.arguments)
except (ValueError, TypeError):
return []
predicted.append({"name": call.name, "arguments": arguments})
return predicted
def _call_names(calls: list[dict[str, Any]]) -> list[str]:
names: list[str] = []
for call in calls:
name, _args = _call_signature(call)
if name:
names.append(name)
return names
def _args_overlap(expected: dict[str, Any], predicted: dict[str, Any]) -> float:
if not expected:
return 1.0 if not predicted else 0.5
matched = 0
for k, v in expected.items():
if k in predicted:
if str(predicted[k]).strip() == str(v).strip():
matched += 1
elif (
str(v).strip()
and str(predicted[k]).strip()
and (
str(v).strip() in str(predicted[k]).strip()
or str(predicted[k]).strip() in str(v).strip()
)
):
matched += 0.5
return matched / max(1, len(expected))
def _strict_arg_match(expected: Any, predicted: Any) -> bool:
if type(predicted) is not type(expected):
return False
if isinstance(expected, dict):
if set(expected.keys()) != set(predicted.keys()):
return False
return all(
_strict_arg_match(value, predicted[key]) for key, value in expected.items()
)
if isinstance(expected, list):
if len(expected) != len(predicted):
return False
return all(
_strict_arg_match(exp, pred) for exp, pred in zip(expected, predicted)
)
if isinstance(expected, float):
return abs(predicted - expected) < 1e-6
if isinstance(expected, str):
return expected == predicted
return expected == predicted
def _call_signature(call: dict[str, Any]) -> tuple[str, dict[str, Any]]:
call = call if isinstance(call, dict) else {}
name = call.get("name") or (call.get("function") or {}).get("name") or ""
args = (
call.get("arguments")
if call.get("arguments") is not None
else (call.get("function") or {}).get("arguments")
)
return str(name), _normalize_args(args)
def structural_call_score(
predicted: list[dict[str, Any]], expected: dict[str, Any]
) -> float:
"""Require exactly the one native action specified by this pivot."""
name = expected.get("name") or (expected.get("function") or {}).get("name")
if not name or len(predicted) != 1:
return 0.0
exp_args = _normalize_args(
expected.get("arguments") or (expected.get("function") or {}).get("arguments")
)
call_name, call_args = _call_signature(predicted[0])
if call_name != name:
return 0.0
return 1.0 if _strict_arg_match(exp_args, call_args) else 0.0
def sequence_score(
expected_calls: list[dict[str, Any]], predicted: list[dict[str, Any]]
) -> float:
if not expected_calls:
return 1.0 if not predicted else 0.5
total = 0.0
used: set[int] = set()
for exp in expected_calls:
exp_name, exp_args = _call_signature(exp)
best = 0.0
best_idx: int | None = None
for i, pred in enumerate(predicted):
if i in used:
continue
pred_name, pred_args = _call_signature(pred)
if pred_name != exp_name:
continue
score = 0.5 + 0.5 * _args_overlap(exp_args, pred_args)
if score > best:
best = score
best_idx = i
if best_idx is not None:
used.add(best_idx)
total += best
return total / max(1, len(expected_calls))
def _name_similarity(predicted: str, expected: str) -> float:
if not predicted or not expected:
return 0.0
if predicted == expected:
return 1.0
pred_parts = predicted.split("_")
exp_parts = expected.split("_")
common = 0
for pred_part, exp_part in zip(pred_parts, exp_parts):
if pred_part != exp_part:
break
common += 1
if common:
return max(0.25, 0.7 * common / max(len(pred_parts), len(exp_parts)))
return 0.15 if pred_parts[0] == exp_parts[0] else 0.0
def _expected_calls_from_info(info: dict[str, Any] | None) -> list[dict[str, Any]]:
info = info or {}
for key in ("ground_truth_json", "expected_action_json"):
# Skip keys the row doesn't carry. Action rows have no `ground_truth_json`, so the
# old unconditional `info.get(key, "[]")` parsed "[]", returned it as a valid empty
# list, and never looked at `expected_action_json` at all — leaving the metrics that
# depend on the gold stuck at their defaults.
if key not in info:
continue
parsed = json.loads(info.get(key) or "[]")
if isinstance(parsed, dict):
return [parsed]
if isinstance(parsed, list) and parsed:
return [item for item in parsed if isinstance(item, dict)]
required_tools = json.loads(info.get("required_tools_json", "[]"))
if isinstance(required_tools, list) and required_tools:
return [{"name": str(name)} for name in required_tools if name]
target_tool = str(info.get("target_tool", "")).strip()
return [{"name": target_tool}] if target_tool else []
def _valid_tool_names_from_info(info: dict[str, Any] | None) -> set[str]:
info = info or {}
tool_defs = json.loads(info.get("tool_defs_json", "[]"))
if not isinstance(tool_defs, list):
return set()
return {
str(tool.get("name", "")).strip()
for tool in tool_defs
if isinstance(tool, dict) and tool.get("name")
}
def tool_call_shape_score(
predicted: list[dict[str, Any]], info: dict[str, Any]
) -> float:
if not predicted:
return 0.0
expected = _expected_calls_from_info(info)
valid_names = _valid_tool_names_from_info(info)
expected_names = [name for call in expected if (name := _call_signature(call)[0])]
expected_arg_sets = [_call_signature(call)[1] for call in expected]
scores: list[float] = []
for call in predicted:
name, args = _call_signature(call)
valid_score = 1.0 if not valid_names or name in valid_names else 0.0
if expected_names:
relevance = max(
_name_similarity(name, expected_name)
for expected_name in expected_names
)
else:
relevance = 0.5 if name else 0.0
if expected_arg_sets:
arg_overlap = max(
_args_overlap(exp_args, args) for exp_args in expected_arg_sets
)
expected_arg_count = max(
1, max(len(exp_args) for exp_args in expected_arg_sets)
)
else:
arg_overlap = 0.5 if args else 0.0
expected_arg_count = 3
arg_count_score = min(1.0, len(args) / expected_arg_count) if args else 0.0
scores.append(
0.35 * valid_score
+ 0.25 * arg_count_score
+ 0.25 * relevance
+ 0.15 * arg_overlap
)
call_count_score = (
min(1.0, len(predicted) / max(1, len(expected))) if expected else 1.0
)
return float(0.9 * max(scores) + 0.1 * call_count_score)