payi 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of payi might be problematic. Click here for more details.

Files changed (54) hide show
  1. payi/__init__.py +83 -0
  2. payi/_base_client.py +2006 -0
  3. payi/_client.py +414 -0
  4. payi/_compat.py +222 -0
  5. payi/_constants.py +14 -0
  6. payi/_exceptions.py +108 -0
  7. payi/_files.py +127 -0
  8. payi/_models.py +739 -0
  9. payi/_qs.py +150 -0
  10. payi/_resource.py +43 -0
  11. payi/_response.py +820 -0
  12. payi/_streaming.py +333 -0
  13. payi/_types.py +220 -0
  14. payi/_utils/__init__.py +52 -0
  15. payi/_utils/_logs.py +25 -0
  16. payi/_utils/_proxy.py +63 -0
  17. payi/_utils/_reflection.py +8 -0
  18. payi/_utils/_streams.py +12 -0
  19. payi/_utils/_sync.py +81 -0
  20. payi/_utils/_transform.py +382 -0
  21. payi/_utils/_typing.py +120 -0
  22. payi/_utils/_utils.py +402 -0
  23. payi/_version.py +4 -0
  24. payi/lib/.keep +4 -0
  25. payi/py.typed +0 -0
  26. payi/resources/__init__.py +33 -0
  27. payi/resources/budgets/__init__.py +33 -0
  28. payi/resources/budgets/budgets.py +717 -0
  29. payi/resources/budgets/tags.py +529 -0
  30. payi/resources/ingest_requests.py +187 -0
  31. payi/types/__init__.py +13 -0
  32. payi/types/budget_create_params.py +26 -0
  33. payi/types/budget_history_response.py +110 -0
  34. payi/types/budget_list_params.py +25 -0
  35. payi/types/budget_response.py +98 -0
  36. payi/types/budget_update_params.py +17 -0
  37. payi/types/budgets/__init__.py +13 -0
  38. payi/types/budgets/budget_tags_response.py +18 -0
  39. payi/types/budgets/tag_create_params.py +16 -0
  40. payi/types/budgets/tag_create_response.py +9 -0
  41. payi/types/budgets/tag_delete_response.py +9 -0
  42. payi/types/budgets/tag_list_response.py +9 -0
  43. payi/types/budgets/tag_remove_params.py +16 -0
  44. payi/types/budgets/tag_remove_response.py +9 -0
  45. payi/types/budgets/tag_update_params.py +16 -0
  46. payi/types/budgets/tag_update_response.py +9 -0
  47. payi/types/default_response.py +13 -0
  48. payi/types/ingest_request_create_params.py +27 -0
  49. payi/types/paged_budget_list.py +110 -0
  50. payi/types/successful_proxy_result.py +43 -0
  51. payi-0.1.0a1.dist-info/METADATA +355 -0
  52. payi-0.1.0a1.dist-info/RECORD +54 -0
  53. payi-0.1.0a1.dist-info/WHEEL +4 -0
  54. payi-0.1.0a1.dist-info/licenses/LICENSE +201 -0
payi/_models.py ADDED
@@ -0,0 +1,739 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, cast
6
+ from datetime import date, datetime
7
+ from typing_extensions import (
8
+ Unpack,
9
+ Literal,
10
+ ClassVar,
11
+ Protocol,
12
+ Required,
13
+ TypedDict,
14
+ TypeGuard,
15
+ final,
16
+ override,
17
+ runtime_checkable,
18
+ )
19
+
20
+ import pydantic
21
+ import pydantic.generics
22
+ from pydantic.fields import FieldInfo
23
+
24
+ from ._types import (
25
+ Body,
26
+ IncEx,
27
+ Query,
28
+ ModelT,
29
+ Headers,
30
+ Timeout,
31
+ NotGiven,
32
+ AnyMapping,
33
+ HttpxRequestFiles,
34
+ )
35
+ from ._utils import (
36
+ PropertyInfo,
37
+ is_list,
38
+ is_given,
39
+ lru_cache,
40
+ is_mapping,
41
+ parse_date,
42
+ coerce_boolean,
43
+ parse_datetime,
44
+ strip_not_given,
45
+ extract_type_arg,
46
+ is_annotated_type,
47
+ strip_annotated_type,
48
+ )
49
+ from ._compat import (
50
+ PYDANTIC_V2,
51
+ ConfigDict,
52
+ GenericModel as BaseGenericModel,
53
+ get_args,
54
+ is_union,
55
+ parse_obj,
56
+ get_origin,
57
+ is_literal_type,
58
+ get_model_config,
59
+ get_model_fields,
60
+ field_get_default,
61
+ )
62
+ from ._constants import RAW_RESPONSE_HEADER
63
+
64
+ if TYPE_CHECKING:
65
+ from pydantic_core.core_schema import ModelField, LiteralSchema, ModelFieldsSchema
66
+
67
+ __all__ = ["BaseModel", "GenericModel"]
68
+
69
+ _T = TypeVar("_T")
70
+
71
+
72
+ @runtime_checkable
73
+ class _ConfigProtocol(Protocol):
74
+ allow_population_by_field_name: bool
75
+
76
+
77
+ class BaseModel(pydantic.BaseModel):
78
+ if PYDANTIC_V2:
79
+ model_config: ClassVar[ConfigDict] = ConfigDict(
80
+ extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
81
+ )
82
+ else:
83
+
84
+ @property
85
+ @override
86
+ def model_fields_set(self) -> set[str]:
87
+ # a forwards-compat shim for pydantic v2
88
+ return self.__fields_set__ # type: ignore
89
+
90
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
91
+ extra: Any = pydantic.Extra.allow # type: ignore
92
+
93
+ def to_dict(
94
+ self,
95
+ *,
96
+ mode: Literal["json", "python"] = "python",
97
+ use_api_names: bool = True,
98
+ exclude_unset: bool = True,
99
+ exclude_defaults: bool = False,
100
+ exclude_none: bool = False,
101
+ warnings: bool = True,
102
+ ) -> dict[str, object]:
103
+ """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
104
+
105
+ By default, fields that were not set by the API will not be included,
106
+ and keys will match the API response, *not* the property names from the model.
107
+
108
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
109
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
110
+
111
+ Args:
112
+ mode:
113
+ 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"`.
114
+ If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
115
+
116
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
117
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
118
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
119
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
120
+ warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
121
+ """
122
+ return self.model_dump(
123
+ mode=mode,
124
+ by_alias=use_api_names,
125
+ exclude_unset=exclude_unset,
126
+ exclude_defaults=exclude_defaults,
127
+ exclude_none=exclude_none,
128
+ warnings=warnings,
129
+ )
130
+
131
+ def to_json(
132
+ self,
133
+ *,
134
+ indent: int | None = 2,
135
+ use_api_names: bool = True,
136
+ exclude_unset: bool = True,
137
+ exclude_defaults: bool = False,
138
+ exclude_none: bool = False,
139
+ warnings: bool = True,
140
+ ) -> str:
141
+ """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
142
+
143
+ By default, fields that were not set by the API will not be included,
144
+ and keys will match the API response, *not* the property names from the model.
145
+
146
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
147
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
148
+
149
+ Args:
150
+ indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
151
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
152
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
153
+ exclude_defaults: Whether to exclude fields that have the default value.
154
+ exclude_none: Whether to exclude fields that have a value of `None`.
155
+ warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
156
+ """
157
+ return self.model_dump_json(
158
+ indent=indent,
159
+ by_alias=use_api_names,
160
+ exclude_unset=exclude_unset,
161
+ exclude_defaults=exclude_defaults,
162
+ exclude_none=exclude_none,
163
+ warnings=warnings,
164
+ )
165
+
166
+ @override
167
+ def __str__(self) -> str:
168
+ # mypy complains about an invalid self arg
169
+ return f'{self.__repr_name__()}({self.__repr_str__(", ")})' # type: ignore[misc]
170
+
171
+ # Override the 'construct' method in a way that supports recursive parsing without validation.
172
+ # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
173
+ @classmethod
174
+ @override
175
+ def construct(
176
+ cls: Type[ModelT],
177
+ _fields_set: set[str] | None = None,
178
+ **values: object,
179
+ ) -> ModelT:
180
+ m = cls.__new__(cls)
181
+ fields_values: dict[str, object] = {}
182
+
183
+ config = get_model_config(cls)
184
+ populate_by_name = (
185
+ config.allow_population_by_field_name
186
+ if isinstance(config, _ConfigProtocol)
187
+ else config.get("populate_by_name")
188
+ )
189
+
190
+ if _fields_set is None:
191
+ _fields_set = set()
192
+
193
+ model_fields = get_model_fields(cls)
194
+ for name, field in model_fields.items():
195
+ key = field.alias
196
+ if key is None or (key not in values and populate_by_name):
197
+ key = name
198
+
199
+ if key in values:
200
+ fields_values[name] = _construct_field(value=values[key], field=field, key=key)
201
+ _fields_set.add(name)
202
+ else:
203
+ fields_values[name] = field_get_default(field)
204
+
205
+ _extra = {}
206
+ for key, value in values.items():
207
+ if key not in model_fields:
208
+ if PYDANTIC_V2:
209
+ _extra[key] = value
210
+ else:
211
+ _fields_set.add(key)
212
+ fields_values[key] = value
213
+
214
+ object.__setattr__(m, "__dict__", fields_values)
215
+
216
+ if PYDANTIC_V2:
217
+ # these properties are copied from Pydantic's `model_construct()` method
218
+ object.__setattr__(m, "__pydantic_private__", None)
219
+ object.__setattr__(m, "__pydantic_extra__", _extra)
220
+ object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
221
+ else:
222
+ # init_private_attributes() does not exist in v2
223
+ m._init_private_attributes() # type: ignore
224
+
225
+ # copied from Pydantic v1's `construct()` method
226
+ object.__setattr__(m, "__fields_set__", _fields_set)
227
+
228
+ return m
229
+
230
+ if not TYPE_CHECKING:
231
+ # type checkers incorrectly complain about this assignment
232
+ # because the type signatures are technically different
233
+ # although not in practice
234
+ model_construct = construct
235
+
236
+ if not PYDANTIC_V2:
237
+ # we define aliases for some of the new pydantic v2 methods so
238
+ # that we can just document these methods without having to specify
239
+ # a specific pydantic version as some users may not know which
240
+ # pydantic version they are currently using
241
+
242
+ @override
243
+ def model_dump(
244
+ self,
245
+ *,
246
+ mode: Literal["json", "python"] | str = "python",
247
+ include: IncEx = None,
248
+ exclude: IncEx = None,
249
+ by_alias: bool = False,
250
+ exclude_unset: bool = False,
251
+ exclude_defaults: bool = False,
252
+ exclude_none: bool = False,
253
+ round_trip: bool = False,
254
+ warnings: bool | Literal["none", "warn", "error"] = True,
255
+ context: dict[str, Any] | None = None,
256
+ serialize_as_any: bool = False,
257
+ ) -> dict[str, Any]:
258
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
259
+
260
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
261
+
262
+ Args:
263
+ mode: The mode in which `to_python` should run.
264
+ If mode is 'json', the dictionary will only contain JSON serializable types.
265
+ If mode is 'python', the dictionary may contain any Python objects.
266
+ include: A list of fields to include in the output.
267
+ exclude: A list of fields to exclude from the output.
268
+ by_alias: Whether to use the field's alias in the dictionary key if defined.
269
+ exclude_unset: Whether to exclude fields that are unset or None from the output.
270
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
271
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
272
+ round_trip: Whether to enable serialization and deserialization round-trip support.
273
+ warnings: Whether to log warnings when invalid fields are encountered.
274
+
275
+ Returns:
276
+ A dictionary representation of the model.
277
+ """
278
+ if mode != "python":
279
+ raise ValueError("mode is only supported in Pydantic v2")
280
+ if round_trip != False:
281
+ raise ValueError("round_trip is only supported in Pydantic v2")
282
+ if warnings != True:
283
+ raise ValueError("warnings is only supported in Pydantic v2")
284
+ if context is not None:
285
+ raise ValueError("context is only supported in Pydantic v2")
286
+ if serialize_as_any != False:
287
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
288
+ return super().dict( # pyright: ignore[reportDeprecated]
289
+ include=include,
290
+ exclude=exclude,
291
+ by_alias=by_alias,
292
+ exclude_unset=exclude_unset,
293
+ exclude_defaults=exclude_defaults,
294
+ exclude_none=exclude_none,
295
+ )
296
+
297
+ @override
298
+ def model_dump_json(
299
+ self,
300
+ *,
301
+ indent: int | None = None,
302
+ include: IncEx = None,
303
+ exclude: IncEx = None,
304
+ by_alias: bool = False,
305
+ exclude_unset: bool = False,
306
+ exclude_defaults: bool = False,
307
+ exclude_none: bool = False,
308
+ round_trip: bool = False,
309
+ warnings: bool | Literal["none", "warn", "error"] = True,
310
+ context: dict[str, Any] | None = None,
311
+ serialize_as_any: bool = False,
312
+ ) -> str:
313
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
314
+
315
+ Generates a JSON representation of the model using Pydantic's `to_json` method.
316
+
317
+ Args:
318
+ indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
319
+ include: Field(s) to include in the JSON output. Can take either a string or set of strings.
320
+ exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings.
321
+ by_alias: Whether to serialize using field aliases.
322
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
323
+ exclude_defaults: Whether to exclude fields that have the default value.
324
+ exclude_none: Whether to exclude fields that have a value of `None`.
325
+ round_trip: Whether to use serialization/deserialization between JSON and class instance.
326
+ warnings: Whether to show any warnings that occurred during serialization.
327
+
328
+ Returns:
329
+ A JSON string representation of the model.
330
+ """
331
+ if round_trip != False:
332
+ raise ValueError("round_trip is only supported in Pydantic v2")
333
+ if warnings != True:
334
+ raise ValueError("warnings is only supported in Pydantic v2")
335
+ if context is not None:
336
+ raise ValueError("context is only supported in Pydantic v2")
337
+ if serialize_as_any != False:
338
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
339
+ return super().json( # type: ignore[reportDeprecated]
340
+ indent=indent,
341
+ include=include,
342
+ exclude=exclude,
343
+ by_alias=by_alias,
344
+ exclude_unset=exclude_unset,
345
+ exclude_defaults=exclude_defaults,
346
+ exclude_none=exclude_none,
347
+ )
348
+
349
+
350
+ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
351
+ if value is None:
352
+ return field_get_default(field)
353
+
354
+ if PYDANTIC_V2:
355
+ type_ = field.annotation
356
+ else:
357
+ type_ = cast(type, field.outer_type_) # type: ignore
358
+
359
+ if type_ is None:
360
+ raise RuntimeError(f"Unexpected field type is None for {key}")
361
+
362
+ return construct_type(value=value, type_=type_)
363
+
364
+
365
+ def is_basemodel(type_: type) -> bool:
366
+ """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
367
+ if is_union(type_):
368
+ for variant in get_args(type_):
369
+ if is_basemodel(variant):
370
+ return True
371
+
372
+ return False
373
+
374
+ return is_basemodel_type(type_)
375
+
376
+
377
+ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
378
+ origin = get_origin(type_) or type_
379
+ return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
380
+
381
+
382
+ def construct_type(*, value: object, type_: object) -> object:
383
+ """Loose coercion to the expected type with construction of nested values.
384
+
385
+ If the given value does not match the expected type then it is returned as-is.
386
+ """
387
+ # we allow `object` as the input type because otherwise, passing things like
388
+ # `Literal['value']` will be reported as a type error by type checkers
389
+ type_ = cast("type[object]", type_)
390
+
391
+ # unwrap `Annotated[T, ...]` -> `T`
392
+ if is_annotated_type(type_):
393
+ meta: tuple[Any, ...] = get_args(type_)[1:]
394
+ type_ = extract_type_arg(type_, 0)
395
+ else:
396
+ meta = tuple()
397
+
398
+ # we need to use the origin class for any types that are subscripted generics
399
+ # e.g. Dict[str, object]
400
+ origin = get_origin(type_) or type_
401
+ args = get_args(type_)
402
+
403
+ if is_union(origin):
404
+ try:
405
+ return validate_type(type_=cast("type[object]", type_), value=value)
406
+ except Exception:
407
+ pass
408
+
409
+ # if the type is a discriminated union then we want to construct the right variant
410
+ # in the union, even if the data doesn't match exactly, otherwise we'd break code
411
+ # that relies on the constructed class types, e.g.
412
+ #
413
+ # class FooType:
414
+ # kind: Literal['foo']
415
+ # value: str
416
+ #
417
+ # class BarType:
418
+ # kind: Literal['bar']
419
+ # value: int
420
+ #
421
+ # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then
422
+ # we'd end up constructing `FooType` when it should be `BarType`.
423
+ discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta)
424
+ if discriminator and is_mapping(value):
425
+ variant_value = value.get(discriminator.field_alias_from or discriminator.field_name)
426
+ if variant_value and isinstance(variant_value, str):
427
+ variant_type = discriminator.mapping.get(variant_value)
428
+ if variant_type:
429
+ return construct_type(type_=variant_type, value=value)
430
+
431
+ # if the data is not valid, use the first variant that doesn't fail while deserializing
432
+ for variant in args:
433
+ try:
434
+ return construct_type(value=value, type_=variant)
435
+ except Exception:
436
+ continue
437
+
438
+ raise RuntimeError(f"Could not convert data into a valid instance of {type_}")
439
+
440
+ if origin == dict:
441
+ if not is_mapping(value):
442
+ return value
443
+
444
+ _, items_type = get_args(type_) # Dict[_, items_type]
445
+ return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
446
+
447
+ if not is_literal_type(type_) and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)):
448
+ if is_list(value):
449
+ return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value]
450
+
451
+ if is_mapping(value):
452
+ if issubclass(type_, BaseModel):
453
+ return type_.construct(**value) # type: ignore[arg-type]
454
+
455
+ return cast(Any, type_).construct(**value)
456
+
457
+ if origin == list:
458
+ if not is_list(value):
459
+ return value
460
+
461
+ inner_type = args[0] # List[inner_type]
462
+ return [construct_type(value=entry, type_=inner_type) for entry in value]
463
+
464
+ if origin == float:
465
+ if isinstance(value, int):
466
+ coerced = float(value)
467
+ if coerced != value:
468
+ return value
469
+ return coerced
470
+
471
+ return value
472
+
473
+ if type_ == datetime:
474
+ try:
475
+ return parse_datetime(value) # type: ignore
476
+ except Exception:
477
+ return value
478
+
479
+ if type_ == date:
480
+ try:
481
+ return parse_date(value) # type: ignore
482
+ except Exception:
483
+ return value
484
+
485
+ return value
486
+
487
+
488
+ @runtime_checkable
489
+ class CachedDiscriminatorType(Protocol):
490
+ __discriminator__: DiscriminatorDetails
491
+
492
+
493
+ class DiscriminatorDetails:
494
+ field_name: str
495
+ """The name of the discriminator field in the variant class, e.g.
496
+
497
+ ```py
498
+ class Foo(BaseModel):
499
+ type: Literal['foo']
500
+ ```
501
+
502
+ Will result in field_name='type'
503
+ """
504
+
505
+ field_alias_from: str | None
506
+ """The name of the discriminator field in the API response, e.g.
507
+
508
+ ```py
509
+ class Foo(BaseModel):
510
+ type: Literal['foo'] = Field(alias='type_from_api')
511
+ ```
512
+
513
+ Will result in field_alias_from='type_from_api'
514
+ """
515
+
516
+ mapping: dict[str, type]
517
+ """Mapping of discriminator value to variant type, e.g.
518
+
519
+ {'foo': FooVariant, 'bar': BarVariant}
520
+ """
521
+
522
+ def __init__(
523
+ self,
524
+ *,
525
+ mapping: dict[str, type],
526
+ discriminator_field: str,
527
+ discriminator_alias: str | None,
528
+ ) -> None:
529
+ self.mapping = mapping
530
+ self.field_name = discriminator_field
531
+ self.field_alias_from = discriminator_alias
532
+
533
+
534
+ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
535
+ if isinstance(union, CachedDiscriminatorType):
536
+ return union.__discriminator__
537
+
538
+ discriminator_field_name: str | None = None
539
+
540
+ for annotation in meta_annotations:
541
+ if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None:
542
+ discriminator_field_name = annotation.discriminator
543
+ break
544
+
545
+ if not discriminator_field_name:
546
+ return None
547
+
548
+ mapping: dict[str, type] = {}
549
+ discriminator_alias: str | None = None
550
+
551
+ for variant in get_args(union):
552
+ variant = strip_annotated_type(variant)
553
+ if is_basemodel_type(variant):
554
+ if PYDANTIC_V2:
555
+ field = _extract_field_schema_pv2(variant, discriminator_field_name)
556
+ if not field:
557
+ continue
558
+
559
+ # Note: if one variant defines an alias then they all should
560
+ discriminator_alias = field.get("serialization_alias")
561
+
562
+ field_schema = field["schema"]
563
+
564
+ if field_schema["type"] == "literal":
565
+ for entry in cast("LiteralSchema", field_schema)["expected"]:
566
+ if isinstance(entry, str):
567
+ mapping[entry] = variant
568
+ else:
569
+ field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
570
+ if not field_info:
571
+ continue
572
+
573
+ # Note: if one variant defines an alias then they all should
574
+ discriminator_alias = field_info.alias
575
+
576
+ if field_info.annotation and is_literal_type(field_info.annotation):
577
+ for entry in get_args(field_info.annotation):
578
+ if isinstance(entry, str):
579
+ mapping[entry] = variant
580
+
581
+ if not mapping:
582
+ return None
583
+
584
+ details = DiscriminatorDetails(
585
+ mapping=mapping,
586
+ discriminator_field=discriminator_field_name,
587
+ discriminator_alias=discriminator_alias,
588
+ )
589
+ cast(CachedDiscriminatorType, union).__discriminator__ = details
590
+ return details
591
+
592
+
593
+ def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None:
594
+ schema = model.__pydantic_core_schema__
595
+ if schema["type"] != "model":
596
+ return None
597
+
598
+ fields_schema = schema["schema"]
599
+ if fields_schema["type"] != "model-fields":
600
+ return None
601
+
602
+ fields_schema = cast("ModelFieldsSchema", fields_schema)
603
+
604
+ field = fields_schema["fields"].get(field_name)
605
+ if not field:
606
+ return None
607
+
608
+ return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast]
609
+
610
+
611
+ def validate_type(*, type_: type[_T], value: object) -> _T:
612
+ """Strict validation that the given value matches the expected type"""
613
+ if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
614
+ return cast(_T, parse_obj(type_, value))
615
+
616
+ return cast(_T, _validate_non_model_type(type_=type_, value=value))
617
+
618
+
619
+ # our use of subclasssing here causes weirdness for type checkers,
620
+ # so we just pretend that we don't subclass
621
+ if TYPE_CHECKING:
622
+ GenericModel = BaseModel
623
+ else:
624
+
625
+ class GenericModel(BaseGenericModel, BaseModel):
626
+ pass
627
+
628
+
629
+ if PYDANTIC_V2:
630
+ from pydantic import TypeAdapter as _TypeAdapter
631
+
632
+ _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter))
633
+
634
+ if TYPE_CHECKING:
635
+ from pydantic import TypeAdapter
636
+ else:
637
+ TypeAdapter = _CachedTypeAdapter
638
+
639
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
640
+ return TypeAdapter(type_).validate_python(value)
641
+
642
+ elif not TYPE_CHECKING: # TODO: condition is weird
643
+
644
+ class RootModel(GenericModel, Generic[_T]):
645
+ """Used as a placeholder to easily convert runtime types to a Pydantic format
646
+ to provide validation.
647
+
648
+ For example:
649
+ ```py
650
+ validated = RootModel[int](__root__="5").__root__
651
+ # validated: 5
652
+ ```
653
+ """
654
+
655
+ __root__: _T
656
+
657
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
658
+ model = _create_pydantic_model(type_).validate(value)
659
+ return cast(_T, model.__root__)
660
+
661
+ def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]:
662
+ return RootModel[type_] # type: ignore
663
+
664
+
665
+ class FinalRequestOptionsInput(TypedDict, total=False):
666
+ method: Required[str]
667
+ url: Required[str]
668
+ params: Query
669
+ headers: Headers
670
+ max_retries: int
671
+ timeout: float | Timeout | None
672
+ files: HttpxRequestFiles | None
673
+ idempotency_key: str
674
+ json_data: Body
675
+ extra_json: AnyMapping
676
+
677
+
678
+ @final
679
+ class FinalRequestOptions(pydantic.BaseModel):
680
+ method: str
681
+ url: str
682
+ params: Query = {}
683
+ headers: Union[Headers, NotGiven] = NotGiven()
684
+ max_retries: Union[int, NotGiven] = NotGiven()
685
+ timeout: Union[float, Timeout, None, NotGiven] = NotGiven()
686
+ files: Union[HttpxRequestFiles, None] = None
687
+ idempotency_key: Union[str, None] = None
688
+ post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
689
+
690
+ # It should be noted that we cannot use `json` here as that would override
691
+ # a BaseModel method in an incompatible fashion.
692
+ json_data: Union[Body, None] = None
693
+ extra_json: Union[AnyMapping, None] = None
694
+
695
+ if PYDANTIC_V2:
696
+ model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
697
+ else:
698
+
699
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
700
+ arbitrary_types_allowed: bool = True
701
+
702
+ def get_max_retries(self, max_retries: int) -> int:
703
+ if isinstance(self.max_retries, NotGiven):
704
+ return max_retries
705
+ return self.max_retries
706
+
707
+ def _strip_raw_response_header(self) -> None:
708
+ if not is_given(self.headers):
709
+ return
710
+
711
+ if self.headers.get(RAW_RESPONSE_HEADER):
712
+ self.headers = {**self.headers}
713
+ self.headers.pop(RAW_RESPONSE_HEADER)
714
+
715
+ # override the `construct` method so that we can run custom transformations.
716
+ # this is necessary as we don't want to do any actual runtime type checking
717
+ # (which means we can't use validators) but we do want to ensure that `NotGiven`
718
+ # values are not present
719
+ #
720
+ # type ignore required because we're adding explicit types to `**values`
721
+ @classmethod
722
+ def construct( # type: ignore
723
+ cls,
724
+ _fields_set: set[str] | None = None,
725
+ **values: Unpack[FinalRequestOptionsInput],
726
+ ) -> FinalRequestOptions:
727
+ kwargs: dict[str, Any] = {
728
+ # we unconditionally call `strip_not_given` on any value
729
+ # as it will just ignore any non-mapping types
730
+ key: strip_not_given(value)
731
+ for key, value in values.items()
732
+ }
733
+ if PYDANTIC_V2:
734
+ return super().model_construct(_fields_set, **kwargs)
735
+ return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
736
+
737
+ if not TYPE_CHECKING:
738
+ # type checkers incorrectly complain about this assignment
739
+ model_construct = construct