diff --git a/src/anthropic/lib/_parse/_transform.py b/src/anthropic/lib/_parse/_transform.py index ce0c83ac9..cc89725bd 100644 --- a/src/anthropic/lib/_parse/_transform.py +++ b/src/anthropic/lib/_parse/_transform.py @@ -82,14 +82,16 @@ def transform_schema( # $defs must be processed before the $ref early-return below, so that a # root-level `{"$ref": "#/$defs/X", "$defs": {...}}` (valid JSON Schema, - # and what pydantic RootModel emits) keeps its definitions. - defs = json_schema.pop("$defs", None) - if defs is not None: - strict_defs: dict[str, Any] = {} - strict_schema["$defs"] = strict_defs - - for name, schema in defs.items(): - strict_defs[name] = transform_schema(schema) + # and what pydantic RootModel emits) keeps its definitions. Draft-07 + # `definitions` is the same keyword under its older name. + for defs_key in ("$defs", "definitions"): + defs = json_schema.pop(defs_key, None) + if defs is not None: + strict_defs: dict[str, Any] = {} + strict_schema[defs_key] = strict_defs + + for name, schema in defs.items(): + strict_defs[name] = transform_schema(schema) ref = json_schema.pop("$ref", None) if ref is not None: diff --git a/tests/lib/_parse/test_transform.py b/tests/lib/_parse/test_transform.py index 7a2799dce..214c746a9 100644 --- a/tests/lib/_parse/test_transform.py +++ b/tests/lib/_parse/test_transform.py @@ -40,6 +40,46 @@ def test_ref_schema_with_defs(): ) +def test_draft07_definitions_are_kept_and_transformed(): + schema = { + "type": "object", + "properties": {"home": {"$ref": "#/definitions/Address"}}, + "required": ["home"], + "definitions": { + "Address": { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + } + }, + } + result = transform_schema(schema) + assert result == snapshot( + { + "definitions": { + "Address": { + "type": "object", + "properties": {"city": {"type": "string"}}, + "additionalProperties": False, + "required": ["city"], + } + }, + "type": "object", + "properties": {"home": {"$ref": "#/definitions/Address"}}, + "additionalProperties": False, + "required": ["home"], + } + ) + + +def test_ref_schema_with_draft07_definitions(): + schema = {"$ref": "#/definitions/Tier", "definitions": {"Tier": {"type": "string", "enum": ["free", "pro"]}}} + result = transform_schema(schema) + assert result == snapshot( + {"definitions": {"Tier": {"type": "string", "enum": ["free", "pro"]}}, "$ref": "#/definitions/Tier"} + ) + + def test_anyof_schema(): schema = { "anyOf": [