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