motor-python-sdk 0.0.2__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 (60) hide show
  1. motor_python_sdk-0.0.2.dist-info/METADATA +230 -0
  2. motor_python_sdk-0.0.2.dist-info/RECORD +60 -0
  3. motor_python_sdk-0.0.2.dist-info/WHEEL +4 -0
  4. yasminaai/__init__.py +113 -0
  5. yasminaai/_default_clients.py +32 -0
  6. yasminaai/client.py +255 -0
  7. yasminaai/core/__init__.py +127 -0
  8. yasminaai/core/api_error.py +23 -0
  9. yasminaai/core/client_wrapper.py +119 -0
  10. yasminaai/core/datetime_utils.py +70 -0
  11. yasminaai/core/file.py +67 -0
  12. yasminaai/core/force_multipart.py +18 -0
  13. yasminaai/core/http_client.py +839 -0
  14. yasminaai/core/http_response.py +59 -0
  15. yasminaai/core/http_sse/__init__.py +42 -0
  16. yasminaai/core/http_sse/_api.py +170 -0
  17. yasminaai/core/http_sse/_decoders.py +61 -0
  18. yasminaai/core/http_sse/_exceptions.py +7 -0
  19. yasminaai/core/http_sse/_models.py +17 -0
  20. yasminaai/core/jsonable_encoder.py +120 -0
  21. yasminaai/core/logging.py +107 -0
  22. yasminaai/core/parse_error.py +36 -0
  23. yasminaai/core/pydantic_utilities.py +508 -0
  24. yasminaai/core/query_encoder.py +58 -0
  25. yasminaai/core/remove_none_from_dict.py +11 -0
  26. yasminaai/core/request_options.py +35 -0
  27. yasminaai/core/serialization.py +347 -0
  28. yasminaai/environment.py +7 -0
  29. yasminaai/errors/__init__.py +42 -0
  30. yasminaai/errors/bad_request_error.py +10 -0
  31. yasminaai/errors/not_found_error.py +10 -0
  32. yasminaai/errors/unauthorized_error.py +10 -0
  33. yasminaai/errors/unprocessable_entity_error.py +10 -0
  34. yasminaai/ot_ps/__init__.py +4 -0
  35. yasminaai/ot_ps/client.py +278 -0
  36. yasminaai/ot_ps/raw_client.py +355 -0
  37. yasminaai/policies/__init__.py +4 -0
  38. yasminaai/policies/client.py +393 -0
  39. yasminaai/policies/raw_client.py +493 -0
  40. yasminaai/py.typed +0 -0
  41. yasminaai/quotes/__init__.py +49 -0
  42. yasminaai/quotes/client.py +438 -0
  43. yasminaai/quotes/raw_client.py +548 -0
  44. yasminaai/quotes/types/__init__.py +47 -0
  45. yasminaai/quotes/types/delete_quote_requests_id_response.py +19 -0
  46. yasminaai/quotes/types/get_quote_requests_response.py +37 -0
  47. yasminaai/quotes/types/get_quote_requests_response_links_item.py +21 -0
  48. yasminaai/quotes/types/post_quote_requests_request_drivers_item.py +33 -0
  49. yasminaai/types/__init__.py +65 -0
  50. yasminaai/types/bad_request_error_body.py +20 -0
  51. yasminaai/types/benefit.py +24 -0
  52. yasminaai/types/company_quote.py +23 -0
  53. yasminaai/types/error.py +20 -0
  54. yasminaai/types/policy.py +33 -0
  55. yasminaai/types/quote_price.py +24 -0
  56. yasminaai/types/quote_response.py +90 -0
  57. yasminaai/types/quote_response_drivers_item.py +33 -0
  58. yasminaai/types/quote_response_quotes_item.py +30 -0
  59. yasminaai/types/unauthorized_error_body.py +20 -0
  60. yasminaai/version.py +3 -0
@@ -0,0 +1,508 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ # nopycln: file
4
+ import datetime as dt
5
+ import inspect
6
+ import json
7
+ import logging
8
+ from collections import defaultdict
9
+ from dataclasses import asdict
10
+ from typing import (
11
+ TYPE_CHECKING,
12
+ Any,
13
+ Callable,
14
+ ClassVar,
15
+ Dict,
16
+ List,
17
+ Mapping,
18
+ Optional,
19
+ Set,
20
+ Tuple,
21
+ Type,
22
+ TypeVar,
23
+ Union,
24
+ cast,
25
+ )
26
+
27
+ import pydantic
28
+ import typing_extensions
29
+ from pydantic.fields import FieldInfo as _FieldInfo
30
+
31
+ _logger = logging.getLogger(__name__)
32
+
33
+ if TYPE_CHECKING:
34
+ from .http_sse._models import ServerSentEvent
35
+
36
+ IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
37
+
38
+ if IS_PYDANTIC_V2:
39
+ _datetime_adapter = pydantic.TypeAdapter(dt.datetime) # type: ignore[attr-defined]
40
+ _date_adapter = pydantic.TypeAdapter(dt.date) # type: ignore[attr-defined]
41
+
42
+ def parse_datetime(value: Any) -> dt.datetime: # type: ignore[misc]
43
+ if isinstance(value, dt.datetime):
44
+ return value
45
+ return _datetime_adapter.validate_python(value)
46
+
47
+ def parse_date(value: Any) -> dt.date: # type: ignore[misc]
48
+ if isinstance(value, dt.datetime):
49
+ return value.date()
50
+ if isinstance(value, dt.date):
51
+ return value
52
+ return _date_adapter.validate_python(value)
53
+
54
+ # Avoid importing from pydantic.v1 to maintain Python 3.14 compatibility.
55
+ from typing import get_args as get_args # type: ignore[assignment]
56
+ from typing import get_origin as get_origin # type: ignore[assignment]
57
+
58
+ def is_literal_type(tp: Optional[Type[Any]]) -> bool: # type: ignore[misc]
59
+ return typing_extensions.get_origin(tp) is typing_extensions.Literal
60
+
61
+ def is_union(tp: Optional[Type[Any]]) -> bool: # type: ignore[misc]
62
+ return tp is Union or typing_extensions.get_origin(tp) is Union # type: ignore[comparison-overlap]
63
+
64
+ # Inline encoders_by_type to avoid importing from pydantic.v1.json
65
+ import re as _re
66
+ from collections import deque as _deque
67
+ from decimal import Decimal as _Decimal
68
+ from enum import Enum as _Enum
69
+ from ipaddress import (
70
+ IPv4Address as _IPv4Address,
71
+ )
72
+ from ipaddress import (
73
+ IPv4Interface as _IPv4Interface,
74
+ )
75
+ from ipaddress import (
76
+ IPv4Network as _IPv4Network,
77
+ )
78
+ from ipaddress import (
79
+ IPv6Address as _IPv6Address,
80
+ )
81
+ from ipaddress import (
82
+ IPv6Interface as _IPv6Interface,
83
+ )
84
+ from ipaddress import (
85
+ IPv6Network as _IPv6Network,
86
+ )
87
+ from pathlib import Path as _Path
88
+ from types import GeneratorType as _GeneratorType
89
+ from uuid import UUID as _UUID
90
+
91
+ from pydantic.fields import FieldInfo as ModelField # type: ignore[no-redef, assignment]
92
+
93
+ def _decimal_encoder(dec_value: Any) -> Any:
94
+ if dec_value.as_tuple().exponent >= 0:
95
+ return int(dec_value)
96
+ return float(dec_value)
97
+
98
+ encoders_by_type: Dict[Type[Any], Callable[[Any], Any]] = { # type: ignore[no-redef]
99
+ bytes: lambda o: o.decode(),
100
+ dt.date: lambda o: o.isoformat(),
101
+ dt.datetime: lambda o: o.isoformat(),
102
+ dt.time: lambda o: o.isoformat(),
103
+ dt.timedelta: lambda td: td.total_seconds(),
104
+ _Decimal: _decimal_encoder,
105
+ _Enum: lambda o: o.value,
106
+ frozenset: list,
107
+ _deque: list,
108
+ _GeneratorType: list,
109
+ _IPv4Address: str,
110
+ _IPv4Interface: str,
111
+ _IPv4Network: str,
112
+ _IPv6Address: str,
113
+ _IPv6Interface: str,
114
+ _IPv6Network: str,
115
+ _Path: str,
116
+ _re.Pattern: lambda o: o.pattern,
117
+ set: list,
118
+ _UUID: str,
119
+ }
120
+ else:
121
+ from pydantic.datetime_parse import parse_date as parse_date # type: ignore[no-redef]
122
+ from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore[no-redef]
123
+ from pydantic.fields import ModelField as ModelField # type: ignore[attr-defined, no-redef, assignment]
124
+ from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[no-redef]
125
+ from pydantic.typing import get_args as get_args # type: ignore[no-redef]
126
+ from pydantic.typing import get_origin as get_origin # type: ignore[no-redef]
127
+ from pydantic.typing import is_literal_type as is_literal_type # type: ignore[no-redef, assignment]
128
+ from pydantic.typing import is_union as is_union # type: ignore[no-redef]
129
+
130
+ from .datetime_utils import serialize_datetime
131
+ from .serialization import convert_and_respect_annotation_metadata
132
+ from typing_extensions import TypeAlias
133
+
134
+ T = TypeVar("T")
135
+ Model = TypeVar("Model", bound=pydantic.BaseModel)
136
+
137
+
138
+ def parse_sse_obj(sse: "ServerSentEvent", type_: Type[T]) -> T:
139
+ """
140
+ Parse a ServerSentEvent into the appropriate type.
141
+
142
+ This function handles data-level discrimination where the discriminator
143
+ (e.g., 'type') is inside the 'data' payload. It parses the SSE data field
144
+ as JSON and deserializes it into the target type.
145
+
146
+ Note: Protocol-level discrimination (where the discriminator comes from
147
+ the SSE event: field) is handled at code-generation time and does not
148
+ use this function.
149
+
150
+ Args:
151
+ sse: The ServerSentEvent object to parse
152
+ type_: The target type to deserialize into
153
+
154
+ Returns:
155
+ The parsed object of type T
156
+
157
+ Note:
158
+ This function is only available in SDK contexts where http_sse module exists.
159
+ """
160
+ sse_event = asdict(sse)
161
+ data_value = sse_event.get("data")
162
+ if isinstance(data_value, str) and data_value:
163
+ try:
164
+ parsed_data = json.loads(data_value)
165
+ return parse_obj_as(type_, parsed_data)
166
+ except json.JSONDecodeError as e:
167
+ _logger.warning(
168
+ "Failed to parse SSE data field as JSON: %s, data: %s",
169
+ e,
170
+ data_value[:100] if len(data_value) > 100 else data_value,
171
+ )
172
+ return parse_obj_as(type_, sse_event)
173
+
174
+
175
+ _type_adapter_cache: Dict[int, Any] = {}
176
+
177
+
178
+ def _get_type_adapter(type_: Type[Any]) -> Any:
179
+ key = id(type_)
180
+ adapter = _type_adapter_cache.get(key)
181
+ if adapter is None:
182
+ adapter = pydantic.TypeAdapter(type_) # type: ignore[attr-defined]
183
+ _type_adapter_cache[key] = adapter
184
+ return adapter
185
+
186
+
187
+ def parse_obj_as(type_: Type[T], object_: Any) -> T:
188
+ # convert_and_respect_annotation_metadata is required for TypedDict aliasing.
189
+ #
190
+ # For Pydantic models, whether we should pre-dealias depends on how the model encodes aliasing:
191
+ # - If the model uses real Pydantic aliases (pydantic.Field(alias=...)), then we must pass wire keys through
192
+ # unchanged so Pydantic can validate them.
193
+ # - If the model encodes aliasing only via FieldMetadata annotations, then we MUST pre-dealias because Pydantic
194
+ # will not recognize those aliases during validation.
195
+ if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
196
+ has_pydantic_aliases = False
197
+ if IS_PYDANTIC_V2:
198
+ for field_name, field_info in getattr(type_, "model_fields", {}).items(): # type: ignore[attr-defined]
199
+ alias = getattr(field_info, "alias", None)
200
+ if alias is not None and alias != field_name:
201
+ has_pydantic_aliases = True
202
+ break
203
+ else:
204
+ for field in getattr(type_, "__fields__", {}).values():
205
+ alias = getattr(field, "alias", None)
206
+ name = getattr(field, "name", None)
207
+ if alias is not None and name is not None and alias != name:
208
+ has_pydantic_aliases = True
209
+ break
210
+
211
+ dealiased_object = (
212
+ object_
213
+ if has_pydantic_aliases
214
+ else convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read")
215
+ )
216
+ else:
217
+ dealiased_object = convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read")
218
+ if IS_PYDANTIC_V2:
219
+ adapter = _get_type_adapter(type_)
220
+ return adapter.validate_python(dealiased_object) # type: ignore[no-any-return]
221
+ return pydantic.parse_obj_as(type_, dealiased_object)
222
+
223
+
224
+ def to_jsonable_with_fallback(obj: Any, fallback_serializer: Callable[[Any], Any]) -> Any:
225
+ if IS_PYDANTIC_V2:
226
+ from pydantic_core import to_jsonable_python
227
+
228
+ return to_jsonable_python(obj, fallback=fallback_serializer)
229
+ return fallback_serializer(obj)
230
+
231
+
232
+ class UniversalBaseModel(pydantic.BaseModel):
233
+ if IS_PYDANTIC_V2:
234
+ model_config: ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( # type: ignore[typeddict-unknown-key]
235
+ # Allow fields beginning with `model_` to be used in the model
236
+ protected_namespaces=(),
237
+ )
238
+
239
+ @pydantic.model_validator(mode="before") # type: ignore[attr-defined]
240
+ @classmethod
241
+ def _coerce_field_names_to_aliases(cls, data: Any) -> Any:
242
+ """
243
+ Accept Python field names in input by rewriting them to their Pydantic aliases,
244
+ while avoiding silent collisions when a key could refer to multiple fields.
245
+ """
246
+ if not isinstance(data, Mapping):
247
+ return data
248
+
249
+ fields = getattr(cls, "model_fields", {}) # type: ignore[attr-defined]
250
+ name_to_alias: Dict[str, str] = {}
251
+ alias_to_name: Dict[str, str] = {}
252
+
253
+ for name, field_info in fields.items():
254
+ alias = getattr(field_info, "alias", None) or name
255
+ name_to_alias[name] = alias
256
+ if alias != name:
257
+ alias_to_name[alias] = name
258
+
259
+ # Detect ambiguous keys: a key that is an alias for one field and a name for another.
260
+ ambiguous_keys = set(alias_to_name.keys()).intersection(set(name_to_alias.keys()))
261
+ for key in ambiguous_keys:
262
+ if key in data and name_to_alias[key] not in data:
263
+ raise ValueError(
264
+ f"Ambiguous input key '{key}': it is both a field name and an alias. "
265
+ "Provide the explicit alias key to disambiguate."
266
+ )
267
+
268
+ original_keys = set(data.keys())
269
+ rewritten: Dict[str, Any] = dict(data)
270
+ for name, alias in name_to_alias.items():
271
+ if alias != name and name in original_keys and alias not in rewritten:
272
+ rewritten[alias] = rewritten.pop(name)
273
+
274
+ return rewritten
275
+
276
+ @pydantic.model_serializer(mode="plain", when_used="json") # type: ignore[attr-defined]
277
+ def serialize_model(self) -> Any: # type: ignore[name-defined]
278
+ serialized = self.dict() # type: ignore[attr-defined]
279
+ data = {k: serialize_datetime(v) if isinstance(v, dt.datetime) else v for k, v in serialized.items()}
280
+ return data
281
+
282
+ else:
283
+
284
+ class Config:
285
+ smart_union = True
286
+ json_encoders = {dt.datetime: serialize_datetime}
287
+
288
+ @pydantic.root_validator(pre=True)
289
+ def _coerce_field_names_to_aliases(cls, values: Any) -> Any:
290
+ """
291
+ Pydantic v1 equivalent of _coerce_field_names_to_aliases.
292
+ """
293
+ if not isinstance(values, Mapping):
294
+ return values
295
+
296
+ fields = getattr(cls, "__fields__", {})
297
+ name_to_alias: Dict[str, str] = {}
298
+ alias_to_name: Dict[str, str] = {}
299
+
300
+ for name, field in fields.items():
301
+ alias = getattr(field, "alias", None) or name
302
+ name_to_alias[name] = alias
303
+ if alias != name:
304
+ alias_to_name[alias] = name
305
+
306
+ ambiguous_keys = set(alias_to_name.keys()).intersection(set(name_to_alias.keys()))
307
+ for key in ambiguous_keys:
308
+ if key in values and name_to_alias[key] not in values:
309
+ raise ValueError(
310
+ f"Ambiguous input key '{key}': it is both a field name and an alias. "
311
+ "Provide the explicit alias key to disambiguate."
312
+ )
313
+
314
+ original_keys = set(values.keys())
315
+ rewritten: Dict[str, Any] = dict(values)
316
+ for name, alias in name_to_alias.items():
317
+ if alias != name and name in original_keys and alias not in rewritten:
318
+ rewritten[alias] = rewritten.pop(name)
319
+
320
+ return rewritten
321
+
322
+ @classmethod
323
+ def model_construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model":
324
+ dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
325
+ return cls.construct(_fields_set, **dealiased_object)
326
+
327
+ @classmethod
328
+ def construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model":
329
+ dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
330
+ if IS_PYDANTIC_V2:
331
+ return super().model_construct(_fields_set, **dealiased_object) # type: ignore[misc]
332
+ return super().construct(_fields_set, **dealiased_object)
333
+
334
+ def json(self, **kwargs: Any) -> str:
335
+ kwargs_with_defaults = {
336
+ "by_alias": True,
337
+ "exclude_unset": True,
338
+ **kwargs,
339
+ }
340
+ if IS_PYDANTIC_V2:
341
+ return super().model_dump_json(**kwargs_with_defaults) # type: ignore[misc]
342
+ return super().json(**kwargs_with_defaults)
343
+
344
+ def dict(self, **kwargs: Any) -> Dict[str, Any]:
345
+ """
346
+ Override the default dict method to `exclude_unset` by default. This function patches
347
+ `exclude_unset` to work include fields within non-None default values.
348
+ """
349
+ # Note: the logic here is multiplexed given the levers exposed in Pydantic V1 vs V2
350
+ # Pydantic V1's .dict can be extremely slow, so we do not want to call it twice.
351
+ #
352
+ # We'd ideally do the same for Pydantic V2, but it shells out to a library to serialize models
353
+ # that we have less control over, and this is less intrusive than custom serializers for now.
354
+ if IS_PYDANTIC_V2:
355
+ kwargs_with_defaults_exclude_unset = {
356
+ **kwargs,
357
+ "by_alias": True,
358
+ "exclude_unset": True,
359
+ "exclude_none": False,
360
+ }
361
+ kwargs_with_defaults_exclude_none = {
362
+ **kwargs,
363
+ "by_alias": True,
364
+ "exclude_none": True,
365
+ "exclude_unset": False,
366
+ }
367
+ dict_dump = deep_union_pydantic_dicts(
368
+ super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore[misc]
369
+ super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore[misc]
370
+ )
371
+
372
+ else:
373
+ _fields_set = self.__fields_set__.copy()
374
+
375
+ fields = _get_model_fields(self.__class__)
376
+ for name, field in fields.items():
377
+ if name not in _fields_set:
378
+ default = _get_field_default(field)
379
+
380
+ # If the default values are non-null act like they've been set
381
+ # This effectively allows exclude_unset to work like exclude_none where
382
+ # the latter passes through intentionally set none values.
383
+ if default is not None or ("exclude_unset" in kwargs and not kwargs["exclude_unset"]):
384
+ _fields_set.add(name)
385
+
386
+ if default is not None:
387
+ self.__fields_set__.add(name)
388
+
389
+ kwargs_with_defaults_exclude_unset_include_fields = {
390
+ "by_alias": True,
391
+ "exclude_unset": True,
392
+ "include": _fields_set,
393
+ **kwargs,
394
+ }
395
+
396
+ dict_dump = super().dict(**kwargs_with_defaults_exclude_unset_include_fields)
397
+
398
+ return cast(
399
+ Dict[str, Any],
400
+ convert_and_respect_annotation_metadata(object_=dict_dump, annotation=self.__class__, direction="write"),
401
+ )
402
+
403
+
404
+ def _union_list_of_pydantic_dicts(source: List[Any], destination: List[Any]) -> List[Any]:
405
+ converted_list: List[Any] = []
406
+ for i, item in enumerate(source):
407
+ destination_value = destination[i]
408
+ if isinstance(item, dict):
409
+ converted_list.append(deep_union_pydantic_dicts(item, destination_value))
410
+ elif isinstance(item, list):
411
+ converted_list.append(_union_list_of_pydantic_dicts(item, destination_value))
412
+ else:
413
+ converted_list.append(item)
414
+ return converted_list
415
+
416
+
417
+ def deep_union_pydantic_dicts(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]:
418
+ for key, value in source.items():
419
+ node = destination.setdefault(key, {})
420
+ if isinstance(value, dict):
421
+ deep_union_pydantic_dicts(value, node)
422
+ # Note: we do not do this same processing for sets given we do not have sets of models
423
+ # and given the sets are unordered, the processing of the set and matching objects would
424
+ # be non-trivial.
425
+ elif isinstance(value, list):
426
+ destination[key] = _union_list_of_pydantic_dicts(value, node)
427
+ else:
428
+ destination[key] = value
429
+
430
+ return destination
431
+
432
+
433
+ if IS_PYDANTIC_V2:
434
+
435
+ class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore[misc, name-defined, type-arg]
436
+ pass
437
+
438
+ UniversalRootModel: TypeAlias = V2RootModel # type: ignore[misc]
439
+ else:
440
+ UniversalRootModel: TypeAlias = UniversalBaseModel # type: ignore[misc, no-redef]
441
+
442
+
443
+ def encode_by_type(o: Any) -> Any:
444
+ encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple)
445
+ for type_, encoder in encoders_by_type.items():
446
+ encoders_by_class_tuples[encoder] += (type_,)
447
+
448
+ if type(o) in encoders_by_type:
449
+ return encoders_by_type[type(o)](o)
450
+ for encoder, classes_tuple in encoders_by_class_tuples.items():
451
+ if isinstance(o, classes_tuple):
452
+ return encoder(o)
453
+
454
+
455
+ def update_forward_refs(model: Type["Model"], **localns: Any) -> None:
456
+ if IS_PYDANTIC_V2:
457
+ model.model_rebuild(raise_errors=False) # type: ignore[attr-defined]
458
+ else:
459
+ model.update_forward_refs(**localns)
460
+
461
+
462
+ # Mirrors Pydantic's internal typing
463
+ AnyCallable = Callable[..., Any]
464
+
465
+
466
+ def universal_root_validator(
467
+ pre: bool = False,
468
+ ) -> Callable[[AnyCallable], AnyCallable]:
469
+ def decorator(func: AnyCallable) -> AnyCallable:
470
+ if IS_PYDANTIC_V2:
471
+ # In Pydantic v2, for RootModel we always use "before" mode
472
+ # The custom validators transform the input value before the model is created
473
+ return cast(AnyCallable, pydantic.model_validator(mode="before")(func)) # type: ignore[attr-defined]
474
+ return cast(AnyCallable, pydantic.root_validator(pre=pre)(func)) # type: ignore[call-overload]
475
+
476
+ return decorator
477
+
478
+
479
+ def universal_field_validator(field_name: str, pre: bool = False) -> Callable[[AnyCallable], AnyCallable]:
480
+ def decorator(func: AnyCallable) -> AnyCallable:
481
+ if IS_PYDANTIC_V2:
482
+ return cast(AnyCallable, pydantic.field_validator(field_name, mode="before" if pre else "after")(func)) # type: ignore[attr-defined]
483
+ return cast(AnyCallable, pydantic.validator(field_name, pre=pre)(func))
484
+
485
+ return decorator
486
+
487
+
488
+ PydanticField = Union[ModelField, _FieldInfo]
489
+
490
+
491
+ def _get_model_fields(model: Type["Model"]) -> Mapping[str, PydanticField]:
492
+ if IS_PYDANTIC_V2:
493
+ return cast(Mapping[str, PydanticField], model.model_fields) # type: ignore[attr-defined]
494
+ return cast(Mapping[str, PydanticField], model.__fields__)
495
+
496
+
497
+ def _get_field_default(field: PydanticField) -> Any:
498
+ try:
499
+ value = field.get_default() # type: ignore[union-attr]
500
+ except:
501
+ value = field.default
502
+ if IS_PYDANTIC_V2:
503
+ from pydantic_core import PydanticUndefined
504
+
505
+ if value == PydanticUndefined:
506
+ return None
507
+ return value
508
+ return value
@@ -0,0 +1,58 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ import pydantic
6
+
7
+
8
+ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict
9
+ def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> List[Tuple[str, Any]]:
10
+ result = []
11
+ for k, v in dict_flat.items():
12
+ key = f"{key_prefix}[{k}]" if key_prefix is not None else k
13
+ if isinstance(v, dict):
14
+ result.extend(traverse_query_dict(v, key))
15
+ elif isinstance(v, list):
16
+ for arr_v in v:
17
+ if isinstance(arr_v, dict):
18
+ result.extend(traverse_query_dict(arr_v, key))
19
+ else:
20
+ result.append((key, arr_v))
21
+ else:
22
+ result.append((key, v))
23
+ return result
24
+
25
+
26
+ def single_query_encoder(query_key: str, query_value: Any) -> List[Tuple[str, Any]]:
27
+ if isinstance(query_value, pydantic.BaseModel) or isinstance(query_value, dict):
28
+ if isinstance(query_value, pydantic.BaseModel):
29
+ obj_dict = query_value.dict(by_alias=True)
30
+ else:
31
+ obj_dict = query_value
32
+ return traverse_query_dict(obj_dict, query_key)
33
+ elif isinstance(query_value, list):
34
+ encoded_values: List[Tuple[str, Any]] = []
35
+ for value in query_value:
36
+ if isinstance(value, pydantic.BaseModel) or isinstance(value, dict):
37
+ if isinstance(value, pydantic.BaseModel):
38
+ obj_dict = value.dict(by_alias=True)
39
+ elif isinstance(value, dict):
40
+ obj_dict = value
41
+
42
+ encoded_values.extend(single_query_encoder(query_key, obj_dict))
43
+ else:
44
+ encoded_values.append((query_key, value))
45
+
46
+ return encoded_values
47
+
48
+ return [(query_key, query_value)]
49
+
50
+
51
+ def encode_query(query: Optional[Dict[str, Any]]) -> Optional[List[Tuple[str, Any]]]:
52
+ if query is None:
53
+ return None
54
+
55
+ encoded_query = []
56
+ for k, v in query.items():
57
+ encoded_query.extend(single_query_encoder(k, v))
58
+ return encoded_query
@@ -0,0 +1,11 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from typing import Any, Dict, Mapping, Optional
4
+
5
+
6
+ def remove_none_from_dict(original: Mapping[str, Optional[Any]]) -> Dict[str, Any]:
7
+ new: Dict[str, Any] = {}
8
+ for key, value in original.items():
9
+ if value is not None:
10
+ new[key] = value
11
+ return new
@@ -0,0 +1,35 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+ try:
6
+ from typing import NotRequired # type: ignore
7
+ except ImportError:
8
+ from typing_extensions import NotRequired
9
+
10
+
11
+ class RequestOptions(typing.TypedDict, total=False):
12
+ """
13
+ Additional options for request-specific configuration when calling APIs via the SDK.
14
+ This is used primarily as an optional final parameter for service functions.
15
+
16
+ Attributes:
17
+ - timeout_in_seconds: int. The number of seconds to await an API call before timing out.
18
+
19
+ - max_retries: int. The max number of retries to attempt if the API call fails.
20
+
21
+ - additional_headers: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's header dict
22
+
23
+ - additional_query_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's query parameters dict
24
+
25
+ - additional_body_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's body parameters dict
26
+
27
+ - chunk_size: int. The size, in bytes, to process each chunk of data being streamed back within the response. This equates to leveraging `chunk_size` within `requests` or `httpx`, and is only leveraged for file downloads.
28
+ """
29
+
30
+ timeout_in_seconds: NotRequired[int]
31
+ max_retries: NotRequired[int]
32
+ additional_headers: NotRequired[typing.Dict[str, typing.Any]]
33
+ additional_query_parameters: NotRequired[typing.Dict[str, typing.Any]]
34
+ additional_body_parameters: NotRequired[typing.Dict[str, typing.Any]]
35
+ chunk_size: NotRequired[int]