Skip to content

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: enhance support for PEP 604 unions in schema generation and add related tests

HenryNdubuakua30627fbc9a0
diff --git a/needle/agent/tools.py b/needle/agent/tools.py
index c2446ef..be06e1f 100644
--- a/needle/agent/tools.py
+++ b/needle/agent/tools.py
@@ -1,11 +1,16 @@
import enum
import inspect
import re
+import types
import typing
_JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean",
list: "array", dict: "object"}
+# PEP 604 unions (X | Y) have origin types.UnionType, which only exists on
+# Python 3.10+; on 3.9 the getattr falls back to typing.Union harmlessly.
+_UNION_ORIGINS = (typing.Union, getattr(types, "UnionType", typing.Union))
+
_MISSING = object()
@@ -44,7 +49,7 @@ class Field:
def _is_optional(annotation):
- return (typing.get_origin(annotation) is typing.Union
+ return (typing.get_origin(annotation) in _UNION_ORIGINS
and type(None) in typing.get_args(annotation))
@@ -69,7 +74,7 @@ def _json_type(annotation):
return {"type": "array", "items": _json_type(args[0]) if args else {"type": "string"}}
if origin in (dict, typing.Dict):
return {"type": "object"}
- if origin is typing.Union:
+ if origin in _UNION_ORIGINS:
rest = [a for a in typing.get_args(annotation) if a is not type(None)]
if rest:
return _json_type(rest[0])
diff --git a/tests/test_tools.py b/tests/test_tools.py
index 82604dc..f8f8faa 100644
--- a/tests/test_tools.py
+++ b/tests/test_tools.py
@@ -1,8 +1,14 @@
+import sys
import typing
+import pytest
+
from needle import tool, Field
from needle.agent.tools import build_schema, pydantic_schema, _is_pydantic_model
+pep604 = pytest.mark.skipif(sys.version_info < (3, 10),
+ reason="PEP 604 unions need Python 3.10+")
+
def test_basic_schema_types_and_required():
@tool
@@ -52,6 +58,31 @@ def test_optional_annotation_not_required():
assert schema["parameters"]["required"] == ["a"]
+@pep604
+def test_pep604_none_union_not_required():
+ def f(a: str, b: str | None = None, c: int | None = None, d: str | int | None = None):
+ pass
+
+ schema = build_schema(f)
+ assert schema["parameters"]["required"] == ["a"]
+ props = schema["parameters"]["properties"]
+ assert props["b"] == {"type": "string"}
+ assert props["c"] == {"type": "integer"}
+ assert props["d"] == {"type": "string"}
+
+
+@pep604
+def test_pep604_union_matches_typing_union():
+ def f(value: int | str):
+ pass
+
+ def g(value: typing.Union[int, str]):
+ pass
+
+ assert build_schema(f)["parameters"] == build_schema(g)["parameters"]
+ assert build_schema(f)["parameters"]["properties"]["value"] == {"type": "integer"}
+
+
def test_field_constraints_and_docstring_args():
def f(temp: int = Field(description="temperature", ge=0, le=100),
name: str = Field(default="x", pattern="^[a-z]+$", min_length=1)):