Debian Codegraph @

src/anthropic/lib/_parse/_transform.py

raw
1 from __future__ import annotations
2
3 import inspect
4 from typing import Any, Literal, Optional, cast
5 from typing_extensions import assert_never
6
7 import pydantic
8
9 from ..._utils import is_list
10
11 SupportedTypes = Literal[
12 "object",
13 "array",
14 "string",
15 "integer",
16 "number",
17 "boolean",
18 "null",
19 ]
20
21 SupportedStringFormats = {
22 "date-time",
23 "time",
24 "date",
25 "duration",
26 "email",
27 "hostname",
28 "uri",
29 "ipv4",
30 "ipv6",
31 "uuid",
32 }
33
34
35 def get_transformed_string(
36 schema: dict[str, Any],
37 ) -> dict[str, Any]:
38 """Transforms a JSON schema of type string to ensure it conforms to the API's expectations.
39
40 Specifically, it ensures that if the schema is of type "string" and does not already
41 specify a "format", it sets the format to "text".
42
43 Args:
44 schema: The original JSON schema.
45
46 Returns:
47 The transformed JSON schema.
48 """
49 if schema.get("type") == "string" and "format" not in schema:
50 schema["format"] = "text"
51 return schema
52
53
54 def transform_schema(
55 json_schema: type[pydantic.BaseModel] | dict[str, Any],
56 ) -> dict[str, Any]:
57 """
58 Transforms a JSON schema to ensure it conforms to the API's expectations.
59
60 Args:
61 json_schema (Dict[str, Any]): The original JSON schema.
62
63 Returns:
64 The transformed JSON schema.
65
66 Examples:
67 >>> transform_schema(
68 ... {
69 ... "type": "integer",
70 ... "minimum": 1,
71 ... "maximum": 10,
72 ... "description": "A number",
73 ... }
74 ... )
75 {'type': 'integer', 'description': 'A number\n\n{minimum: 1, maximum: 10}'}
76 """
77 if inspect.isclass(json_schema) and issubclass(json_schema, pydantic.BaseModel): # pyright: ignore[reportUnnecessaryIsInstance]
78 json_schema = json_schema.model_json_schema()
79
80 strict_schema: dict[str, Any] = {}
81 json_schema = {**json_schema}
82
83 # $defs must be processed before the $ref early-return below, so that a
84 # root-level `{"$ref": "#/$defs/X", "$defs": {...}}` (valid JSON Schema,
85 # and what pydantic RootModel emits) keeps its definitions.
86 defs = json_schema.pop("$defs", None)
87 if defs is not None:
88 strict_defs: dict[str, Any] = {}
89 strict_schema["$defs"] = strict_defs
90
91 for name, schema in defs.items():
92 strict_defs[name] = transform_schema(schema)
93
94 ref = json_schema.pop("$ref", None)
95 if ref is not None:
96 strict_schema["$ref"] = ref
97 return strict_schema
98
99 type_: Optional[SupportedTypes] = json_schema.pop("type", None)
100 any_of = json_schema.pop("anyOf", None)
101 one_of = json_schema.pop("oneOf", None)
102 all_of = json_schema.pop("allOf", None)
103
104 if is_list(any_of):
105 strict_schema["anyOf"] = [transform_schema(cast("dict[str, Any]", variant)) for variant in any_of]
106 elif is_list(one_of):
107 strict_schema["anyOf"] = [transform_schema(cast("dict[str, Any]", variant)) for variant in one_of]
108 elif is_list(all_of):
109 strict_schema["allOf"] = [transform_schema(cast("dict[str, Any]", variant)) for variant in all_of]
110 else:
111 if type_ is None:
112 raise ValueError("Schema must have a 'type', 'anyOf', 'oneOf', or 'allOf' field.")
113
114 strict_schema["type"] = type_
115
116 enum = json_schema.pop("enum", None)
117 if is_list(enum):
118 strict_schema["enum"] = enum
119
120 description = json_schema.pop("description", None)
121 if description is not None:
122 strict_schema["description"] = description
123
124 title = json_schema.pop("title", None)
125 if title is not None:
126 strict_schema["title"] = title
127
128 if type_ == "object":
129 strict_schema["properties"] = {
130 key: transform_schema(prop_schema) for key, prop_schema in json_schema.pop("properties", {}).items()
131 }
132 json_schema.pop("additionalProperties", None)
133 strict_schema["additionalProperties"] = False
134
135 required = json_schema.pop("required", None)
136 if required is not None:
137 strict_schema["required"] = required
138
139 elif type_ == "string":
140 format = json_schema.pop("format", None)
141 if format and format in SupportedStringFormats:
142 strict_schema["format"] = format
143 elif format:
144 # add it back so its treated as an extra property and appended to the description
145 json_schema["format"] = format
146 elif type_ == "array":
147 items = json_schema.pop("items", None)
148 if items is not None:
149 strict_schema["items"] = transform_schema(items)
150
151 min_items = json_schema.pop("minItems", None)
152 if min_items is not None and min_items == 0 or min_items == 1:
153 strict_schema["minItems"] = min_items
154 elif min_items is not None:
155 # add it back so its treated as an extra property and appended to the description
156 json_schema["minItems"] = min_items
157
158 elif type_ == "boolean" or type_ == "integer" or type_ == "number" or type_ == "null" or type_ is None:
159 pass
160 else:
161 assert_never(type_)
162
163 # if there are any propes leftover then they aren't supported, so we add them to the description
164 # so that the model *might* follow them.
165 if json_schema:
166 description = strict_schema.get("description")
167 strict_schema["description"] = (
168 (description + "\n\n" if description is not None else "")
169 + "{"
170 + ", ".join(f"{key}: {value}" for key, value in json_schema.items())
171 + "}"
172 )
173
174 return strict_schema