| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import sys |
| 5 |
import types |
| 6 |
import inspect |
| 7 |
import weakref |
| 8 |
from typing import ( |
| 9 |
IO, |
| 10 |
TYPE_CHECKING, |
| 11 |
Any, |
| 12 |
Type, |
| 13 |
Union, |
| 14 |
Generic, |
| 15 |
TypeVar, |
| 16 |
Callable, |
| 17 |
Iterable, |
| 18 |
Optional, |
| 19 |
AsyncIterable, |
| 20 |
cast, |
| 21 |
) |
| 22 |
from datetime import date, datetime |
| 23 |
from typing_extensions import ( |
| 24 |
List, |
| 25 |
Unpack, |
| 26 |
Literal, |
| 27 |
ClassVar, |
| 28 |
Protocol, |
| 29 |
Required, |
| 30 |
Annotated, |
| 31 |
ParamSpec, |
| 32 |
TypeAlias, |
| 33 |
TypedDict, |
| 34 |
TypeGuard, |
| 35 |
final, |
| 36 |
override, |
| 37 |
runtime_checkable, |
| 38 |
) |
| 39 |
|
| 40 |
import pydantic |
| 41 |
from pydantic.fields import FieldInfo |
| 42 |
|
| 43 |
from ._types import ( |
| 44 |
Body, |
| 45 |
IncEx, |
| 46 |
Query, |
| 47 |
ModelT, |
| 48 |
Headers, |
| 49 |
Timeout, |
| 50 |
NotGiven, |
| 51 |
AnyMapping, |
| 52 |
HttpxRequestFiles, |
| 53 |
) |
| 54 |
from ._utils import ( |
| 55 |
is_list, |
| 56 |
is_given, |
| 57 |
json_safe, |
| 58 |
lru_cache, |
| 59 |
is_mapping, |
| 60 |
parse_date, |
| 61 |
coerce_boolean, |
| 62 |
parse_datetime, |
| 63 |
strip_not_given, |
| 64 |
extract_type_arg, |
| 65 |
is_annotated_type, |
| 66 |
is_type_alias_type, |
| 67 |
strip_annotated_type, |
| 68 |
) |
| 69 |
from ._compat import ( |
| 70 |
PYDANTIC_V1, |
| 71 |
ConfigDict, |
| 72 |
GenericModel as BaseGenericModel, |
| 73 |
get_args, |
| 74 |
is_union, |
| 75 |
parse_obj, |
| 76 |
get_origin, |
| 77 |
is_literal_type, |
| 78 |
get_model_config, |
| 79 |
get_model_fields, |
| 80 |
field_get_default, |
| 81 |
) |
| 82 |
from ._constants import RAW_RESPONSE_HEADER |
| 83 |
|
| 84 |
if TYPE_CHECKING: |
| 85 |
from pydantic import GetCoreSchemaHandler, ValidatorFunctionWrapHandler |
| 86 |
from pydantic_core import CoreSchema, core_schema |
| 87 |
from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema |
| 88 |
else: |
| 89 |
try: |
| 90 |
from pydantic_core import CoreSchema, core_schema |
| 91 |
except ImportError: |
| 92 |
CoreSchema = None |
| 93 |
core_schema = None |
| 94 |
|
| 95 |
__all__ = ["BaseModel", "GenericModel"] |
| 96 |
|
| 97 |
_T = TypeVar("_T") |
| 98 |
_BaseModelT = TypeVar("_BaseModelT", bound="BaseModel") |
| 99 |
|
| 100 |
P = ParamSpec("P") |
| 101 |
|
| 102 |
|
| 103 |
@runtime_checkable |
| 104 |
class _ConfigProtocol(Protocol): |
| 105 |
allow_population_by_field_name: bool |
| 106 |
|
| 107 |
|
| 108 |
class BaseModel(pydantic.BaseModel): |
| 109 |
if PYDANTIC_V1: |
| 110 |
|
| 111 |
@property |
| 112 |
@override |
| 113 |
def model_fields_set(self) -> set[str]: |
| 114 |
# a forwards-compat shim for pydantic v2 |
| 115 |
return self.__fields_set__ # type: ignore |
| 116 |
|
| 117 |
class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] |
| 118 |
extra: Any = pydantic.Extra.allow # type: ignore |
| 119 |
else: |
| 120 |
model_config: ClassVar[ConfigDict] = ConfigDict( |
| 121 |
extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")) |
| 122 |
) |
| 123 |
|
| 124 |
if TYPE_CHECKING: |
| 125 |
_request_id: Optional[str] = None |
| 126 |
"""The ID of the request, returned via the `request-id` header. Useful for debugging requests and reporting issues to Anthropic. |
| 127 |
This will **only** be set for the top-level response object, it will not be defined for nested objects. For example: |
| 128 |
|
| 129 |
```py |
| 130 |
message = await client.messages.create(...) |
| 131 |
message._request_id # req_xxx |
| 132 |
message.usage._request_id # raises `AttributeError` |
| 133 |
``` |
| 134 |
|
| 135 |
Note: unlike other properties that use an `_` prefix, this property |
| 136 |
*is* public. Unless documented otherwise, all other `_` prefix properties, |
| 137 |
methods and modules are *private*. |
| 138 |
""" |
| 139 |
|
| 140 |
_workspace_id: Optional[str] = None |
| 141 |
"""The ID of the workspace the request was made in, returned via the `anthropic-workspace-id` header. |
| 142 |
Like `_request_id`, this will **only** be set for the top-level response object and, |
| 143 |
despite the `_` prefix, *is* public. |
| 144 |
""" |
| 145 |
|
| 146 |
def to_dict( |
| 147 |
self, |
| 148 |
*, |
| 149 |
mode: Literal["json", "python"] = "python", |
| 150 |
use_api_names: bool = True, |
| 151 |
exclude_unset: bool = True, |
| 152 |
exclude_defaults: bool = False, |
| 153 |
exclude_none: bool = False, |
| 154 |
warnings: bool = True, |
| 155 |
) -> dict[str, object]: |
| 156 |
"""Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude. |
| 157 |
|
| 158 |
By default, fields that were not set by the API will not be included, |
| 159 |
and keys will match the API response, *not* the property names from the model. |
| 160 |
|
| 161 |
For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, |
| 162 |
the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). |
| 163 |
|
| 164 |
Args: |
| 165 |
mode: |
| 166 |
If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`. |
| 167 |
If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)` |
| 168 |
|
| 169 |
use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. |
| 170 |
exclude_unset: Whether to exclude fields that have not been explicitly set. |
| 171 |
exclude_defaults: Whether to exclude fields that are set to their default value from the output. |
| 172 |
exclude_none: Whether to exclude fields that have a value of `None` from the output. |
| 173 |
warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2. |
| 174 |
""" |
| 175 |
return self.model_dump( |
| 176 |
mode=mode, |
| 177 |
by_alias=use_api_names, |
| 178 |
exclude_unset=exclude_unset, |
| 179 |
exclude_defaults=exclude_defaults, |
| 180 |
exclude_none=exclude_none, |
| 181 |
warnings=warnings, |
| 182 |
) |
| 183 |
|
| 184 |
def to_json( |
| 185 |
self, |
| 186 |
*, |
| 187 |
indent: int | None = 2, |
| 188 |
use_api_names: bool = True, |
| 189 |
exclude_unset: bool = True, |
| 190 |
exclude_defaults: bool = False, |
| 191 |
exclude_none: bool = False, |
| 192 |
warnings: bool = True, |
| 193 |
) -> str: |
| 194 |
"""Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation). |
| 195 |
|
| 196 |
By default, fields that were not set by the API will not be included, |
| 197 |
and keys will match the API response, *not* the property names from the model. |
| 198 |
|
| 199 |
For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, |
| 200 |
the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). |
| 201 |
|
| 202 |
Args: |
| 203 |
indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2` |
| 204 |
use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. |
| 205 |
exclude_unset: Whether to exclude fields that have not been explicitly set. |
| 206 |
exclude_defaults: Whether to exclude fields that have the default value. |
| 207 |
exclude_none: Whether to exclude fields that have a value of `None`. |
| 208 |
warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2. |
| 209 |
""" |
| 210 |
return self.model_dump_json( |
| 211 |
indent=indent, |
| 212 |
by_alias=use_api_names, |
| 213 |
exclude_unset=exclude_unset, |
| 214 |
exclude_defaults=exclude_defaults, |
| 215 |
exclude_none=exclude_none, |
| 216 |
warnings=warnings, |
| 217 |
) |
| 218 |
|
| 219 |
@override |
| 220 |
def __str__(self) -> str: |
| 221 |
# mypy complains about an invalid self arg |
| 222 |
return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc] |
| 223 |
|
| 224 |
# Override the 'construct' method in a way that supports recursive parsing without validation. |
| 225 |
# Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836. |
| 226 |
@classmethod |
| 227 |
@override |
| 228 |
def construct( # pyright: ignore[reportIncompatibleMethodOverride] |
| 229 |
__cls: Type[ModelT], |
| 230 |
_fields_set: set[str] | None = None, |
| 231 |
**values: object, |
| 232 |
) -> ModelT: |
| 233 |
m = __cls.__new__(__cls) |
| 234 |
fields_values: dict[str, object] = {} |
| 235 |
|
| 236 |
config = get_model_config(__cls) |
| 237 |
populate_by_name = ( |
| 238 |
config.allow_population_by_field_name |
| 239 |
if isinstance(config, _ConfigProtocol) |
| 240 |
else config.get("populate_by_name") |
| 241 |
) |
| 242 |
|
| 243 |
if _fields_set is None: |
| 244 |
_fields_set = set() |
| 245 |
|
| 246 |
model_fields = get_model_fields(__cls) |
| 247 |
for name, field in model_fields.items(): |
| 248 |
key = field.alias |
| 249 |
if key is None or (key not in values and populate_by_name): |
| 250 |
key = name |
| 251 |
|
| 252 |
if key in values: |
| 253 |
fields_values[name] = _construct_field(value=values[key], field=field, key=key) |
| 254 |
_fields_set.add(name) |
| 255 |
else: |
| 256 |
fields_values[name] = field_get_default(field) |
| 257 |
|
| 258 |
extra_field_type = _get_extra_fields_type(__cls) |
| 259 |
|
| 260 |
_extra = {} |
| 261 |
for key, value in values.items(): |
| 262 |
if key not in model_fields: |
| 263 |
parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value |
| 264 |
|
| 265 |
if PYDANTIC_V1: |
| 266 |
_fields_set.add(key) |
| 267 |
fields_values[key] = parsed |
| 268 |
else: |
| 269 |
_extra[key] = parsed |
| 270 |
|
| 271 |
object.__setattr__(m, "__dict__", fields_values) |
| 272 |
|
| 273 |
if PYDANTIC_V1: |
| 274 |
# init_private_attributes() does not exist in v2 |
| 275 |
m._init_private_attributes() # type: ignore |
| 276 |
|
| 277 |
# copied from Pydantic v1's `construct()` method |
| 278 |
object.__setattr__(m, "__fields_set__", _fields_set) |
| 279 |
else: |
| 280 |
# these properties are copied from Pydantic's `model_construct()` method |
| 281 |
object.__setattr__(m, "__pydantic_private__", None) |
| 282 |
object.__setattr__(m, "__pydantic_extra__", _extra) |
| 283 |
object.__setattr__(m, "__pydantic_fields_set__", _fields_set) |
| 284 |
|
| 285 |
return m |
| 286 |
|
| 287 |
if not TYPE_CHECKING: |
| 288 |
# type checkers incorrectly complain about this assignment |
| 289 |
# because the type signatures are technically different |
| 290 |
# although not in practice |
| 291 |
model_construct = construct |
| 292 |
|
| 293 |
if PYDANTIC_V1: |
| 294 |
# we define aliases for some of the new pydantic v2 methods so |
| 295 |
# that we can just document these methods without having to specify |
| 296 |
# a specific pydantic version as some users may not know which |
| 297 |
# pydantic version they are currently using |
| 298 |
|
| 299 |
@override |
| 300 |
def model_dump( |
| 301 |
self, |
| 302 |
*, |
| 303 |
mode: Literal["json", "python"] | str = "python", |
| 304 |
include: IncEx | None = None, |
| 305 |
exclude: IncEx | None = None, |
| 306 |
context: Any | None = None, |
| 307 |
by_alias: bool | None = None, |
| 308 |
exclude_unset: bool = False, |
| 309 |
exclude_defaults: bool = False, |
| 310 |
exclude_none: bool = False, |
| 311 |
exclude_computed_fields: bool = False, |
| 312 |
round_trip: bool = False, |
| 313 |
warnings: bool | Literal["none", "warn", "error"] = True, |
| 314 |
fallback: Callable[[Any], Any] | None = None, |
| 315 |
serialize_as_any: bool = False, |
| 316 |
) -> dict[str, Any]: |
| 317 |
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump |
| 318 |
|
| 319 |
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. |
| 320 |
|
| 321 |
Args: |
| 322 |
mode: The mode in which `to_python` should run. |
| 323 |
If mode is 'json', the output will only contain JSON serializable types. |
| 324 |
If mode is 'python', the output may contain non-JSON-serializable Python objects. |
| 325 |
include: A set of fields to include in the output. |
| 326 |
exclude: A set of fields to exclude from the output. |
| 327 |
context: Additional context to pass to the serializer. |
| 328 |
by_alias: Whether to use the field's alias in the dictionary key if defined. |
| 329 |
exclude_unset: Whether to exclude fields that have not been explicitly set. |
| 330 |
exclude_defaults: Whether to exclude fields that are set to their default value. |
| 331 |
exclude_none: Whether to exclude fields that have a value of `None`. |
| 332 |
exclude_computed_fields: Whether to exclude computed fields. |
| 333 |
While this can be useful for round-tripping, it is usually recommended to use the dedicated |
| 334 |
`round_trip` parameter instead. |
| 335 |
round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. |
| 336 |
warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, |
| 337 |
"error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. |
| 338 |
fallback: A function to call when an unknown value is encountered. If not provided, |
| 339 |
a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. |
| 340 |
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. |
| 341 |
|
| 342 |
Returns: |
| 343 |
A dictionary representation of the model. |
| 344 |
""" |
| 345 |
if mode not in {"json", "python"}: |
| 346 |
raise ValueError("mode must be either 'json' or 'python'") |
| 347 |
if round_trip != False: |
| 348 |
raise ValueError("round_trip is only supported in Pydantic v2") |
| 349 |
if warnings != True: |
| 350 |
raise ValueError("warnings is only supported in Pydantic v2") |
| 351 |
if context is not None: |
| 352 |
raise ValueError("context is only supported in Pydantic v2") |
| 353 |
if serialize_as_any != False: |
| 354 |
raise ValueError("serialize_as_any is only supported in Pydantic v2") |
| 355 |
if fallback is not None: |
| 356 |
raise ValueError("fallback is only supported in Pydantic v2") |
| 357 |
if exclude_computed_fields != False: |
| 358 |
raise ValueError("exclude_computed_fields is only supported in Pydantic v2") |
| 359 |
dumped = super().dict( # pyright: ignore[reportDeprecated] |
| 360 |
include=include, |
| 361 |
exclude=exclude, |
| 362 |
by_alias=by_alias if by_alias is not None else False, |
| 363 |
exclude_unset=exclude_unset, |
| 364 |
exclude_defaults=exclude_defaults, |
| 365 |
exclude_none=exclude_none, |
| 366 |
) |
| 367 |
|
| 368 |
return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped |
| 369 |
|
| 370 |
@override |
| 371 |
def model_dump_json( |
| 372 |
self, |
| 373 |
*, |
| 374 |
indent: int | None = None, |
| 375 |
ensure_ascii: bool = False, |
| 376 |
include: IncEx | None = None, |
| 377 |
exclude: IncEx | None = None, |
| 378 |
context: Any | None = None, |
| 379 |
by_alias: bool | None = None, |
| 380 |
exclude_unset: bool = False, |
| 381 |
exclude_defaults: bool = False, |
| 382 |
exclude_none: bool = False, |
| 383 |
exclude_computed_fields: bool = False, |
| 384 |
round_trip: bool = False, |
| 385 |
warnings: bool | Literal["none", "warn", "error"] = True, |
| 386 |
fallback: Callable[[Any], Any] | None = None, |
| 387 |
serialize_as_any: bool = False, |
| 388 |
) -> str: |
| 389 |
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json |
| 390 |
|
| 391 |
Generates a JSON representation of the model using Pydantic's `to_json` method. |
| 392 |
|
| 393 |
Args: |
| 394 |
indent: Indentation to use in the JSON output. If None is passed, the output will be compact. |
| 395 |
include: Field(s) to include in the JSON output. Can take either a string or set of strings. |
| 396 |
exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings. |
| 397 |
by_alias: Whether to serialize using field aliases. |
| 398 |
exclude_unset: Whether to exclude fields that have not been explicitly set. |
| 399 |
exclude_defaults: Whether to exclude fields that have the default value. |
| 400 |
exclude_none: Whether to exclude fields that have a value of `None`. |
| 401 |
round_trip: Whether to use serialization/deserialization between JSON and class instance. |
| 402 |
warnings: Whether to show any warnings that occurred during serialization. |
| 403 |
|
| 404 |
Returns: |
| 405 |
A JSON string representation of the model. |
| 406 |
""" |
| 407 |
if round_trip != False: |
| 408 |
raise ValueError("round_trip is only supported in Pydantic v2") |
| 409 |
if warnings != True: |
| 410 |
raise ValueError("warnings is only supported in Pydantic v2") |
| 411 |
if context is not None: |
| 412 |
raise ValueError("context is only supported in Pydantic v2") |
| 413 |
if serialize_as_any != False: |
| 414 |
raise ValueError("serialize_as_any is only supported in Pydantic v2") |
| 415 |
if fallback is not None: |
| 416 |
raise ValueError("fallback is only supported in Pydantic v2") |
| 417 |
if ensure_ascii != False: |
| 418 |
raise ValueError("ensure_ascii is only supported in Pydantic v2") |
| 419 |
if exclude_computed_fields != False: |
| 420 |
raise ValueError("exclude_computed_fields is only supported in Pydantic v2") |
| 421 |
return super().json( # type: ignore[reportDeprecated] |
| 422 |
indent=indent, |
| 423 |
include=include, |
| 424 |
exclude=exclude, |
| 425 |
by_alias=by_alias if by_alias is not None else False, |
| 426 |
exclude_unset=exclude_unset, |
| 427 |
exclude_defaults=exclude_defaults, |
| 428 |
exclude_none=exclude_none, |
| 429 |
) |
| 430 |
|
| 431 |
|
| 432 |
class _EagerIterable(list[_T], Generic[_T]): |
| 433 |
""" |
| 434 |
Accepts any Iterable[T] input (including generators), consumes it |
| 435 |
eagerly, and validates all items upfront. |
| 436 |
|
| 437 |
Validation preserves the original container type where possible |
| 438 |
(e.g. a set[T] stays a set[T]). Serialization (model_dump / JSON) |
| 439 |
always emits a list — round-tripping through model_dump() will not |
| 440 |
restore the original container type. |
| 441 |
""" |
| 442 |
|
| 443 |
@classmethod |
| 444 |
def __get_pydantic_core_schema__( |
| 445 |
cls, |
| 446 |
source_type: Any, |
| 447 |
handler: GetCoreSchemaHandler, |
| 448 |
) -> CoreSchema: |
| 449 |
(item_type,) = get_args(source_type) or (Any,) |
| 450 |
item_schema: CoreSchema = handler.generate_schema(item_type) |
| 451 |
list_of_items_schema: CoreSchema = core_schema.list_schema(item_schema) |
| 452 |
|
| 453 |
return core_schema.no_info_wrap_validator_function( |
| 454 |
cls._validate, |
| 455 |
list_of_items_schema, |
| 456 |
serialization=core_schema.plain_serializer_function_ser_schema( |
| 457 |
cls._serialize, |
| 458 |
info_arg=False, |
| 459 |
), |
| 460 |
) |
| 461 |
|
| 462 |
@staticmethod |
| 463 |
def _validate(v: Iterable[_T], handler: "ValidatorFunctionWrapHandler") -> Any: |
| 464 |
original_type: type[Any] = type(v) |
| 465 |
|
| 466 |
# Normalize to list so list_schema can validate each item |
| 467 |
if isinstance(v, list): |
| 468 |
items: list[_T] = v |
| 469 |
else: |
| 470 |
try: |
| 471 |
items = list(v) |
| 472 |
except TypeError as e: |
| 473 |
raise TypeError("Value is not iterable") from e |
| 474 |
|
| 475 |
# Validate items against the inner schema |
| 476 |
validated: list[_T] = handler(items) |
| 477 |
|
| 478 |
# Reconstruct original container type |
| 479 |
if original_type is list: |
| 480 |
return validated |
| 481 |
# str(list) produces the list's repr, not a string built from items, |
| 482 |
# so skip reconstruction for str and its subclasses. |
| 483 |
if issubclass(original_type, str): |
| 484 |
return validated |
| 485 |
try: |
| 486 |
return original_type(validated) |
| 487 |
except (TypeError, ValueError): |
| 488 |
# If the type cannot be reconstructed, just return the validated list |
| 489 |
return validated |
| 490 |
|
| 491 |
@staticmethod |
| 492 |
def _serialize(v: Iterable[_T]) -> list[_T]: |
| 493 |
"""Always serialize as a list so Pydantic's JSON encoder is happy.""" |
| 494 |
if isinstance(v, list): |
| 495 |
return v |
| 496 |
return list(v) |
| 497 |
|
| 498 |
|
| 499 |
EagerIterable: TypeAlias = Annotated[Iterable[_T], _EagerIterable] |
| 500 |
|
| 501 |
|
| 502 |
def _construct_field(value: object, field: FieldInfo, key: str) -> object: |
| 503 |
if value is None: |
| 504 |
return field_get_default(field) |
| 505 |
|
| 506 |
if PYDANTIC_V1: |
| 507 |
type_ = cast(type, field.outer_type_) # type: ignore |
| 508 |
else: |
| 509 |
type_ = field.annotation # type: ignore |
| 510 |
|
| 511 |
if type_ is None: |
| 512 |
raise RuntimeError(f"Unexpected field type is None for {key}") |
| 513 |
|
| 514 |
return construct_type(value=value, type_=type_, metadata=getattr(field, "metadata", None)) |
| 515 |
|
| 516 |
|
| 517 |
def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None: |
| 518 |
if PYDANTIC_V1: |
| 519 |
# TODO |
| 520 |
return None |
| 521 |
|
| 522 |
schema = cls.__pydantic_core_schema__ |
| 523 |
if schema["type"] == "model": |
| 524 |
fields = schema["schema"] |
| 525 |
if fields["type"] == "model-fields": |
| 526 |
extras = fields.get("extras_schema") |
| 527 |
if extras and "cls" in extras: |
| 528 |
# mypy can't narrow the type |
| 529 |
return extras["cls"] # type: ignore[no-any-return] |
| 530 |
|
| 531 |
return None |
| 532 |
|
| 533 |
|
| 534 |
def is_basemodel(type_: type) -> bool: |
| 535 |
"""Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`""" |
| 536 |
if is_union(type_): |
| 537 |
for variant in get_args(type_): |
| 538 |
if is_basemodel(variant): |
| 539 |
return True |
| 540 |
|
| 541 |
return False |
| 542 |
|
| 543 |
return is_basemodel_type(type_) |
| 544 |
|
| 545 |
|
| 546 |
def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]: |
| 547 |
origin = get_origin(type_) or type_ |
| 548 |
if not inspect.isclass(origin): |
| 549 |
return False |
| 550 |
return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) |
| 551 |
|
| 552 |
|
| 553 |
def build( |
| 554 |
base_model_cls: Callable[P, _BaseModelT], |
| 555 |
*args: P.args, |
| 556 |
**kwargs: P.kwargs, |
| 557 |
) -> _BaseModelT: |
| 558 |
"""Construct a BaseModel class without validation. |
| 559 |
|
| 560 |
This is useful for cases where you need to instantiate a `BaseModel` |
| 561 |
from an API response as this provides type-safe params which isn't supported |
| 562 |
by helpers like `construct_type()`. |
| 563 |
|
| 564 |
```py |
| 565 |
build(MyModel, my_field_a="foo", my_field_b=123) |
| 566 |
``` |
| 567 |
""" |
| 568 |
if args: |
| 569 |
raise TypeError( |
| 570 |
"Received positional arguments which are not supported; Keyword arguments must be used instead", |
| 571 |
) |
| 572 |
|
| 573 |
return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs)) |
| 574 |
|
| 575 |
|
| 576 |
def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T: |
| 577 |
"""Loose coercion to the expected type with construction of nested values. |
| 578 |
|
| 579 |
Note: the returned value from this function is not guaranteed to match the |
| 580 |
given type. |
| 581 |
""" |
| 582 |
return cast(_T, construct_type(value=value, type_=type_)) |
| 583 |
|
| 584 |
|
| 585 |
def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]] = None) -> object: |
| 586 |
"""Loose coercion to the expected type with construction of nested values. |
| 587 |
|
| 588 |
If the given value does not match the expected type then it is returned as-is. |
| 589 |
""" |
| 590 |
|
| 591 |
# store a reference to the original type we were given before we extract any inner |
| 592 |
# types so that we can properly resolve forward references in `TypeAliasType` annotations |
| 593 |
original_type = None |
| 594 |
|
| 595 |
# we allow `object` as the input type because otherwise, passing things like |
| 596 |
# `Literal['value']` will be reported as a type error by type checkers |
| 597 |
type_ = cast("type[object]", type_) |
| 598 |
if is_type_alias_type(type_): |
| 599 |
original_type = type_ # type: ignore[unreachable] |
| 600 |
type_ = type_.__value__ # type: ignore[unreachable] |
| 601 |
|
| 602 |
# unwrap `Annotated[T, ...]` -> `T` |
| 603 |
if metadata is not None and len(metadata) > 0: |
| 604 |
meta: tuple[Any, ...] = tuple(metadata) |
| 605 |
elif is_annotated_type(type_): |
| 606 |
meta = get_args(type_)[1:] |
| 607 |
type_ = extract_type_arg(type_, 0) |
| 608 |
else: |
| 609 |
meta = tuple() |
| 610 |
|
| 611 |
# we need to use the origin class for any types that are subscripted generics |
| 612 |
# e.g. Dict[str, object] |
| 613 |
origin = get_origin(type_) or type_ |
| 614 |
args = get_args(type_) |
| 615 |
|
| 616 |
if is_union(origin): |
| 617 |
try: |
| 618 |
return validate_type(type_=cast("type[object]", original_type or type_), value=value) |
| 619 |
except Exception: |
| 620 |
pass |
| 621 |
|
| 622 |
# if the type is a discriminated union then we want to construct the right variant |
| 623 |
# in the union, even if the data doesn't match exactly, otherwise we'd break code |
| 624 |
# that relies on the constructed class types, e.g. |
| 625 |
# |
| 626 |
# class FooType: |
| 627 |
# kind: Literal['foo'] |
| 628 |
# value: str |
| 629 |
# |
| 630 |
# class BarType: |
| 631 |
# kind: Literal['bar'] |
| 632 |
# value: int |
| 633 |
# |
| 634 |
# without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then |
| 635 |
# we'd end up constructing `FooType` when it should be `BarType`. |
| 636 |
discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta) |
| 637 |
if discriminator and is_mapping(value): |
| 638 |
variant_value = value.get(discriminator.field_alias_from or discriminator.field_name) |
| 639 |
if variant_value and isinstance(variant_value, str): |
| 640 |
variant_type = discriminator.mapping.get(variant_value) |
| 641 |
if variant_type: |
| 642 |
return construct_type(type_=variant_type, value=value) |
| 643 |
|
| 644 |
# if the data is not valid, use the first variant that doesn't fail while deserializing |
| 645 |
for variant in args: |
| 646 |
try: |
| 647 |
return construct_type(value=value, type_=variant) |
| 648 |
except Exception: |
| 649 |
continue |
| 650 |
|
| 651 |
raise RuntimeError(f"Could not convert data into a valid instance of {type_}") |
| 652 |
|
| 653 |
if origin == dict: |
| 654 |
if not is_mapping(value): |
| 655 |
return value |
| 656 |
|
| 657 |
_, items_type = get_args(type_) # Dict[_, items_type] |
| 658 |
return {key: construct_type(value=item, type_=items_type) for key, item in value.items()} |
| 659 |
|
| 660 |
if ( |
| 661 |
not is_literal_type(type_) |
| 662 |
and inspect.isclass(origin) |
| 663 |
and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)) |
| 664 |
): |
| 665 |
if is_list(value): |
| 666 |
return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value] |
| 667 |
|
| 668 |
if is_mapping(value): |
| 669 |
if issubclass(type_, BaseModel): |
| 670 |
return type_.construct(**value) # type: ignore[arg-type] |
| 671 |
|
| 672 |
return cast(Any, type_).construct(**value) |
| 673 |
|
| 674 |
if origin == list: |
| 675 |
if not is_list(value): |
| 676 |
return value |
| 677 |
|
| 678 |
inner_type = args[0] # List[inner_type] |
| 679 |
return [construct_type(value=entry, type_=inner_type) for entry in value] |
| 680 |
|
| 681 |
if origin == float: |
| 682 |
if isinstance(value, int): |
| 683 |
coerced = float(value) |
| 684 |
if coerced != value: |
| 685 |
return value |
| 686 |
return coerced |
| 687 |
|
| 688 |
return value |
| 689 |
|
| 690 |
if type_ == datetime: |
| 691 |
try: |
| 692 |
return parse_datetime(value) # type: ignore |
| 693 |
except Exception: |
| 694 |
return value |
| 695 |
|
| 696 |
if type_ == date: |
| 697 |
try: |
| 698 |
return parse_date(value) # type: ignore |
| 699 |
except Exception: |
| 700 |
return value |
| 701 |
|
| 702 |
return value |
| 703 |
|
| 704 |
|
| 705 |
class UnionDiscriminator: |
| 706 |
"""Annotated metadata naming the field that tells the variants of a union apart, e.g. |
| 707 |
|
| 708 |
```py |
| 709 |
Pet: TypeAlias = Annotated[Union[Cat, Dog], UnionDiscriminator("type")] |
| 710 |
``` |
| 711 |
|
| 712 |
When constructing a `Pet` from a response, the `type` value picks which variant to build. |
| 713 |
""" |
| 714 |
|
| 715 |
field_name: str |
| 716 |
"""The discriminator field's attribute name on the variant classes (not its API alias), e.g. `type`""" |
| 717 |
|
| 718 |
def __init__(self, field_name: str) -> None: |
| 719 |
self.field_name = field_name |
| 720 |
|
| 721 |
@override |
| 722 |
def __repr__(self) -> str: |
| 723 |
return f"{self.__class__.__name__}({self.field_name!r})" |
| 724 |
|
| 725 |
|
| 726 |
@runtime_checkable |
| 727 |
class CachedDiscriminatorType(Protocol): |
| 728 |
__discriminator__: DiscriminatorDetails |
| 729 |
|
| 730 |
|
| 731 |
DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary() |
| 732 |
|
| 733 |
|
| 734 |
def _discriminator_cache_key(union: type) -> type: |
| 735 |
if sys.version_info < (3, 14) and isinstance(cast(object, union), types.UnionType): |
| 736 |
# `X | Y` can't be weakly referenced before Python 3.14, so key on the equal `typing.Union[X, Y]`. |
| 737 |
# That object may be held only by `typing`'s LRU cache, so the cache entry can be dropped and rebuilt. |
| 738 |
return cast(type, cast(Any, Union)[get_args(union)]) |
| 739 |
return union |
| 740 |
|
| 741 |
|
| 742 |
class DiscriminatorDetails: |
| 743 |
field_name: str |
| 744 |
"""The name of the discriminator field in the variant class, e.g. |
| 745 |
|
| 746 |
```py |
| 747 |
class Foo(BaseModel): |
| 748 |
type: Literal['foo'] |
| 749 |
``` |
| 750 |
|
| 751 |
Will result in field_name='type' |
| 752 |
""" |
| 753 |
|
| 754 |
field_alias_from: str | None |
| 755 |
"""The name of the discriminator field in the API response, e.g. |
| 756 |
|
| 757 |
```py |
| 758 |
class Foo(BaseModel): |
| 759 |
type: Literal['foo'] = Field(alias='type_from_api') |
| 760 |
``` |
| 761 |
|
| 762 |
Will result in field_alias_from='type_from_api' |
| 763 |
""" |
| 764 |
|
| 765 |
mapping: dict[str, type] |
| 766 |
"""Mapping of discriminator value to variant type, e.g. |
| 767 |
|
| 768 |
{'foo': FooVariant, 'bar': BarVariant} |
| 769 |
""" |
| 770 |
|
| 771 |
def __init__( |
| 772 |
self, |
| 773 |
*, |
| 774 |
mapping: dict[str, type], |
| 775 |
discriminator_field: str, |
| 776 |
discriminator_alias: str | None, |
| 777 |
) -> None: |
| 778 |
self.mapping = mapping |
| 779 |
self.field_name = discriminator_field |
| 780 |
self.field_alias_from = discriminator_alias |
| 781 |
|
| 782 |
|
| 783 |
def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None: |
| 784 |
key = _discriminator_cache_key(union) |
| 785 |
cached = DISCRIMINATOR_CACHE.get(key) |
| 786 |
if cached is not None: |
| 787 |
return cached |
| 788 |
|
| 789 |
discriminator_field_name: str | None = None |
| 790 |
|
| 791 |
for annotation in meta_annotations: |
| 792 |
if isinstance(annotation, UnionDiscriminator): |
| 793 |
discriminator_field_name = annotation.field_name |
| 794 |
break |
| 795 |
|
| 796 |
if not discriminator_field_name: |
| 797 |
return None |
| 798 |
|
| 799 |
mapping: dict[str, type] = {} |
| 800 |
discriminator_alias: str | None = None |
| 801 |
|
| 802 |
for variant in get_args(union): |
| 803 |
variant = strip_annotated_type(variant) |
| 804 |
if is_basemodel_type(variant): |
| 805 |
if PYDANTIC_V1: |
| 806 |
field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] |
| 807 |
if not field_info: |
| 808 |
continue |
| 809 |
|
| 810 |
# Note: if one variant defines an alias then they all should |
| 811 |
discriminator_alias = field_info.alias |
| 812 |
|
| 813 |
if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): |
| 814 |
for entry in get_args(annotation): |
| 815 |
if isinstance(entry, str): |
| 816 |
mapping[entry] = variant |
| 817 |
else: |
| 818 |
field = _extract_field_schema_pv2(variant, discriminator_field_name) |
| 819 |
if not field: |
| 820 |
continue |
| 821 |
|
| 822 |
# Note: if one variant defines an alias then they all should |
| 823 |
discriminator_alias = field.get("serialization_alias") |
| 824 |
|
| 825 |
field_schema = field["schema"] |
| 826 |
|
| 827 |
if field_schema["type"] == "literal": |
| 828 |
for entry in cast("LiteralSchema", field_schema)["expected"]: # pyright: ignore[reportUnnecessaryCast] |
| 829 |
if isinstance(entry, str): |
| 830 |
mapping[entry] = variant |
| 831 |
|
| 832 |
if not mapping: |
| 833 |
return None |
| 834 |
|
| 835 |
details = DiscriminatorDetails( |
| 836 |
mapping=mapping, |
| 837 |
discriminator_field=discriminator_field_name, |
| 838 |
discriminator_alias=discriminator_alias, |
| 839 |
) |
| 840 |
DISCRIMINATOR_CACHE.setdefault(key, details) |
| 841 |
return details |
| 842 |
|
| 843 |
|
| 844 |
def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None: |
| 845 |
schema = model.__pydantic_core_schema__ |
| 846 |
if schema["type"] == "definitions": |
| 847 |
schema = schema["schema"] |
| 848 |
|
| 849 |
if schema["type"] != "model": |
| 850 |
return None |
| 851 |
|
| 852 |
schema = cast("ModelSchema", schema) # pyright: ignore[reportUnnecessaryCast] |
| 853 |
fields_schema = schema["schema"] |
| 854 |
if fields_schema["type"] != "model-fields": |
| 855 |
return None |
| 856 |
|
| 857 |
fields_schema = cast("ModelFieldsSchema", fields_schema) # pyright: ignore[reportUnnecessaryCast] |
| 858 |
field = fields_schema["fields"].get(field_name) |
| 859 |
if not field: |
| 860 |
return None |
| 861 |
|
| 862 |
return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast] |
| 863 |
|
| 864 |
|
| 865 |
def validate_type(*, type_: type[_T], value: object) -> _T: |
| 866 |
"""Strict validation that the given value matches the expected type""" |
| 867 |
if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel): |
| 868 |
return cast(_T, parse_obj(type_, value)) |
| 869 |
|
| 870 |
return cast(_T, _validate_non_model_type(type_=type_, value=value)) |
| 871 |
|
| 872 |
|
| 873 |
def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None: |
| 874 |
"""Add a pydantic config for the given type. |
| 875 |
|
| 876 |
Note: this is a no-op on Pydantic v1. |
| 877 |
""" |
| 878 |
setattr(typ, "__pydantic_config__", config) # noqa: B010 |
| 879 |
|
| 880 |
|
| 881 |
def add_response_ids(obj: BaseModel, *, request_id: str | None, workspace_id: str | None) -> None: |
| 882 |
obj._request_id = request_id |
| 883 |
obj._workspace_id = workspace_id |
| 884 |
|
| 885 |
# in Pydantic v1, using setattr like we do above causes the attributes |
| 886 |
# to be included when serializing the model which we don't want in this |
| 887 |
# case so we need to explicitly exclude them |
| 888 |
if PYDANTIC_V1: |
| 889 |
private_fields = {"_request_id", "_workspace_id", "__exclude_fields__"} |
| 890 |
try: |
| 891 |
exclude_fields = obj.__exclude_fields__ # type: ignore |
| 892 |
except AttributeError: |
| 893 |
cast(Any, obj).__exclude_fields__ = private_fields |
| 894 |
else: |
| 895 |
cast(Any, obj).__exclude_fields__ = {*(exclude_fields or {}), *private_fields} |
| 896 |
|
| 897 |
|
| 898 |
# our use of subclassing here causes weirdness for type checkers, |
| 899 |
# so we just pretend that we don't subclass |
| 900 |
if TYPE_CHECKING: |
| 901 |
GenericModel = BaseModel |
| 902 |
else: |
| 903 |
|
| 904 |
class GenericModel(BaseGenericModel, BaseModel): |
| 905 |
pass |
| 906 |
|
| 907 |
|
| 908 |
if not PYDANTIC_V1: |
| 909 |
from pydantic import TypeAdapter as _TypeAdapter, computed_field as computed_field |
| 910 |
|
| 911 |
_CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter)) |
| 912 |
|
| 913 |
if TYPE_CHECKING: |
| 914 |
from pydantic import TypeAdapter |
| 915 |
else: |
| 916 |
TypeAdapter = _CachedTypeAdapter |
| 917 |
|
| 918 |
def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: |
| 919 |
return TypeAdapter(type_).validate_python(value) |
| 920 |
|
| 921 |
elif not TYPE_CHECKING: # TODO: condition is weird |
| 922 |
|
| 923 |
class RootModel(GenericModel, Generic[_T]): |
| 924 |
"""Used as a placeholder to easily convert runtime types to a Pydantic format |
| 925 |
to provide validation. |
| 926 |
|
| 927 |
For example: |
| 928 |
```py |
| 929 |
validated = RootModel[int](__root__="5").__root__ |
| 930 |
# validated: 5 |
| 931 |
``` |
| 932 |
""" |
| 933 |
|
| 934 |
__root__: _T |
| 935 |
|
| 936 |
def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: |
| 937 |
model = _create_pydantic_model(type_).validate(value) |
| 938 |
return cast(_T, model.__root__) |
| 939 |
|
| 940 |
def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]: |
| 941 |
return RootModel[type_] # type: ignore |
| 942 |
|
| 943 |
def TypeAdapter(*_args: Any, **_kwargs: Any) -> Any: |
| 944 |
raise RuntimeError("attempted to use TypeAdapter in pydantic v1") |
| 945 |
|
| 946 |
def computed_field(func: Any | None = None, /, **__: Any) -> Any: |
| 947 |
def _exc_func(*_: Any, **__: Any) -> Any: |
| 948 |
raise RuntimeError("attempted to use computed_field in pydantic v1") |
| 949 |
|
| 950 |
def _dec(*_: Any, **__: Any) -> Any: |
| 951 |
return _exc_func |
| 952 |
|
| 953 |
if func is not None: |
| 954 |
return _dec(func) |
| 955 |
else: |
| 956 |
return _dec |
| 957 |
|
| 958 |
|
| 959 |
class FinalRequestOptionsInput(TypedDict, total=False): |
| 960 |
method: Required[str] |
| 961 |
url: Required[str] |
| 962 |
params: Query |
| 963 |
headers: Headers |
| 964 |
max_retries: int |
| 965 |
timeout: float | Timeout | None |
| 966 |
files: HttpxRequestFiles | None |
| 967 |
idempotency_key: str |
| 968 |
content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] |
| 969 |
json_data: Body |
| 970 |
extra_json: AnyMapping |
| 971 |
follow_redirects: bool |
| 972 |
|
| 973 |
|
| 974 |
@final |
| 975 |
class FinalRequestOptions(pydantic.BaseModel): |
| 976 |
method: str |
| 977 |
url: str |
| 978 |
params: Query = {} |
| 979 |
headers: Union[Headers, NotGiven] = NotGiven() |
| 980 |
max_retries: Union[int, NotGiven] = NotGiven() |
| 981 |
timeout: Union[float, Timeout, None, NotGiven] = NotGiven() |
| 982 |
files: Union[HttpxRequestFiles, None] = None |
| 983 |
idempotency_key: Union[str, None] = None |
| 984 |
post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven() |
| 985 |
follow_redirects: Union[bool, None] = None |
| 986 |
|
| 987 |
content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] = None |
| 988 |
# It should be noted that we cannot use `json` here as that would override |
| 989 |
# a BaseModel method in an incompatible fashion. |
| 990 |
json_data: Union[Body, None] = None |
| 991 |
extra_json: Union[AnyMapping, None] = None |
| 992 |
|
| 993 |
if PYDANTIC_V1: |
| 994 |
|
| 995 |
class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] |
| 996 |
arbitrary_types_allowed: bool = True |
| 997 |
else: |
| 998 |
model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) |
| 999 |
|
| 1000 |
def get_max_retries(self, max_retries: int) -> int: |
| 1001 |
if isinstance(self.max_retries, NotGiven): |
| 1002 |
return max_retries |
| 1003 |
return self.max_retries |
| 1004 |
|
| 1005 |
def _strip_raw_response_header(self) -> None: |
| 1006 |
if not is_given(self.headers): |
| 1007 |
return |
| 1008 |
|
| 1009 |
if self.headers.get(RAW_RESPONSE_HEADER): |
| 1010 |
self.headers = {**self.headers} |
| 1011 |
self.headers.pop(RAW_RESPONSE_HEADER) |
| 1012 |
|
| 1013 |
# override the `construct` method so that we can run custom transformations. |
| 1014 |
# this is necessary as we don't want to do any actual runtime type checking |
| 1015 |
# (which means we can't use validators) but we do want to ensure that `NotGiven` |
| 1016 |
# values are not present |
| 1017 |
# |
| 1018 |
# type ignore required because we're adding explicit types to `**values` |
| 1019 |
@classmethod |
| 1020 |
def construct( # type: ignore |
| 1021 |
cls, |
| 1022 |
_fields_set: set[str] | None = None, |
| 1023 |
**values: Unpack[FinalRequestOptionsInput], |
| 1024 |
) -> FinalRequestOptions: |
| 1025 |
kwargs: dict[str, Any] = { |
| 1026 |
# we unconditionally call `strip_not_given` on any value |
| 1027 |
# as it will just ignore any non-mapping types |
| 1028 |
key: strip_not_given(value) |
| 1029 |
for key, value in values.items() |
| 1030 |
} |
| 1031 |
if PYDANTIC_V1: |
| 1032 |
return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated] |
| 1033 |
return super().model_construct(_fields_set, **kwargs) |
| 1034 |
|
| 1035 |
if not TYPE_CHECKING: |
| 1036 |
# type checkers incorrectly complain about this assignment |
| 1037 |
model_construct = construct |