Automation foundation model for tiny devices: 2-bit, 8-29 MB, tool calls, ASR, structured extraction and embeddings on phones, wearables, smart homes, robots, cars and microcontrollers.
fix(tools): keep an Optional argument optional when it is Annotated (#171)
brekenfe6c3c4cf842
diff --git a/needle/agent/tools.py b/needle/agent/tools.pyindex c4d9bcc..821973a 100644--- a/needle/agent/tools.py+++ b/needle/agent/tools.py@@ -50,6 +50,8 @@ class Field:def _is_optional(annotation):+ if typing.get_origin(annotation) is typing.Annotated:+ return _is_optional(typing.get_args(annotation)[0])return (typing.get_origin(annotation) in _UNION_ORIGINSand type(None) in typing.get_args(annotation))diff --git a/tests/test_tools.py b/tests/test_tools.pyindex 3864cde..b920bd5 100644--- a/tests/test_tools.py+++ b/tests/test_tools.py@@ -178,3 +178,23 @@ def test_numeric_literal_and_int_enum_schema():assert props["port"] == {"type": "integer", "enum": [80, 443, 8080]}assert props["level"] == {"type": "integer", "enum": [1, 2, 3]}assert props["mode"] == {"type": "string", "enum": ["fast", "slow"]}+++def test_annotated_optional_is_not_required():+ def f(city: str, units: typing.Annotated[typing.Optional[str], Field(description="metric or imperial")]):+ pass++ def g(city: str, units: typing.Optional[str]):+ pass++ assert build_schema(f)["parameters"]["required"] == ["city"]+ assert build_schema(f)["parameters"]["required"] == build_schema(g)["parameters"]["required"]+ assert build_schema(f)["parameters"]["properties"]["units"]["description"] == "metric or imperial"+++@pep604+def test_annotated_pep604_optional_is_not_required():+ def f(city: str, units: typing.Annotated[str | None, Field(description="metric or imperial")]):+ pass++ assert build_schema(f)["parameters"]["required"] == ["city"]