Skip to content
Closed
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
88 changes: 81 additions & 7 deletions src/transformers/utils/chat_parsing/response_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,88 @@
from .response_templates import ResponseTemplate, ResponseTemplateField, load_response_template


def _schema_types(schema: Any) -> tuple[str, ...]:
def _resolve_local_ref(ref: str, root: dict[str, Any] | None) -> Any:
if not isinstance(root, dict) or not ref.startswith("#"):
return None
if ref == "#":
return root
if not ref.startswith("#/"):
return None
cur: Any = root
for part in ref[2:].split("/"):
key = part.replace("~1", "/").replace("~0", "~")
if isinstance(cur, dict) and key in cur:
cur = cur[key]
elif isinstance(cur, list) and key.isdigit():
idx = int(key)
if idx >= len(cur):
return None
cur = cur[idx]
else:
return None
return cur


def _json_value_type(value: Any) -> str | None:
if value is None:
return "null"
if isinstance(value, bool):
return "boolean"
if isinstance(value, int):
return "integer"
if isinstance(value, float):
return "number"
if isinstance(value, str):
return "string"
if isinstance(value, list):
return "array"
if isinstance(value, dict):
return "object"
return None


def _schema_types(
schema: Any, root: dict[str, Any] | None = None, _seen: frozenset[str] = frozenset()
) -> tuple[str, ...]:
if not isinstance(schema, dict):
return ()
types: list[str] = []
if isinstance(ref := schema.get("$ref"), str) and ref not in _seen:
types.extend(_schema_types(_resolve_local_ref(ref, root), root=root, _seen=_seen | {ref}))
declared = schema.get("type")
types = [declared] if isinstance(declared, str) else []
if isinstance(declared, list):
if isinstance(declared, str):
types.append(declared)
elif isinstance(declared, list):
types.extend(t for t in declared if isinstance(t, str))
for union_name in ("anyOf", "oneOf"):
for choice in schema.get(union_name) or []:
types.extend(_schema_types(choice))
types.extend(_schema_types(choice, root=root, _seen=_seen))
if branch_sets := [
bt for branch in (schema.get("allOf") or []) if (bt := _schema_types(branch, root=root, _seen=_seen))
]:
if len(branch_sets) == 1:
types.extend(branch_sets[0])
else:
narrowed = [
t
for branch_types in branch_sets
for t in branch_types
if all(t in other or (t == "integer" and "number" in other) for other in branch_sets)
]
if narrowed:
types.extend(narrowed)
else:
for branch_types in branch_sets:
types.extend(branch_types)
if "const" in schema and (val_type := _json_value_type(schema["const"])) is not None:
types.append(val_type)
if isinstance(enum_vals := schema.get("enum"), list):
for item in enum_vals:
if (val_type := _json_value_type(item)) is not None:
types.append(val_type)
if schema.get("nullable") and "null" not in types: # `nullable` is how get_json_schema marks Optionals
types.append("null")
return tuple(types)
return tuple(dict.fromkeys(types))


def _coerce(raw: str, types: tuple[str, ...]) -> Any:
Expand Down Expand Up @@ -135,8 +204,10 @@ def __init__(
"opening `<think>` tag) that the parser must see to parse the output correctly. If the generation "
'already contains the complete message, pass `prefix=""` to opt out explicitly.'
)
# Maps tool name -> schema `properties`, used to cast parsed tool-call arguments
# Maps tool name -> schema `properties` (and root `parameters` for `$ref`),
# used to cast parsed tool-call arguments.
self._tool_params: dict[str, dict] = {}
self._tool_roots: dict[str, dict] = {}
for tool in tools or []:
if isfunction(tool) or ismethod(tool):
tool = get_json_schema(tool)
Expand All @@ -145,6 +216,8 @@ def __init__(
parameters = fn.get("parameters")
properties = parameters.get("properties") if isinstance(parameters, dict) else None
self._tool_params[fn["name"]] = properties if isinstance(properties, dict) else {}
if isinstance(parameters, dict):
self._tool_roots[fn["name"]] = parameters
self._buffer: str = ""
self._pos: int = 0
self._output: dict[str, Any] = deepcopy(self._spec.defaults)
Expand Down Expand Up @@ -404,8 +477,9 @@ def _coerce_tool_calls(self, value: Any, *, typed: bool = False) -> Any:
if not isinstance(name, str) or not isinstance(arguments, dict):
return value
if properties := self._tool_params.get(name):
root = self._tool_roots.get(name)
for key, argument in arguments.items():
if key not in properties or not (types := _schema_types(properties[key])):
if key not in properties or not (types := _schema_types(properties[key], root=root)):
continue
if typed and "string" in types:
continue
Expand Down
77 changes: 77 additions & 0 deletions tests/utils/test_chat_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2170,6 +2170,83 @@ def test_tools_typed_parsers_preserve_string_schemas_and_coerce_non_string(self)
self.assertIs(type(typed_args["code"]), int)
self.assertIs(type(typed_args["flag"]), bool)

def test_schema_types_and_coerce_handle_ref_allof_const_enum(self):
root = {
"type": "object",
"$defs": {
"Port": {"type": "integer"},
"NestedPort": {"$ref": "#/$defs/Port"},
"Loop": {"$ref": "#/$defs/Loop"},
"WrappedStr": {"allOf": [{"type": "string"}], "description": "text"},
"BoundedInt": {"allOf": [{"type": "number"}, {"type": "integer"}]},
"Slash~Name": {"type": "boolean"},
},
"definitions": {"LegacyFloat": {"type": "number"}},
"properties": {
"port": {"$ref": "#/$defs/NestedPort"},
"ratio": {"$ref": "#/definitions/LegacyFloat"},
"label": {"$ref": "#/$defs/WrappedStr"},
"bounded": {"$ref": "#/$defs/BoundedInt"},
"escaped": {"$ref": "#/$defs/Slash~0Name"},
"const_flag": {"const": True},
"const_count": {"const": 5},
"const_str": {"const": "true"},
"enum_mix": {"enum": [1, "auto"]},
"loop": {"$ref": "#/$defs/Loop"},
},
}
self.assertEqual(_schema_types(root["properties"]["port"], root=root), ("integer",))
self.assertEqual(_schema_types(root["properties"]["ratio"], root=root), ("number",))
self.assertEqual(_schema_types(root["properties"]["label"], root=root), ("string",))
self.assertEqual(_schema_types(root["properties"]["bounded"], root=root), ("integer",))
self.assertEqual(_schema_types(root["properties"]["escaped"], root=root), ("boolean",))
self.assertEqual(_schema_types(root["properties"]["const_flag"], root=root), ("boolean",))
self.assertEqual(_schema_types(root["properties"]["const_count"], root=root), ("integer",))
self.assertEqual(_schema_types(root["properties"]["const_str"], root=root), ("string",))
self.assertEqual(_schema_types(root["properties"]["enum_mix"], root=root), ("integer", "string"))
self.assertEqual(_schema_types(root["properties"]["loop"], root=root), ())

tools = [{"type": "function", "function": {"name": "set_alarm", "parameters": root}}]
xml_out = (
"<tool_call>\n<function=set_alarm>\n"
"<parameter=port>\n8080\n</parameter>\n"
"<parameter=ratio>\n1.25\n</parameter>\n"
"<parameter=label>\n0123\n</parameter>\n"
"<parameter=bounded>\n42\n</parameter>\n"
"<parameter=escaped>\ntrue\n</parameter>\n"
"<parameter=const_flag>\ntrue\n</parameter>\n"
"<parameter=const_count>\n5\n</parameter>\n"
"<parameter=const_str>\ntrue\n</parameter>\n"
"<parameter=enum_mix>\n1\n</parameter>\n"
"<parameter=loop>\nkeep\n</parameter>\n"
"</function>\n</tool_call>"
)
xml_args = _first_tool_args(parse_response(xml_out, _XML_STRING_ARGS_TEMPLATE, prefix="", tools=tools))
self.assertEqual(
xml_args,
{
"port": 8080,
"ratio": 1.25,
"label": "0123",
"bounded": 42,
"escaped": True,
"const_flag": True,
"const_count": 5,
"const_str": "true",
"enum_mix": 1,
"loop": "keep",
},
)
self.assertIs(type(xml_args["const_flag"]), bool)
self.assertIs(type(xml_args["const_count"]), int)

smollm_out = (
'<tool_call>{"name": "set_alarm", "arguments": '
'{"port": "8080", "label": "0123", "const_str": "true", "enum_mix": "1"}}</tool_call>'
)
json_args = _first_tool_args(parse_response(smollm_out, smollm_template, prefix="", tools=tools))
self.assertEqual(json_args, {"port": 8080, "label": "0123", "const_str": "true", "enum_mix": "1"})


if __name__ == "__main__":
unittest.main()
Loading