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: preserve constraints on optional annotated fields (#100)
s4kura4653f7cc430f
diff --git a/needle/agent/tools.py b/needle/agent/tools.pyindex e836bfc..e16b7e6 100644--- a/needle/agent/tools.py+++ b/needle/agent/tools.py@@ -89,10 +89,15 @@ def _json_type(annotation):def _field_of(annotation, default):if isinstance(default, Field):return default- if typing.get_origin(annotation) is typing.Annotated:+ origin = typing.get_origin(annotation)+ if origin is typing.Annotated:for meta in typing.get_args(annotation)[1:]:if isinstance(meta, Field):return meta+ if origin in _UNION_ORIGINS:+ rest = [a for a in typing.get_args(annotation) if a is not type(None)]+ if len(rest) == 1:+ return _field_of(rest[0], _MISSING)return Nonediff --git a/tests/test_tools.py b/tests/test_tools.pyindex 4b9a15f..3864cde 100644--- a/tests/test_tools.py+++ b/tests/test_tools.py@@ -59,6 +59,26 @@ def test_optional_annotation_not_required():assert schema["parameters"]["required"] == ["a"]+def test_optional_annotated_field_constraints():+ def f(+ value: typing.Optional[typing.Annotated[+ str, Field(pattern="^[a-z]+$", min_length=2, format="email")]] = None,+ count: typing.Annotated[typing.Optional[int], Field(ge=0)] = None,+ ):+ pass++ schema = build_schema(f)+ properties = schema["parameters"]["properties"]+ assert properties["value"] == {+ "type": "string",+ "pattern": "^[a-z]+$",+ "minLength": 2,+ "format": "email",+ }+ assert properties["count"] == {"type": "integer", "minimum": 0}+ assert not {"value", "count"} & set(schema["parameters"].get("required", []))++@pep604def test_pep604_none_union_not_required():def f(a: str, b: str | None = None, c: int | None = None, d: str | int | None = None):