openmeter 1.0.0b53__py3-none-any.whl → 2.0.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.

Potentially problematic release.


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

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