deeprails 0.3.2__py3-none-any.whl → 1.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 deeprails might be problematic. Click here for more details.

Files changed (60) hide show
  1. deeprails/__init__.py +104 -1
  2. deeprails/_base_client.py +1995 -0
  3. deeprails/_client.py +478 -0
  4. deeprails/_compat.py +219 -0
  5. deeprails/_constants.py +14 -0
  6. deeprails/_exceptions.py +108 -0
  7. deeprails/_files.py +123 -0
  8. deeprails/_models.py +835 -0
  9. deeprails/_qs.py +150 -0
  10. deeprails/_resource.py +43 -0
  11. deeprails/_response.py +830 -0
  12. deeprails/_streaming.py +333 -0
  13. deeprails/_types.py +260 -0
  14. deeprails/_utils/__init__.py +64 -0
  15. deeprails/_utils/_compat.py +45 -0
  16. deeprails/_utils/_datetime_parse.py +136 -0
  17. deeprails/_utils/_logs.py +25 -0
  18. deeprails/_utils/_proxy.py +65 -0
  19. deeprails/_utils/_reflection.py +42 -0
  20. deeprails/_utils/_resources_proxy.py +24 -0
  21. deeprails/_utils/_streams.py +12 -0
  22. deeprails/_utils/_sync.py +86 -0
  23. deeprails/_utils/_transform.py +457 -0
  24. deeprails/_utils/_typing.py +156 -0
  25. deeprails/_utils/_utils.py +421 -0
  26. deeprails/_version.py +4 -0
  27. deeprails/lib/.keep +4 -0
  28. deeprails/py.typed +0 -0
  29. deeprails/resources/__init__.py +47 -0
  30. deeprails/resources/defend/__init__.py +33 -0
  31. deeprails/resources/defend/defend.py +480 -0
  32. deeprails/resources/defend/events.py +311 -0
  33. deeprails/resources/evaluate.py +334 -0
  34. deeprails/resources/monitor.py +566 -0
  35. deeprails/types/__init__.py +16 -0
  36. deeprails/types/api_response.py +50 -0
  37. deeprails/types/defend/__init__.py +6 -0
  38. deeprails/types/defend/event_submit_event_params.py +44 -0
  39. deeprails/types/defend/workflow_event_response.py +33 -0
  40. deeprails/types/defend_create_workflow_params.py +56 -0
  41. deeprails/types/defend_response.py +50 -0
  42. deeprails/types/defend_update_workflow_params.py +18 -0
  43. deeprails/types/evaluate_create_params.py +60 -0
  44. deeprails/types/evaluation.py +113 -0
  45. deeprails/types/monitor_create_params.py +15 -0
  46. deeprails/types/monitor_retrieve_params.py +12 -0
  47. deeprails/types/monitor_retrieve_response.py +81 -0
  48. deeprails/types/monitor_submit_event_params.py +63 -0
  49. deeprails/types/monitor_submit_event_response.py +36 -0
  50. deeprails/types/monitor_update_params.py +22 -0
  51. deeprails-1.0.0.dist-info/METADATA +550 -0
  52. deeprails-1.0.0.dist-info/RECORD +54 -0
  53. {deeprails-0.3.2.dist-info → deeprails-1.0.0.dist-info}/WHEEL +1 -1
  54. deeprails-1.0.0.dist-info/licenses/LICENSE +201 -0
  55. deeprails/client.py +0 -285
  56. deeprails/exceptions.py +0 -10
  57. deeprails/schemas.py +0 -92
  58. deeprails-0.3.2.dist-info/METADATA +0 -235
  59. deeprails-0.3.2.dist-info/RECORD +0 -8
  60. deeprails-0.3.2.dist-info/licenses/LICENSE +0 -11
deeprails/_client.py ADDED
@@ -0,0 +1,478 @@
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, Dict, Mapping, cast
7
+ from typing_extensions import Self, Literal, override
8
+
9
+ import httpx
10
+
11
+ from . import _exceptions
12
+ from ._qs import Querystring
13
+ from ._types import (
14
+ Omit,
15
+ Timeout,
16
+ NotGiven,
17
+ Transport,
18
+ ProxiesTypes,
19
+ RequestOptions,
20
+ not_given,
21
+ )
22
+ from ._utils import is_given, get_async_library
23
+ from ._version import __version__
24
+ from .resources import monitor, evaluate
25
+ from ._streaming import Stream as Stream, AsyncStream as AsyncStream
26
+ from ._exceptions import APIStatusError, DeeprailsError
27
+ from ._base_client import (
28
+ DEFAULT_MAX_RETRIES,
29
+ SyncAPIClient,
30
+ AsyncAPIClient,
31
+ )
32
+ from .resources.defend import defend
33
+
34
+ __all__ = [
35
+ "ENVIRONMENTS",
36
+ "Timeout",
37
+ "Transport",
38
+ "ProxiesTypes",
39
+ "RequestOptions",
40
+ "Deeprails",
41
+ "AsyncDeeprails",
42
+ "Client",
43
+ "AsyncClient",
44
+ ]
45
+
46
+ ENVIRONMENTS: Dict[str, str] = {
47
+ "production": "https://api.deeprails.com",
48
+ "environment_1": "https://dev-api.deeprails",
49
+ }
50
+
51
+
52
+ class Deeprails(SyncAPIClient):
53
+ defend: defend.DefendResource
54
+ monitor: monitor.MonitorResource
55
+ evaluate: evaluate.EvaluateResource
56
+ with_raw_response: DeeprailsWithRawResponse
57
+ with_streaming_response: DeeprailsWithStreamedResponse
58
+
59
+ # client options
60
+ api_key: str
61
+
62
+ _environment: Literal["production", "environment_1"] | NotGiven
63
+
64
+ def __init__(
65
+ self,
66
+ *,
67
+ api_key: str | None = None,
68
+ environment: Literal["production", "environment_1"] | NotGiven = not_given,
69
+ base_url: str | httpx.URL | None | NotGiven = not_given,
70
+ timeout: float | Timeout | None | NotGiven = not_given,
71
+ max_retries: int = DEFAULT_MAX_RETRIES,
72
+ default_headers: Mapping[str, str] | None = None,
73
+ default_query: Mapping[str, object] | None = None,
74
+ # Configure a custom httpx client.
75
+ # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
76
+ # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
77
+ http_client: httpx.Client | None = None,
78
+ # Enable or disable schema validation for data returned by the API.
79
+ # When enabled an error APIResponseValidationError is raised
80
+ # if the API responds with invalid data for the expected schema.
81
+ #
82
+ # This parameter may be removed or changed in the future.
83
+ # If you rely on this feature, please open a GitHub issue
84
+ # outlining your use-case to help us decide if it should be
85
+ # part of our public interface in the future.
86
+ _strict_response_validation: bool = False,
87
+ ) -> None:
88
+ """Construct a new synchronous Deeprails client instance.
89
+
90
+ This automatically infers the `api_key` argument from the `DEEPRAILS_API_KEY` environment variable if it is not provided.
91
+ """
92
+ if api_key is None:
93
+ api_key = os.environ.get("DEEPRAILS_API_KEY")
94
+ if api_key is None:
95
+ raise DeeprailsError(
96
+ "The api_key client option must be set either by passing api_key to the client or by setting the DEEPRAILS_API_KEY environment variable"
97
+ )
98
+ self.api_key = api_key
99
+
100
+ self._environment = environment
101
+
102
+ base_url_env = os.environ.get("DEEPRAILS_BASE_URL")
103
+ if is_given(base_url) and base_url is not None:
104
+ # cast required because mypy doesn't understand the type narrowing
105
+ base_url = cast("str | httpx.URL", base_url) # pyright: ignore[reportUnnecessaryCast]
106
+ elif is_given(environment):
107
+ if base_url_env and base_url is not None:
108
+ raise ValueError(
109
+ "Ambiguous URL; The `DEEPRAILS_BASE_URL` env var and the `environment` argument are given. If you want to use the environment, you must pass base_url=None",
110
+ )
111
+
112
+ try:
113
+ base_url = ENVIRONMENTS[environment]
114
+ except KeyError as exc:
115
+ raise ValueError(f"Unknown environment: {environment}") from exc
116
+ elif base_url_env is not None:
117
+ base_url = base_url_env
118
+ else:
119
+ self._environment = environment = "production"
120
+
121
+ try:
122
+ base_url = ENVIRONMENTS[environment]
123
+ except KeyError as exc:
124
+ raise ValueError(f"Unknown environment: {environment}") from exc
125
+
126
+ super().__init__(
127
+ version=__version__,
128
+ base_url=base_url,
129
+ max_retries=max_retries,
130
+ timeout=timeout,
131
+ http_client=http_client,
132
+ custom_headers=default_headers,
133
+ custom_query=default_query,
134
+ _strict_response_validation=_strict_response_validation,
135
+ )
136
+
137
+ self.defend = defend.DefendResource(self)
138
+ self.monitor = monitor.MonitorResource(self)
139
+ self.evaluate = evaluate.EvaluateResource(self)
140
+ self.with_raw_response = DeeprailsWithRawResponse(self)
141
+ self.with_streaming_response = DeeprailsWithStreamedResponse(self)
142
+
143
+ @property
144
+ @override
145
+ def qs(self) -> Querystring:
146
+ return Querystring(array_format="comma")
147
+
148
+ @property
149
+ @override
150
+ def auth_headers(self) -> dict[str, str]:
151
+ api_key = self.api_key
152
+ return {"Authorization": f"Bearer {api_key}"}
153
+
154
+ @property
155
+ @override
156
+ def default_headers(self) -> dict[str, str | Omit]:
157
+ return {
158
+ **super().default_headers,
159
+ "X-Stainless-Async": "false",
160
+ **self._custom_headers,
161
+ }
162
+
163
+ def copy(
164
+ self,
165
+ *,
166
+ api_key: str | None = None,
167
+ environment: Literal["production", "environment_1"] | None = None,
168
+ base_url: str | httpx.URL | None = None,
169
+ timeout: float | Timeout | None | NotGiven = not_given,
170
+ http_client: httpx.Client | None = None,
171
+ max_retries: int | NotGiven = not_given,
172
+ default_headers: Mapping[str, str] | None = None,
173
+ set_default_headers: Mapping[str, str] | None = None,
174
+ default_query: Mapping[str, object] | None = None,
175
+ set_default_query: Mapping[str, object] | None = None,
176
+ _extra_kwargs: Mapping[str, Any] = {},
177
+ ) -> Self:
178
+ """
179
+ Create a new client instance re-using the same options given to the current client with optional overriding.
180
+ """
181
+ if default_headers is not None and set_default_headers is not None:
182
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
183
+
184
+ if default_query is not None and set_default_query is not None:
185
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
186
+
187
+ headers = self._custom_headers
188
+ if default_headers is not None:
189
+ headers = {**headers, **default_headers}
190
+ elif set_default_headers is not None:
191
+ headers = set_default_headers
192
+
193
+ params = self._custom_query
194
+ if default_query is not None:
195
+ params = {**params, **default_query}
196
+ elif set_default_query is not None:
197
+ params = set_default_query
198
+
199
+ http_client = http_client or self._client
200
+ return self.__class__(
201
+ api_key=api_key or self.api_key,
202
+ base_url=base_url or self.base_url,
203
+ environment=environment or self._environment,
204
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
205
+ http_client=http_client,
206
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
207
+ default_headers=headers,
208
+ default_query=params,
209
+ **_extra_kwargs,
210
+ )
211
+
212
+ # Alias for `copy` for nicer inline usage, e.g.
213
+ # client.with_options(timeout=10).foo.create(...)
214
+ with_options = copy
215
+
216
+ @override
217
+ def _make_status_error(
218
+ self,
219
+ err_msg: str,
220
+ *,
221
+ body: object,
222
+ response: httpx.Response,
223
+ ) -> APIStatusError:
224
+ if response.status_code == 400:
225
+ return _exceptions.BadRequestError(err_msg, response=response, body=body)
226
+
227
+ if response.status_code == 401:
228
+ return _exceptions.AuthenticationError(err_msg, response=response, body=body)
229
+
230
+ if response.status_code == 403:
231
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
232
+
233
+ if response.status_code == 404:
234
+ return _exceptions.NotFoundError(err_msg, response=response, body=body)
235
+
236
+ if response.status_code == 409:
237
+ return _exceptions.ConflictError(err_msg, response=response, body=body)
238
+
239
+ if response.status_code == 422:
240
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
241
+
242
+ if response.status_code == 429:
243
+ return _exceptions.RateLimitError(err_msg, response=response, body=body)
244
+
245
+ if response.status_code >= 500:
246
+ return _exceptions.InternalServerError(err_msg, response=response, body=body)
247
+ return APIStatusError(err_msg, response=response, body=body)
248
+
249
+
250
+ class AsyncDeeprails(AsyncAPIClient):
251
+ defend: defend.AsyncDefendResource
252
+ monitor: monitor.AsyncMonitorResource
253
+ evaluate: evaluate.AsyncEvaluateResource
254
+ with_raw_response: AsyncDeeprailsWithRawResponse
255
+ with_streaming_response: AsyncDeeprailsWithStreamedResponse
256
+
257
+ # client options
258
+ api_key: str
259
+
260
+ _environment: Literal["production", "environment_1"] | NotGiven
261
+
262
+ def __init__(
263
+ self,
264
+ *,
265
+ api_key: str | None = None,
266
+ environment: Literal["production", "environment_1"] | NotGiven = not_given,
267
+ base_url: str | httpx.URL | None | NotGiven = not_given,
268
+ timeout: float | Timeout | None | NotGiven = not_given,
269
+ max_retries: int = DEFAULT_MAX_RETRIES,
270
+ default_headers: Mapping[str, str] | None = None,
271
+ default_query: Mapping[str, object] | None = None,
272
+ # Configure a custom httpx client.
273
+ # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
274
+ # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details.
275
+ http_client: httpx.AsyncClient | None = None,
276
+ # Enable or disable schema validation for data returned by the API.
277
+ # When enabled an error APIResponseValidationError is raised
278
+ # if the API responds with invalid data for the expected schema.
279
+ #
280
+ # This parameter may be removed or changed in the future.
281
+ # If you rely on this feature, please open a GitHub issue
282
+ # outlining your use-case to help us decide if it should be
283
+ # part of our public interface in the future.
284
+ _strict_response_validation: bool = False,
285
+ ) -> None:
286
+ """Construct a new async AsyncDeeprails client instance.
287
+
288
+ This automatically infers the `api_key` argument from the `DEEPRAILS_API_KEY` environment variable if it is not provided.
289
+ """
290
+ if api_key is None:
291
+ api_key = os.environ.get("DEEPRAILS_API_KEY")
292
+ if api_key is None:
293
+ raise DeeprailsError(
294
+ "The api_key client option must be set either by passing api_key to the client or by setting the DEEPRAILS_API_KEY environment variable"
295
+ )
296
+ self.api_key = api_key
297
+
298
+ self._environment = environment
299
+
300
+ base_url_env = os.environ.get("DEEPRAILS_BASE_URL")
301
+ if is_given(base_url) and base_url is not None:
302
+ # cast required because mypy doesn't understand the type narrowing
303
+ base_url = cast("str | httpx.URL", base_url) # pyright: ignore[reportUnnecessaryCast]
304
+ elif is_given(environment):
305
+ if base_url_env and base_url is not None:
306
+ raise ValueError(
307
+ "Ambiguous URL; The `DEEPRAILS_BASE_URL` env var and the `environment` argument are given. If you want to use the environment, you must pass base_url=None",
308
+ )
309
+
310
+ try:
311
+ base_url = ENVIRONMENTS[environment]
312
+ except KeyError as exc:
313
+ raise ValueError(f"Unknown environment: {environment}") from exc
314
+ elif base_url_env is not None:
315
+ base_url = base_url_env
316
+ else:
317
+ self._environment = environment = "production"
318
+
319
+ try:
320
+ base_url = ENVIRONMENTS[environment]
321
+ except KeyError as exc:
322
+ raise ValueError(f"Unknown environment: {environment}") from exc
323
+
324
+ super().__init__(
325
+ version=__version__,
326
+ base_url=base_url,
327
+ max_retries=max_retries,
328
+ timeout=timeout,
329
+ http_client=http_client,
330
+ custom_headers=default_headers,
331
+ custom_query=default_query,
332
+ _strict_response_validation=_strict_response_validation,
333
+ )
334
+
335
+ self.defend = defend.AsyncDefendResource(self)
336
+ self.monitor = monitor.AsyncMonitorResource(self)
337
+ self.evaluate = evaluate.AsyncEvaluateResource(self)
338
+ self.with_raw_response = AsyncDeeprailsWithRawResponse(self)
339
+ self.with_streaming_response = AsyncDeeprailsWithStreamedResponse(self)
340
+
341
+ @property
342
+ @override
343
+ def qs(self) -> Querystring:
344
+ return Querystring(array_format="comma")
345
+
346
+ @property
347
+ @override
348
+ def auth_headers(self) -> dict[str, str]:
349
+ api_key = self.api_key
350
+ return {"Authorization": f"Bearer {api_key}"}
351
+
352
+ @property
353
+ @override
354
+ def default_headers(self) -> dict[str, str | Omit]:
355
+ return {
356
+ **super().default_headers,
357
+ "X-Stainless-Async": f"async:{get_async_library()}",
358
+ **self._custom_headers,
359
+ }
360
+
361
+ def copy(
362
+ self,
363
+ *,
364
+ api_key: str | None = None,
365
+ environment: Literal["production", "environment_1"] | None = None,
366
+ base_url: str | httpx.URL | None = None,
367
+ timeout: float | Timeout | None | NotGiven = not_given,
368
+ http_client: httpx.AsyncClient | None = None,
369
+ max_retries: int | NotGiven = not_given,
370
+ default_headers: Mapping[str, str] | None = None,
371
+ set_default_headers: Mapping[str, str] | None = None,
372
+ default_query: Mapping[str, object] | None = None,
373
+ set_default_query: Mapping[str, object] | None = None,
374
+ _extra_kwargs: Mapping[str, Any] = {},
375
+ ) -> Self:
376
+ """
377
+ Create a new client instance re-using the same options given to the current client with optional overriding.
378
+ """
379
+ if default_headers is not None and set_default_headers is not None:
380
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
381
+
382
+ if default_query is not None and set_default_query is not None:
383
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
384
+
385
+ headers = self._custom_headers
386
+ if default_headers is not None:
387
+ headers = {**headers, **default_headers}
388
+ elif set_default_headers is not None:
389
+ headers = set_default_headers
390
+
391
+ params = self._custom_query
392
+ if default_query is not None:
393
+ params = {**params, **default_query}
394
+ elif set_default_query is not None:
395
+ params = set_default_query
396
+
397
+ http_client = http_client or self._client
398
+ return self.__class__(
399
+ api_key=api_key or self.api_key,
400
+ base_url=base_url or self.base_url,
401
+ environment=environment or self._environment,
402
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
403
+ http_client=http_client,
404
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
405
+ default_headers=headers,
406
+ default_query=params,
407
+ **_extra_kwargs,
408
+ )
409
+
410
+ # Alias for `copy` for nicer inline usage, e.g.
411
+ # client.with_options(timeout=10).foo.create(...)
412
+ with_options = copy
413
+
414
+ @override
415
+ def _make_status_error(
416
+ self,
417
+ err_msg: str,
418
+ *,
419
+ body: object,
420
+ response: httpx.Response,
421
+ ) -> APIStatusError:
422
+ if response.status_code == 400:
423
+ return _exceptions.BadRequestError(err_msg, response=response, body=body)
424
+
425
+ if response.status_code == 401:
426
+ return _exceptions.AuthenticationError(err_msg, response=response, body=body)
427
+
428
+ if response.status_code == 403:
429
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
430
+
431
+ if response.status_code == 404:
432
+ return _exceptions.NotFoundError(err_msg, response=response, body=body)
433
+
434
+ if response.status_code == 409:
435
+ return _exceptions.ConflictError(err_msg, response=response, body=body)
436
+
437
+ if response.status_code == 422:
438
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
439
+
440
+ if response.status_code == 429:
441
+ return _exceptions.RateLimitError(err_msg, response=response, body=body)
442
+
443
+ if response.status_code >= 500:
444
+ return _exceptions.InternalServerError(err_msg, response=response, body=body)
445
+ return APIStatusError(err_msg, response=response, body=body)
446
+
447
+
448
+ class DeeprailsWithRawResponse:
449
+ def __init__(self, client: Deeprails) -> None:
450
+ self.defend = defend.DefendResourceWithRawResponse(client.defend)
451
+ self.monitor = monitor.MonitorResourceWithRawResponse(client.monitor)
452
+ self.evaluate = evaluate.EvaluateResourceWithRawResponse(client.evaluate)
453
+
454
+
455
+ class AsyncDeeprailsWithRawResponse:
456
+ def __init__(self, client: AsyncDeeprails) -> None:
457
+ self.defend = defend.AsyncDefendResourceWithRawResponse(client.defend)
458
+ self.monitor = monitor.AsyncMonitorResourceWithRawResponse(client.monitor)
459
+ self.evaluate = evaluate.AsyncEvaluateResourceWithRawResponse(client.evaluate)
460
+
461
+
462
+ class DeeprailsWithStreamedResponse:
463
+ def __init__(self, client: Deeprails) -> None:
464
+ self.defend = defend.DefendResourceWithStreamingResponse(client.defend)
465
+ self.monitor = monitor.MonitorResourceWithStreamingResponse(client.monitor)
466
+ self.evaluate = evaluate.EvaluateResourceWithStreamingResponse(client.evaluate)
467
+
468
+
469
+ class AsyncDeeprailsWithStreamedResponse:
470
+ def __init__(self, client: AsyncDeeprails) -> None:
471
+ self.defend = defend.AsyncDefendResourceWithStreamingResponse(client.defend)
472
+ self.monitor = monitor.AsyncMonitorResourceWithStreamingResponse(client.monitor)
473
+ self.evaluate = evaluate.AsyncEvaluateResourceWithStreamingResponse(client.evaluate)
474
+
475
+
476
+ Client = Deeprails
477
+
478
+ AsyncClient = AsyncDeeprails
deeprails/_compat.py ADDED
@@ -0,0 +1,219 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
4
+ from datetime import date, datetime
5
+ from typing_extensions import Self, Literal
6
+
7
+ import pydantic
8
+ from pydantic.fields import FieldInfo
9
+
10
+ from ._types import IncEx, StrBytesIntFloat
11
+
12
+ _T = TypeVar("_T")
13
+ _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
14
+
15
+ # --------------- Pydantic v2, v3 compatibility ---------------
16
+
17
+ # Pyright incorrectly reports some of our functions as overriding a method when they don't
18
+ # pyright: reportIncompatibleMethodOverride=false
19
+
20
+ PYDANTIC_V1 = pydantic.VERSION.startswith("1.")
21
+
22
+ if TYPE_CHECKING:
23
+
24
+ def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
25
+ ...
26
+
27
+ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001
28
+ ...
29
+
30
+ def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001
31
+ ...
32
+
33
+ def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001
34
+ ...
35
+
36
+ def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001
37
+ ...
38
+
39
+ def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001
40
+ ...
41
+
42
+ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001
43
+ ...
44
+
45
+ else:
46
+ # v1 re-exports
47
+ if PYDANTIC_V1:
48
+ from pydantic.typing import (
49
+ get_args as get_args,
50
+ is_union as is_union,
51
+ get_origin as get_origin,
52
+ is_typeddict as is_typeddict,
53
+ is_literal_type as is_literal_type,
54
+ )
55
+ from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
56
+ else:
57
+ from ._utils import (
58
+ get_args as get_args,
59
+ is_union as is_union,
60
+ get_origin as get_origin,
61
+ parse_date as parse_date,
62
+ is_typeddict as is_typeddict,
63
+ parse_datetime as parse_datetime,
64
+ is_literal_type as is_literal_type,
65
+ )
66
+
67
+
68
+ # refactored config
69
+ if TYPE_CHECKING:
70
+ from pydantic import ConfigDict as ConfigDict
71
+ else:
72
+ if PYDANTIC_V1:
73
+ # TODO: provide an error message here?
74
+ ConfigDict = None
75
+ else:
76
+ from pydantic import ConfigDict as ConfigDict
77
+
78
+
79
+ # renamed methods / properties
80
+ def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
81
+ if PYDANTIC_V1:
82
+ return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
83
+ else:
84
+ return model.model_validate(value)
85
+
86
+
87
+ def field_is_required(field: FieldInfo) -> bool:
88
+ if PYDANTIC_V1:
89
+ return field.required # type: ignore
90
+ return field.is_required()
91
+
92
+
93
+ def field_get_default(field: FieldInfo) -> Any:
94
+ value = field.get_default()
95
+ if PYDANTIC_V1:
96
+ return value
97
+ from pydantic_core import PydanticUndefined
98
+
99
+ if value == PydanticUndefined:
100
+ return None
101
+ return value
102
+
103
+
104
+ def field_outer_type(field: FieldInfo) -> Any:
105
+ if PYDANTIC_V1:
106
+ return field.outer_type_ # type: ignore
107
+ return field.annotation
108
+
109
+
110
+ def get_model_config(model: type[pydantic.BaseModel]) -> Any:
111
+ if PYDANTIC_V1:
112
+ return model.__config__ # type: ignore
113
+ return model.model_config
114
+
115
+
116
+ def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
117
+ if PYDANTIC_V1:
118
+ return model.__fields__ # type: ignore
119
+ return model.model_fields
120
+
121
+
122
+ def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT:
123
+ if PYDANTIC_V1:
124
+ return model.copy(deep=deep) # type: ignore
125
+ return model.model_copy(deep=deep)
126
+
127
+
128
+ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
129
+ if PYDANTIC_V1:
130
+ return model.json(indent=indent) # type: ignore
131
+ return model.model_dump_json(indent=indent)
132
+
133
+
134
+ def model_dump(
135
+ model: pydantic.BaseModel,
136
+ *,
137
+ exclude: IncEx | None = None,
138
+ exclude_unset: bool = False,
139
+ exclude_defaults: bool = False,
140
+ warnings: bool = True,
141
+ mode: Literal["json", "python"] = "python",
142
+ ) -> dict[str, Any]:
143
+ if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
144
+ return model.model_dump(
145
+ mode=mode,
146
+ exclude=exclude,
147
+ exclude_unset=exclude_unset,
148
+ exclude_defaults=exclude_defaults,
149
+ # warnings are not supported in Pydantic v1
150
+ warnings=True if PYDANTIC_V1 else warnings,
151
+ )
152
+ return cast(
153
+ "dict[str, Any]",
154
+ model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
155
+ exclude=exclude,
156
+ exclude_unset=exclude_unset,
157
+ exclude_defaults=exclude_defaults,
158
+ ),
159
+ )
160
+
161
+
162
+ def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
163
+ if PYDANTIC_V1:
164
+ return model.parse_obj(data) # pyright: ignore[reportDeprecated]
165
+ return model.model_validate(data)
166
+
167
+
168
+ # generic models
169
+ if TYPE_CHECKING:
170
+
171
+ class GenericModel(pydantic.BaseModel): ...
172
+
173
+ else:
174
+ if PYDANTIC_V1:
175
+ import pydantic.generics
176
+
177
+ class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
178
+ else:
179
+ # there no longer needs to be a distinction in v2 but
180
+ # we still have to create our own subclass to avoid
181
+ # inconsistent MRO ordering errors
182
+ class GenericModel(pydantic.BaseModel): ...
183
+
184
+
185
+ # cached properties
186
+ if TYPE_CHECKING:
187
+ cached_property = property
188
+
189
+ # we define a separate type (copied from typeshed)
190
+ # that represents that `cached_property` is `set`able
191
+ # at runtime, which differs from `@property`.
192
+ #
193
+ # this is a separate type as editors likely special case
194
+ # `@property` and we don't want to cause issues just to have
195
+ # more helpful internal types.
196
+
197
+ class typed_cached_property(Generic[_T]):
198
+ func: Callable[[Any], _T]
199
+ attrname: str | None
200
+
201
+ def __init__(self, func: Callable[[Any], _T]) -> None: ...
202
+
203
+ @overload
204
+ def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ...
205
+
206
+ @overload
207
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ...
208
+
209
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self:
210
+ raise NotImplementedError()
211
+
212
+ def __set_name__(self, owner: type[Any], name: str) -> None: ...
213
+
214
+ # __set__ is not defined at runtime, but @cached_property is designed to be settable
215
+ def __set__(self, instance: object, value: _T) -> None: ...
216
+ else:
217
+ from functools import cached_property as cached_property
218
+
219
+ typed_cached_property = cached_property