|
1 |
| -"""Utilities for handling JSON schema compatibility.""" |
| 1 | +"""Convert JSON Schema dicts to Python types.""" |
| 2 | + |
| 3 | +import sys |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from typing import Any, Dict, List, Literal, Optional |
| 6 | + |
| 7 | +from pydantic import BaseModel, create_model |
| 8 | + |
| 9 | +if sys.version_info >= (3, 12): # pragma: no cover |
| 10 | + from typing import _TypedDictMeta, TypedDict # type: ignore |
| 11 | +else: # pragma: no cover |
| 12 | + from typing_extensions import _TypedDictMeta, TypedDict # type: ignore |
| 13 | + |
| 14 | + |
| 15 | +def schema_type_to_python( |
| 16 | + schema: dict, |
| 17 | + caller_target_type: Literal["pydantic", "typeddict", "dataclass"] |
| 18 | +) -> Any: |
| 19 | + """Get a Python type from a JSON Schema dict. |
| 20 | +
|
| 21 | + Parameters |
| 22 | + ---------- |
| 23 | + schema: dict |
| 24 | + The JSON Schema dict to convert to a Python type |
| 25 | + caller_target_type: Literal["pydantic", "typeddict", "dataclass"] |
| 26 | + The type of the caller |
| 27 | +
|
| 28 | + Returns |
| 29 | + ------- |
| 30 | + Any |
| 31 | + The Python type |
| 32 | +
|
| 33 | + """ |
| 34 | + if "enum" in schema: |
| 35 | + values = schema["enum"] |
| 36 | + return Literal[tuple(values)] |
| 37 | + |
| 38 | + t = schema.get("type") |
| 39 | + |
| 40 | + if t == "string": |
| 41 | + return str |
| 42 | + elif t == "integer": |
| 43 | + return int |
| 44 | + elif t == "number": |
| 45 | + return float |
| 46 | + elif t == "boolean": |
| 47 | + return bool |
| 48 | + elif t == "array": |
| 49 | + items = schema.get("items", {}) |
| 50 | + if items: |
| 51 | + item_type = schema_type_to_python(items, caller_target_type) |
| 52 | + else: |
| 53 | + item_type = Any |
| 54 | + return List[item_type] # type: ignore |
| 55 | + elif t == "object": |
| 56 | + name = schema.get("title") |
| 57 | + if caller_target_type == "pydantic": |
| 58 | + return json_schema_dict_to_pydantic(schema, name) |
| 59 | + elif caller_target_type == "typeddict": |
| 60 | + return json_schema_dict_to_typeddict(schema, name) |
| 61 | + elif caller_target_type == "dataclass": |
| 62 | + return json_schema_dict_to_dataclass(schema, name) |
| 63 | + |
| 64 | + return Any |
| 65 | + |
| 66 | + |
| 67 | +def json_schema_dict_to_typeddict( |
| 68 | + schema: dict, |
| 69 | + name: Optional[str] = None |
| 70 | +) -> _TypedDictMeta: |
| 71 | + """Convert a JSON Schema dict into a TypedDict class. |
| 72 | +
|
| 73 | + Parameters |
| 74 | + ---------- |
| 75 | + schema: dict |
| 76 | + The JSON Schema dict to convert to a TypedDict |
| 77 | + name: Optional[str] |
| 78 | + The name of the TypedDict |
| 79 | +
|
| 80 | + Returns |
| 81 | + ------- |
| 82 | + _TypedDictMeta |
| 83 | + The TypedDict class |
| 84 | +
|
| 85 | + """ |
| 86 | + required = set(schema.get("required", [])) |
| 87 | + properties = schema.get("properties", {}) |
| 88 | + |
| 89 | + annotations: Dict[str, Any] = {} |
| 90 | + |
| 91 | + for property, details in properties.items(): |
| 92 | + typ = schema_type_to_python(details, "typeddict") |
| 93 | + if property not in required: |
| 94 | + typ = Optional[typ] |
| 95 | + annotations[property] = typ |
| 96 | + |
| 97 | + return TypedDict(name or "AnonymousTypedDict", annotations) # type: ignore |
| 98 | + |
| 99 | + |
| 100 | +def json_schema_dict_to_pydantic( |
| 101 | + schema: dict, |
| 102 | + name: Optional[str] = None |
| 103 | +) -> type[BaseModel]: |
| 104 | + """Convert a JSON Schema dict into a Pydantic BaseModel class. |
| 105 | +
|
| 106 | + Parameters |
| 107 | + ---------- |
| 108 | + schema: dict |
| 109 | + The JSON Schema dict to convert to a Pydantic BaseModel |
| 110 | + name: Optional[str] |
| 111 | + The name of the Pydantic BaseModel |
| 112 | +
|
| 113 | + Returns |
| 114 | + ------- |
| 115 | + type[BaseModel] |
| 116 | + The Pydantic BaseModel class |
| 117 | +
|
| 118 | + """ |
| 119 | + required = set(schema.get("required", [])) |
| 120 | + properties = schema.get("properties", {}) |
| 121 | + |
| 122 | + field_definitions: Dict[str, Any] = {} |
| 123 | + |
| 124 | + for property, details in properties.items(): |
| 125 | + typ = schema_type_to_python(details, "pydantic") |
| 126 | + if property not in required: |
| 127 | + field_definitions[property] = (Optional[typ], None) |
| 128 | + else: |
| 129 | + field_definitions[property] = (typ, ...) |
| 130 | + |
| 131 | + return create_model(name or "AnonymousPydanticModel", **field_definitions) |
| 132 | + |
| 133 | + |
| 134 | +def json_schema_dict_to_dataclass( |
| 135 | + schema: dict, |
| 136 | + name: Optional[str] = None |
| 137 | +) -> type: |
| 138 | + """Convert a JSON Schema dict into a dataclass. |
| 139 | +
|
| 140 | + Parameters |
| 141 | + ---------- |
| 142 | + schema: dict |
| 143 | + The JSON Schema dict to convert to a dataclass |
| 144 | + name: Optional[str] |
| 145 | + The name of the dataclass |
| 146 | +
|
| 147 | + Returns |
| 148 | + ------- |
| 149 | + type |
| 150 | + The dataclass |
| 151 | +
|
| 152 | + """ |
| 153 | + required = set(schema.get("required", [])) |
| 154 | + properties = schema.get("properties", {}) |
| 155 | + |
| 156 | + annotations: Dict[str, Any] = {} |
| 157 | + defaults: Dict[str, Any] = {} |
| 158 | + |
| 159 | + for property, details in properties.items(): |
| 160 | + typ = schema_type_to_python(details, "dataclass") |
| 161 | + annotations[property] = typ |
| 162 | + |
| 163 | + if property not in required: |
| 164 | + defaults[property] = None |
| 165 | + |
| 166 | + class_dict = { |
| 167 | + '__annotations__': annotations, |
| 168 | + '__module__': __name__, |
| 169 | + } |
| 170 | + |
| 171 | + for property, default_val in defaults.items(): |
| 172 | + class_dict[property] = field(default=default_val) |
| 173 | + |
| 174 | + cls = type(name or "AnonymousDataclass", (), class_dict) |
| 175 | + return dataclass(cls) |
0 commit comments