in src/smolagents/_function_type_hints_utils.py [0:0]
def _parse_type_hint(hint: type) -> dict:
origin = get_origin(hint)
args = get_args(hint)
if origin is None:
try:
return _get_json_schema_type(hint)
except KeyError:
raise TypeHintParsingException(
"Couldn't parse this type hint, likely due to a custom class or object: ",
hint,
)
elif origin is Union or (hasattr(types, "UnionType") and origin is types.UnionType):
return _parse_union_type(args)
elif origin is list:
if not args:
return {"type": "array"}
else:
# Lists can only have a single type argument, so recurse into it
return {"type": "array", "items": _parse_type_hint(args[0])}
elif origin is tuple:
if not args:
return {"type": "array"}
if len(args) == 1:
raise TypeHintParsingException(
f"The type hint {str(hint).replace('typing.', '')} is a Tuple with a single element, which "
"we do not automatically convert to JSON schema as it is rarely necessary. If this input can contain "
"more than one element, we recommend "
"using a List[] type instead, or if it really is a single element, remove the Tuple[] wrapper and just "
"pass the element directly."
)
if ... in args:
raise TypeHintParsingException(
"Conversion of '...' is not supported in Tuple type hints. "
"Use List[] types for variable-length"
" inputs instead."
)
return {"type": "array", "prefixItems": [_parse_type_hint(t) for t in args]}
elif origin is dict:
# The JSON equivalent to a dict is 'object', which mandates that all keys are strings
# However, we can specify the type of the dict values with "additionalProperties"
out = {"type": "object"}
if len(args) == 2:
out["additionalProperties"] = _parse_type_hint(args[1])
return out
elif origin is Literal:
literal_types = set(type(arg) for arg in args)
final_type = _parse_union_type(literal_types)
# None literal value is represented by 'nullable' field set by _parse_union_type
final_type.update({"enum": [arg for arg in args if arg is not None]})
return final_type
raise TypeHintParsingException("Couldn't parse this type hint, likely due to a custom class or object: ", hint)