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 a model argument's $defs on the tool parameters
HenryNdubuaku1dc8ffc6fecf
diff --git a/needle/agent/tools.py b/needle/agent/tools.pyindex a68618b..89b7d0f 100644--- a/needle/agent/tools.py+++ b/needle/agent/tools.py@@ -58,12 +58,12 @@ def _is_optional(annotation):and type(None) in typing.get_args(annotation))-def _json_type(annotation):+def _json_type(annotation, defs):if annotation is inspect.Parameter.empty or annotation is None:return {"type": "string"}origin = typing.get_origin(annotation)if origin is typing.Annotated:- return _json_type(typing.get_args(annotation)[0])+ return _json_type(typing.get_args(annotation)[0], defs)if origin is None:if annotation in _JSON_TYPES:return {"type": _JSON_TYPES[annotation]}@@ -72,7 +72,11 @@ def _json_type(annotation):val_type = _JSON_TYPES.get(type(values[0]), "string") if values else "string"return {"type": val_type, "enum": values}if _is_pydantic_model(annotation):- return pydantic_schema(annotation)["parameters"]+ schema = pydantic_schema(annotation)["parameters"]+ for key in ("$defs", "definitions"):+ if key in schema:+ defs.setdefault(key, {}).update(schema.pop(key))+ return schemareturn {"type": "string"}if origin is typing.Literal:args = list(typing.get_args(annotation))@@ -80,13 +84,13 @@ def _json_type(annotation):return {"type": val_type, "enum": args}if origin in (list, typing.List):args = typing.get_args(annotation)- return {"type": "array", "items": _json_type(args[0]) if args else {"type": "string"}}+ return {"type": "array", "items": _json_type(args[0], defs) if args else {"type": "string"}}if origin in (dict, typing.Dict):return {"type": "object"}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])+ return _json_type(rest[0], defs)return {"type": "string"}@@ -144,12 +148,12 @@ def build_schema(fn: Callable) -> dict:except Exception:hints = {}description, arg_docs = _parse_doc(fn.__doc__)- properties, required = {}, []+ properties, required, defs = {}, [], {}for name, param in signature.parameters.items():if name in ("self", "cls") or param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):continueannotation = hints.get(name, param.annotation)- schema = _json_type(annotation)+ schema = _json_type(annotation, defs)if name in arg_docs and "description" not in schema:schema["description"] = arg_docs[name]field = _field_of(annotation, param.default)@@ -164,6 +168,7 @@ def build_schema(fn: Callable) -> dict:parameters = {"type": "object", "properties": properties}if required:parameters["required"] = required+ parameters.update(defs)out = {"name": fn.__name__}if description:out["description"] = descriptiondiff --git a/tests/test_grounding.py b/tests/test_grounding.pyindex 982f5b2..88e8501 100644--- a/tests/test_grounding.py+++ b/tests/test_grounding.py@@ -432,3 +432,24 @@ def test_extract_accepts_dates_written_with_abbreviated_months_and_periods(stub)invoice = needle.extract("Invoice from Acme, issued Jun 5, 2025 and due Dec. 25, 2026", Invoice)assert invoice.due_date == datetime.date(2026, 12, 25)+++class Shipment(pydantic.BaseModel):+ invoice: Invoice+++def ship(shipment: Shipment):+ "Ship an order with its invoice."+++def test_complete_checks_dates_inside_a_nested_model_argument(stub):+ import needle++ stub.envelopes = [{"type": "call", "confidence": 0.9, "function_calls": [{+ "name": "ship",+ "arguments": {"shipment": {"invoice": {"vendor": "Acme", "due_date": "2026-09-05"}}},+ }]}]+ agent = needle.Needle(tools=[ship])+ response = agent.complete("Ship the Acme order, invoice due on 5th September 2031")++ assert response["validation"]["ungrounded"] == ["ship.shipment.invoice.due_date"]diff --git a/tests/test_tools.py b/tests/test_tools.pyindex fc193c7..1a051f7 100644--- a/tests/test_tools.py+++ b/tests/test_tools.py@@ -237,3 +237,27 @@ def test_annotated_pep604_optional_is_not_required():passassert build_schema(f)["parameters"]["required"] == ["city"]+++def test_model_arguments_keep_their_defs_on_the_tool_parameters():+ import pydantic++ class Address(pydantic.BaseModel):+ city: str++ class Customer(pydantic.BaseModel):+ name: str+ address: Address++ def register(customer: Customer, backup: typing.Optional[typing.List[Customer]] = None,+ definitions: dict = None):+ "Register a customer."++ parameters = build_schema(register)["parameters"]+ customer = parameters["properties"]["customer"]++ assert customer["properties"]["address"] == {"$ref": "#/$defs/Address"}+ assert "$defs" not in customer+ assert "$defs" not in parameters["properties"]["backup"]["items"]+ assert parameters["$defs"]["Address"]["properties"]["city"]["type"] == "string"+ assert parameters["properties"]["definitions"] == {"type": "object"}