Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/anthropic/lib/_parse/_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
40 changes: 40 additions & 0 deletions tests/lib/_parse/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down