diff --git a/python/packages/anthropic/agent_framework_anthropic/_chat_client.py b/python/packages/anthropic/agent_framework_anthropic/_chat_client.py index a27fb504eab..3cee872a3cf 100644 --- a/python/packages/anthropic/agent_framework_anthropic/_chat_client.py +++ b/python/packages/anthropic/agent_framework_anthropic/_chat_client.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import copy import json import logging import sys @@ -311,6 +312,35 @@ def _drop_unsupported_sampling_options(options: dict[str, Any]) -> None: } +def _forbid_additional_properties(node: Any) -> None: + """Set ``additionalProperties: false`` on every object schema in ``node``, in place. + + Anthropic structured outputs only support ``additionalProperties: false``, including on + nested models in ``$defs``, so a missing, ``true`` or schema-valued one (a map such as + ``dict[str, str]``) is replaced, as the Anthropic SDK's ``transform_schema`` does. Maps of + names to schemas (``properties``, ``$defs``) are walked as maps, so a field named + ``properties`` or ``type`` is not mistaken for a schema. + """ + if isinstance(node, list): + for item in cast(list[Any], node): + _forbid_additional_properties(item) + return + if not isinstance(node, dict): + return + schema = cast(dict[str, Any], node) + schema_type = schema.get("type") + is_object = schema_type == "object" or (isinstance(schema_type, list) and "object" in schema_type) + if is_object or "properties" in schema: + schema["additionalProperties"] = False + for key, value in schema.items(): + if key in ("properties", "$defs", "definitions", "patternProperties"): + if isinstance(value, dict): + for sub_schema in cast(dict[str, Any], value).values(): + _forbid_additional_properties(sub_schema) + elif key not in ("default", "examples", "const", "enum"): + _forbid_additional_properties(value) + + def _map_finish_reason(stop_reason: str | None) -> FinishReason | None: """Map an Anthropic stop reason onto a framework finish reason. @@ -1041,7 +1071,9 @@ def _prepare_response_format(self, response_format: type[BaseModel] | dict[str, if isinstance(schema, dict): # Copy, so the caller's response_format is not changed for later requests. - schema = {**schema, "additionalProperties": False} + schema = copy.deepcopy(cast(dict[str, Any], schema)) + schema["additionalProperties"] = False + _forbid_additional_properties(schema) return { "type": "json_schema", @@ -1050,6 +1082,7 @@ def _prepare_response_format(self, response_format: type[BaseModel] | dict[str, schema = response_format.model_json_schema() schema["additionalProperties"] = False + _forbid_additional_properties(schema) return { "type": "json_schema", diff --git a/python/packages/anthropic/tests/test_anthropic_client.py b/python/packages/anthropic/tests/test_anthropic_client.py index 15f9b264fee..e33a107730a 100644 --- a/python/packages/anthropic/tests/test_anthropic_client.py +++ b/python/packages/anthropic/tests/test_anthropic_client.py @@ -4778,6 +4778,71 @@ class TestModel(BaseModel): assert "properties" in result["schema"] +def test_prepare_response_format_nested_pydantic_model(mock_anthropic_client: MagicMock) -> None: + """Nested models in $defs also get additionalProperties: false, which Anthropic requires.""" + client = create_test_anthropic_client(mock_anthropic_client) + + class Address(BaseModel): + city: str + + class Person(BaseModel): + name: str + address: Address + previous_addresses: list[Address] + + result = client._prepare_response_format(Person) + + assert result["schema"]["additionalProperties"] is False + assert result["schema"]["$defs"]["Address"]["additionalProperties"] is False + + +def test_prepare_response_format_nested_dict_schema(mock_anthropic_client: MagicMock) -> None: + """Nested objects in a dict schema get additionalProperties: false; field names and the caller's dict do not.""" + client = create_test_anthropic_client(mock_anthropic_client) + + schema: dict[str, Any] = { + "type": "object", + "properties": { + "properties": {"type": "object", "properties": {"color": {"type": "string"}}}, + "tags": {"type": "array", "items": {"type": "object", "properties": {"label": {"type": "string"}}}}, + }, + } + + result = client._prepare_response_format({"schema": schema}) + + fields = result["schema"]["properties"] + assert "additionalProperties" not in fields + assert fields["properties"]["additionalProperties"] is False + assert fields["tags"]["items"]["additionalProperties"] is False + assert "additionalProperties" not in schema["properties"]["properties"] + + +def test_prepare_response_format_nested_map_schema(mock_anthropic_client: MagicMock) -> None: + """A map field (dict[str, str]) gets additionalProperties: false, the only value Anthropic supports.""" + client = create_test_anthropic_client(mock_anthropic_client) + + class Labels(BaseModel): + values: dict[str, str] + + result = client._prepare_response_format(Labels) + + assert result["schema"]["properties"]["values"]["additionalProperties"] is False + + +@pytest.mark.parametrize("extra", [{}, {"additionalProperties": True}]) +def test_prepare_response_format_nullable_nested_object( + mock_anthropic_client: MagicMock, extra: dict[str, Any] +) -> None: + """A nested object that may also be null (type ["object", "null"]) gets additionalProperties: false too.""" + client = create_test_anthropic_client(mock_anthropic_client) + + response_format = {"type": "object", "properties": {"meta": {"type": ["object", "null"], **extra}}} + + result = client._prepare_response_format(response_format) + + assert result["schema"]["properties"]["meta"]["additionalProperties"] is False + + async def test_prepare_options_uses_output_config_for_response_format( mock_anthropic_client: MagicMock, ) -> None: