payi 0.1.0a1__py3-none-any.whl

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

Potentially problematic release.


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

Files changed (54) hide show
  1. payi/__init__.py +83 -0
  2. payi/_base_client.py +2006 -0
  3. payi/_client.py +414 -0
  4. payi/_compat.py +222 -0
  5. payi/_constants.py +14 -0
  6. payi/_exceptions.py +108 -0
  7. payi/_files.py +127 -0
  8. payi/_models.py +739 -0
  9. payi/_qs.py +150 -0
  10. payi/_resource.py +43 -0
  11. payi/_response.py +820 -0
  12. payi/_streaming.py +333 -0
  13. payi/_types.py +220 -0
  14. payi/_utils/__init__.py +52 -0
  15. payi/_utils/_logs.py +25 -0
  16. payi/_utils/_proxy.py +63 -0
  17. payi/_utils/_reflection.py +8 -0
  18. payi/_utils/_streams.py +12 -0
  19. payi/_utils/_sync.py +81 -0
  20. payi/_utils/_transform.py +382 -0
  21. payi/_utils/_typing.py +120 -0
  22. payi/_utils/_utils.py +402 -0
  23. payi/_version.py +4 -0
  24. payi/lib/.keep +4 -0
  25. payi/py.typed +0 -0
  26. payi/resources/__init__.py +33 -0
  27. payi/resources/budgets/__init__.py +33 -0
  28. payi/resources/budgets/budgets.py +717 -0
  29. payi/resources/budgets/tags.py +529 -0
  30. payi/resources/ingest_requests.py +187 -0
  31. payi/types/__init__.py +13 -0
  32. payi/types/budget_create_params.py +26 -0
  33. payi/types/budget_history_response.py +110 -0
  34. payi/types/budget_list_params.py +25 -0
  35. payi/types/budget_response.py +98 -0
  36. payi/types/budget_update_params.py +17 -0
  37. payi/types/budgets/__init__.py +13 -0
  38. payi/types/budgets/budget_tags_response.py +18 -0
  39. payi/types/budgets/tag_create_params.py +16 -0
  40. payi/types/budgets/tag_create_response.py +9 -0
  41. payi/types/budgets/tag_delete_response.py +9 -0
  42. payi/types/budgets/tag_list_response.py +9 -0
  43. payi/types/budgets/tag_remove_params.py +16 -0
  44. payi/types/budgets/tag_remove_response.py +9 -0
  45. payi/types/budgets/tag_update_params.py +16 -0
  46. payi/types/budgets/tag_update_response.py +9 -0
  47. payi/types/default_response.py +13 -0
  48. payi/types/ingest_request_create_params.py +27 -0
  49. payi/types/paged_budget_list.py +110 -0
  50. payi/types/successful_proxy_result.py +43 -0
  51. payi-0.1.0a1.dist-info/METADATA +355 -0
  52. payi-0.1.0a1.dist-info/RECORD +54 -0
  53. payi-0.1.0a1.dist-info/WHEEL +4 -0
  54. payi-0.1.0a1.dist-info/licenses/LICENSE +201 -0
payi/_base_client.py ADDED
@@ -0,0 +1,2006 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ import uuid
6
+ import email
7
+ import asyncio
8
+ import inspect
9
+ import logging
10
+ import platform
11
+ import warnings
12
+ import email.utils
13
+ from types import TracebackType
14
+ from random import random
15
+ from typing import (
16
+ TYPE_CHECKING,
17
+ Any,
18
+ Dict,
19
+ Type,
20
+ Union,
21
+ Generic,
22
+ Mapping,
23
+ TypeVar,
24
+ Iterable,
25
+ Iterator,
26
+ Optional,
27
+ Generator,
28
+ AsyncIterator,
29
+ cast,
30
+ overload,
31
+ )
32
+ from typing_extensions import Literal, override, get_origin
33
+
34
+ import anyio
35
+ import httpx
36
+ import distro
37
+ import pydantic
38
+ from httpx import URL, Limits
39
+ from pydantic import PrivateAttr
40
+
41
+ from . import _exceptions
42
+ from ._qs import Querystring
43
+ from ._files import to_httpx_files, async_to_httpx_files
44
+ from ._types import (
45
+ NOT_GIVEN,
46
+ Body,
47
+ Omit,
48
+ Query,
49
+ Headers,
50
+ Timeout,
51
+ NotGiven,
52
+ ResponseT,
53
+ Transport,
54
+ AnyMapping,
55
+ PostParser,
56
+ ProxiesTypes,
57
+ RequestFiles,
58
+ HttpxSendArgs,
59
+ AsyncTransport,
60
+ RequestOptions,
61
+ ModelBuilderProtocol,
62
+ )
63
+ from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping
64
+ from ._compat import model_copy, model_dump
65
+ from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type
66
+ from ._response import (
67
+ APIResponse,
68
+ BaseAPIResponse,
69
+ AsyncAPIResponse,
70
+ extract_response_type,
71
+ )
72
+ from ._constants import (
73
+ DEFAULT_TIMEOUT,
74
+ MAX_RETRY_DELAY,
75
+ DEFAULT_MAX_RETRIES,
76
+ INITIAL_RETRY_DELAY,
77
+ RAW_RESPONSE_HEADER,
78
+ OVERRIDE_CAST_TO_HEADER,
79
+ DEFAULT_CONNECTION_LIMITS,
80
+ )
81
+ from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder
82
+ from ._exceptions import (
83
+ APIStatusError,
84
+ APITimeoutError,
85
+ APIConnectionError,
86
+ APIResponseValidationError,
87
+ )
88
+
89
+ log: logging.Logger = logging.getLogger(__name__)
90
+
91
+ # TODO: make base page type vars covariant
92
+ SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]")
93
+ AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]")
94
+
95
+
96
+ _T = TypeVar("_T")
97
+ _T_co = TypeVar("_T_co", covariant=True)
98
+
99
+ _StreamT = TypeVar("_StreamT", bound=Stream[Any])
100
+ _AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any])
101
+
102
+ if TYPE_CHECKING:
103
+ from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT
104
+ else:
105
+ try:
106
+ from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT
107
+ except ImportError:
108
+ # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366
109
+ HTTPX_DEFAULT_TIMEOUT = Timeout(5.0)
110
+
111
+
112
+ class PageInfo:
113
+ """Stores the necessary information to build the request to retrieve the next page.
114
+
115
+ Either `url` or `params` must be set.
116
+ """
117
+
118
+ url: URL | NotGiven
119
+ params: Query | NotGiven
120
+
121
+ @overload
122
+ def __init__(
123
+ self,
124
+ *,
125
+ url: URL,
126
+ ) -> None:
127
+ ...
128
+
129
+ @overload
130
+ def __init__(
131
+ self,
132
+ *,
133
+ params: Query,
134
+ ) -> None:
135
+ ...
136
+
137
+ def __init__(
138
+ self,
139
+ *,
140
+ url: URL | NotGiven = NOT_GIVEN,
141
+ params: Query | NotGiven = NOT_GIVEN,
142
+ ) -> None:
143
+ self.url = url
144
+ self.params = params
145
+
146
+
147
+ class BasePage(GenericModel, Generic[_T]):
148
+ """
149
+ Defines the core interface for pagination.
150
+
151
+ Type Args:
152
+ ModelT: The pydantic model that represents an item in the response.
153
+
154
+ Methods:
155
+ has_next_page(): Check if there is another page available
156
+ next_page_info(): Get the necessary information to make a request for the next page
157
+ """
158
+
159
+ _options: FinalRequestOptions = PrivateAttr()
160
+ _model: Type[_T] = PrivateAttr()
161
+
162
+ def has_next_page(self) -> bool:
163
+ items = self._get_page_items()
164
+ if not items:
165
+ return False
166
+ return self.next_page_info() is not None
167
+
168
+ def next_page_info(self) -> Optional[PageInfo]:
169
+ ...
170
+
171
+ def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body]
172
+ ...
173
+
174
+ def _params_from_url(self, url: URL) -> httpx.QueryParams:
175
+ # TODO: do we have to preprocess params here?
176
+ return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params)
177
+
178
+ def _info_to_options(self, info: PageInfo) -> FinalRequestOptions:
179
+ options = model_copy(self._options)
180
+ options._strip_raw_response_header()
181
+
182
+ if not isinstance(info.params, NotGiven):
183
+ options.params = {**options.params, **info.params}
184
+ return options
185
+
186
+ if not isinstance(info.url, NotGiven):
187
+ params = self._params_from_url(info.url)
188
+ url = info.url.copy_with(params=params)
189
+ options.params = dict(url.params)
190
+ options.url = str(url)
191
+ return options
192
+
193
+ raise ValueError("Unexpected PageInfo state")
194
+
195
+
196
+ class BaseSyncPage(BasePage[_T], Generic[_T]):
197
+ _client: SyncAPIClient = pydantic.PrivateAttr()
198
+
199
+ def _set_private_attributes(
200
+ self,
201
+ client: SyncAPIClient,
202
+ model: Type[_T],
203
+ options: FinalRequestOptions,
204
+ ) -> None:
205
+ self._model = model
206
+ self._client = client
207
+ self._options = options
208
+
209
+ # Pydantic uses a custom `__iter__` method to support casting BaseModels
210
+ # to dictionaries. e.g. dict(model).
211
+ # As we want to support `for item in page`, this is inherently incompatible
212
+ # with the default pydantic behaviour. It is not possible to support both
213
+ # use cases at once. Fortunately, this is not a big deal as all other pydantic
214
+ # methods should continue to work as expected as there is an alternative method
215
+ # to cast a model to a dictionary, model.dict(), which is used internally
216
+ # by pydantic.
217
+ def __iter__(self) -> Iterator[_T]: # type: ignore
218
+ for page in self.iter_pages():
219
+ for item in page._get_page_items():
220
+ yield item
221
+
222
+ def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]:
223
+ page = self
224
+ while True:
225
+ yield page
226
+ if page.has_next_page():
227
+ page = page.get_next_page()
228
+ else:
229
+ return
230
+
231
+ def get_next_page(self: SyncPageT) -> SyncPageT:
232
+ info = self.next_page_info()
233
+ if not info:
234
+ raise RuntimeError(
235
+ "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
236
+ )
237
+
238
+ options = self._info_to_options(info)
239
+ return self._client._request_api_list(self._model, page=self.__class__, options=options)
240
+
241
+
242
+ class AsyncPaginator(Generic[_T, AsyncPageT]):
243
+ def __init__(
244
+ self,
245
+ client: AsyncAPIClient,
246
+ options: FinalRequestOptions,
247
+ page_cls: Type[AsyncPageT],
248
+ model: Type[_T],
249
+ ) -> None:
250
+ self._model = model
251
+ self._client = client
252
+ self._options = options
253
+ self._page_cls = page_cls
254
+
255
+ def __await__(self) -> Generator[Any, None, AsyncPageT]:
256
+ return self._get_page().__await__()
257
+
258
+ async def _get_page(self) -> AsyncPageT:
259
+ def _parser(resp: AsyncPageT) -> AsyncPageT:
260
+ resp._set_private_attributes(
261
+ model=self._model,
262
+ options=self._options,
263
+ client=self._client,
264
+ )
265
+ return resp
266
+
267
+ self._options.post_parser = _parser
268
+
269
+ return await self._client.request(self._page_cls, self._options)
270
+
271
+ async def __aiter__(self) -> AsyncIterator[_T]:
272
+ # https://github.com/microsoft/pyright/issues/3464
273
+ page = cast(
274
+ AsyncPageT,
275
+ await self, # type: ignore
276
+ )
277
+ async for item in page:
278
+ yield item
279
+
280
+
281
+ class BaseAsyncPage(BasePage[_T], Generic[_T]):
282
+ _client: AsyncAPIClient = pydantic.PrivateAttr()
283
+
284
+ def _set_private_attributes(
285
+ self,
286
+ model: Type[_T],
287
+ client: AsyncAPIClient,
288
+ options: FinalRequestOptions,
289
+ ) -> None:
290
+ self._model = model
291
+ self._client = client
292
+ self._options = options
293
+
294
+ async def __aiter__(self) -> AsyncIterator[_T]:
295
+ async for page in self.iter_pages():
296
+ for item in page._get_page_items():
297
+ yield item
298
+
299
+ async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]:
300
+ page = self
301
+ while True:
302
+ yield page
303
+ if page.has_next_page():
304
+ page = await page.get_next_page()
305
+ else:
306
+ return
307
+
308
+ async def get_next_page(self: AsyncPageT) -> AsyncPageT:
309
+ info = self.next_page_info()
310
+ if not info:
311
+ raise RuntimeError(
312
+ "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
313
+ )
314
+
315
+ options = self._info_to_options(info)
316
+ return await self._client._request_api_list(self._model, page=self.__class__, options=options)
317
+
318
+
319
+ _HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient])
320
+ _DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]])
321
+
322
+
323
+ class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]):
324
+ _client: _HttpxClientT
325
+ _version: str
326
+ _base_url: URL
327
+ max_retries: int
328
+ timeout: Union[float, Timeout, None]
329
+ _limits: httpx.Limits
330
+ _proxies: ProxiesTypes | None
331
+ _transport: Transport | AsyncTransport | None
332
+ _strict_response_validation: bool
333
+ _idempotency_header: str | None
334
+ _default_stream_cls: type[_DefaultStreamT] | None = None
335
+
336
+ def __init__(
337
+ self,
338
+ *,
339
+ version: str,
340
+ base_url: str | URL,
341
+ _strict_response_validation: bool,
342
+ max_retries: int = DEFAULT_MAX_RETRIES,
343
+ timeout: float | Timeout | None = DEFAULT_TIMEOUT,
344
+ limits: httpx.Limits,
345
+ transport: Transport | AsyncTransport | None,
346
+ proxies: ProxiesTypes | None,
347
+ custom_headers: Mapping[str, str] | None = None,
348
+ custom_query: Mapping[str, object] | None = None,
349
+ ) -> None:
350
+ self._version = version
351
+ self._base_url = self._enforce_trailing_slash(URL(base_url))
352
+ self.max_retries = max_retries
353
+ self.timeout = timeout
354
+ self._limits = limits
355
+ self._proxies = proxies
356
+ self._transport = transport
357
+ self._custom_headers = custom_headers or {}
358
+ self._custom_query = custom_query or {}
359
+ self._strict_response_validation = _strict_response_validation
360
+ self._idempotency_header = None
361
+ self._platform: Platform | None = None
362
+
363
+ if max_retries is None: # pyright: ignore[reportUnnecessaryComparison]
364
+ raise TypeError(
365
+ "max_retries cannot be None. If you want to disable retries, pass `0`; if you want unlimited retries, pass `math.inf` or a very high number; if you want the default behavior, pass `payi.DEFAULT_MAX_RETRIES`"
366
+ )
367
+
368
+ def _enforce_trailing_slash(self, url: URL) -> URL:
369
+ if url.raw_path.endswith(b"/"):
370
+ return url
371
+ return url.copy_with(raw_path=url.raw_path + b"/")
372
+
373
+ def _make_status_error_from_response(
374
+ self,
375
+ response: httpx.Response,
376
+ ) -> APIStatusError:
377
+ if response.is_closed and not response.is_stream_consumed:
378
+ # We can't read the response body as it has been closed
379
+ # before it was read. This can happen if an event hook
380
+ # raises a status error.
381
+ body = None
382
+ err_msg = f"Error code: {response.status_code}"
383
+ else:
384
+ err_text = response.text.strip()
385
+ body = err_text
386
+
387
+ try:
388
+ body = json.loads(err_text)
389
+ err_msg = f"Error code: {response.status_code} - {body}"
390
+ except Exception:
391
+ err_msg = err_text or f"Error code: {response.status_code}"
392
+
393
+ return self._make_status_error(err_msg, body=body, response=response)
394
+
395
+ def _make_status_error(
396
+ self,
397
+ err_msg: str,
398
+ *,
399
+ body: object,
400
+ response: httpx.Response,
401
+ ) -> _exceptions.APIStatusError:
402
+ raise NotImplementedError()
403
+
404
+ def _remaining_retries(
405
+ self,
406
+ remaining_retries: Optional[int],
407
+ options: FinalRequestOptions,
408
+ ) -> int:
409
+ return remaining_retries if remaining_retries is not None else options.get_max_retries(self.max_retries)
410
+
411
+ def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers:
412
+ custom_headers = options.headers or {}
413
+ headers_dict = _merge_mappings(self.default_headers, custom_headers)
414
+ self._validate_headers(headers_dict, custom_headers)
415
+
416
+ # headers are case-insensitive while dictionaries are not.
417
+ headers = httpx.Headers(headers_dict)
418
+
419
+ idempotency_header = self._idempotency_header
420
+ if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers:
421
+ headers[idempotency_header] = options.idempotency_key or self._idempotency_key()
422
+
423
+ return headers
424
+
425
+ def _prepare_url(self, url: str) -> URL:
426
+ """
427
+ Merge a URL argument together with any 'base_url' on the client,
428
+ to create the URL used for the outgoing request.
429
+ """
430
+ # Copied from httpx's `_merge_url` method.
431
+ merge_url = URL(url)
432
+ if merge_url.is_relative_url:
433
+ merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
434
+ return self.base_url.copy_with(raw_path=merge_raw_path)
435
+
436
+ return merge_url
437
+
438
+ def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder:
439
+ return SSEDecoder()
440
+
441
+ def _build_request(
442
+ self,
443
+ options: FinalRequestOptions,
444
+ ) -> httpx.Request:
445
+ if log.isEnabledFor(logging.DEBUG):
446
+ log.debug("Request options: %s", model_dump(options, exclude_unset=True))
447
+
448
+ kwargs: dict[str, Any] = {}
449
+
450
+ json_data = options.json_data
451
+ if options.extra_json is not None:
452
+ if json_data is None:
453
+ json_data = cast(Body, options.extra_json)
454
+ elif is_mapping(json_data):
455
+ json_data = _merge_mappings(json_data, options.extra_json)
456
+ else:
457
+ raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`")
458
+
459
+ headers = self._build_headers(options)
460
+ params = _merge_mappings(self.default_query, options.params)
461
+ content_type = headers.get("Content-Type")
462
+
463
+ # If the given Content-Type header is multipart/form-data then it
464
+ # has to be removed so that httpx can generate the header with
465
+ # additional information for us as it has to be in this form
466
+ # for the server to be able to correctly parse the request:
467
+ # multipart/form-data; boundary=---abc--
468
+ if content_type is not None and content_type.startswith("multipart/form-data"):
469
+ if "boundary" not in content_type:
470
+ # only remove the header if the boundary hasn't been explicitly set
471
+ # as the caller doesn't want httpx to come up with their own boundary
472
+ headers.pop("Content-Type")
473
+
474
+ # As we are now sending multipart/form-data instead of application/json
475
+ # we need to tell httpx to use it, https://www.python-httpx.org/advanced/#multipart-file-encoding
476
+ if json_data:
477
+ if not is_dict(json_data):
478
+ raise TypeError(
479
+ f"Expected query input to be a dictionary for multipart requests but got {type(json_data)} instead."
480
+ )
481
+ kwargs["data"] = self._serialize_multipartform(json_data)
482
+
483
+ # TODO: report this error to httpx
484
+ return self._client.build_request( # pyright: ignore[reportUnknownMemberType]
485
+ headers=headers,
486
+ timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout,
487
+ method=options.method,
488
+ url=self._prepare_url(options.url),
489
+ # the `Query` type that we use is incompatible with qs'
490
+ # `Params` type as it needs to be typed as `Mapping[str, object]`
491
+ # so that passing a `TypedDict` doesn't cause an error.
492
+ # https://github.com/microsoft/pyright/issues/3526#event-6715453066
493
+ params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None,
494
+ json=json_data,
495
+ files=options.files,
496
+ **kwargs,
497
+ )
498
+
499
+ def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]:
500
+ items = self.qs.stringify_items(
501
+ # TODO: type ignore is required as stringify_items is well typed but we can't be
502
+ # well typed without heavy validation.
503
+ data, # type: ignore
504
+ array_format="brackets",
505
+ )
506
+ serialized: dict[str, object] = {}
507
+ for key, value in items:
508
+ existing = serialized.get(key)
509
+
510
+ if not existing:
511
+ serialized[key] = value
512
+ continue
513
+
514
+ # If a value has already been set for this key then that
515
+ # means we're sending data like `array[]=[1, 2, 3]` and we
516
+ # need to tell httpx that we want to send multiple values with
517
+ # the same key which is done by using a list or a tuple.
518
+ #
519
+ # Note: 2d arrays should never result in the same key at both
520
+ # levels so it's safe to assume that if the value is a list,
521
+ # it was because we changed it to be a list.
522
+ if is_list(existing):
523
+ existing.append(value)
524
+ else:
525
+ serialized[key] = [existing, value]
526
+
527
+ return serialized
528
+
529
+ def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]:
530
+ if not is_given(options.headers):
531
+ return cast_to
532
+
533
+ # make a copy of the headers so we don't mutate user-input
534
+ headers = dict(options.headers)
535
+
536
+ # we internally support defining a temporary header to override the
537
+ # default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response`
538
+ # see _response.py for implementation details
539
+ override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, NOT_GIVEN)
540
+ if is_given(override_cast_to):
541
+ options.headers = headers
542
+ return cast(Type[ResponseT], override_cast_to)
543
+
544
+ return cast_to
545
+
546
+ def _should_stream_response_body(self, request: httpx.Request) -> bool:
547
+ return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return]
548
+
549
+ def _process_response_data(
550
+ self,
551
+ *,
552
+ data: object,
553
+ cast_to: type[ResponseT],
554
+ response: httpx.Response,
555
+ ) -> ResponseT:
556
+ if data is None:
557
+ return cast(ResponseT, None)
558
+
559
+ if cast_to is object:
560
+ return cast(ResponseT, data)
561
+
562
+ try:
563
+ if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol):
564
+ return cast(ResponseT, cast_to.build(response=response, data=data))
565
+
566
+ if self._strict_response_validation:
567
+ return cast(ResponseT, validate_type(type_=cast_to, value=data))
568
+
569
+ return cast(ResponseT, construct_type(type_=cast_to, value=data))
570
+ except pydantic.ValidationError as err:
571
+ raise APIResponseValidationError(response=response, body=data) from err
572
+
573
+ @property
574
+ def qs(self) -> Querystring:
575
+ return Querystring()
576
+
577
+ @property
578
+ def custom_auth(self) -> httpx.Auth | None:
579
+ return None
580
+
581
+ @property
582
+ def auth_headers(self) -> dict[str, str]:
583
+ return {}
584
+
585
+ @property
586
+ def default_headers(self) -> dict[str, str | Omit]:
587
+ return {
588
+ "Accept": "application/json",
589
+ "Content-Type": "application/json",
590
+ "User-Agent": self.user_agent,
591
+ **self.platform_headers(),
592
+ **self.auth_headers,
593
+ **self._custom_headers,
594
+ }
595
+
596
+ @property
597
+ def default_query(self) -> dict[str, object]:
598
+ return {
599
+ **self._custom_query,
600
+ }
601
+
602
+ def _validate_headers(
603
+ self,
604
+ headers: Headers, # noqa: ARG002
605
+ custom_headers: Headers, # noqa: ARG002
606
+ ) -> None:
607
+ """Validate the given default headers and custom headers.
608
+
609
+ Does nothing by default.
610
+ """
611
+ return
612
+
613
+ @property
614
+ def user_agent(self) -> str:
615
+ return f"{self.__class__.__name__}/Python {self._version}"
616
+
617
+ @property
618
+ def base_url(self) -> URL:
619
+ return self._base_url
620
+
621
+ @base_url.setter
622
+ def base_url(self, url: URL | str) -> None:
623
+ self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url))
624
+
625
+ def platform_headers(self) -> Dict[str, str]:
626
+ # the actual implementation is in a separate `lru_cache` decorated
627
+ # function because adding `lru_cache` to methods will leak memory
628
+ # https://github.com/python/cpython/issues/88476
629
+ return platform_headers(self._version, platform=self._platform)
630
+
631
+ def _parse_retry_after_header(self, response_headers: Optional[httpx.Headers] = None) -> float | None:
632
+ """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified.
633
+
634
+ About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
635
+ See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax
636
+ """
637
+ if response_headers is None:
638
+ return None
639
+
640
+ # First, try the non-standard `retry-after-ms` header for milliseconds,
641
+ # which is more precise than integer-seconds `retry-after`
642
+ try:
643
+ retry_ms_header = response_headers.get("retry-after-ms", None)
644
+ return float(retry_ms_header) / 1000
645
+ except (TypeError, ValueError):
646
+ pass
647
+
648
+ # Next, try parsing `retry-after` header as seconds (allowing nonstandard floats).
649
+ retry_header = response_headers.get("retry-after")
650
+ try:
651
+ # note: the spec indicates that this should only ever be an integer
652
+ # but if someone sends a float there's no reason for us to not respect it
653
+ return float(retry_header)
654
+ except (TypeError, ValueError):
655
+ pass
656
+
657
+ # Last, try parsing `retry-after` as a date.
658
+ retry_date_tuple = email.utils.parsedate_tz(retry_header)
659
+ if retry_date_tuple is None:
660
+ return None
661
+
662
+ retry_date = email.utils.mktime_tz(retry_date_tuple)
663
+ return float(retry_date - time.time())
664
+
665
+ def _calculate_retry_timeout(
666
+ self,
667
+ remaining_retries: int,
668
+ options: FinalRequestOptions,
669
+ response_headers: Optional[httpx.Headers] = None,
670
+ ) -> float:
671
+ max_retries = options.get_max_retries(self.max_retries)
672
+
673
+ # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says.
674
+ retry_after = self._parse_retry_after_header(response_headers)
675
+ if retry_after is not None and 0 < retry_after <= 60:
676
+ return retry_after
677
+
678
+ nb_retries = max_retries - remaining_retries
679
+
680
+ # Apply exponential backoff, but not more than the max.
681
+ sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY)
682
+
683
+ # Apply some jitter, plus-or-minus half a second.
684
+ jitter = 1 - 0.25 * random()
685
+ timeout = sleep_seconds * jitter
686
+ return timeout if timeout >= 0 else 0
687
+
688
+ def _should_retry(self, response: httpx.Response) -> bool:
689
+ # Note: this is not a standard header
690
+ should_retry_header = response.headers.get("x-should-retry")
691
+
692
+ # If the server explicitly says whether or not to retry, obey.
693
+ if should_retry_header == "true":
694
+ log.debug("Retrying as header `x-should-retry` is set to `true`")
695
+ return True
696
+ if should_retry_header == "false":
697
+ log.debug("Not retrying as header `x-should-retry` is set to `false`")
698
+ return False
699
+
700
+ # Retry on request timeouts.
701
+ if response.status_code == 408:
702
+ log.debug("Retrying due to status code %i", response.status_code)
703
+ return True
704
+
705
+ # Retry on lock timeouts.
706
+ if response.status_code == 409:
707
+ log.debug("Retrying due to status code %i", response.status_code)
708
+ return True
709
+
710
+ # Retry on rate limits.
711
+ if response.status_code == 429:
712
+ log.debug("Retrying due to status code %i", response.status_code)
713
+ return True
714
+
715
+ # Retry internal errors.
716
+ if response.status_code >= 500:
717
+ log.debug("Retrying due to status code %i", response.status_code)
718
+ return True
719
+
720
+ log.debug("Not retrying")
721
+ return False
722
+
723
+ def _idempotency_key(self) -> str:
724
+ return f"stainless-python-retry-{uuid.uuid4()}"
725
+
726
+
727
+ class _DefaultHttpxClient(httpx.Client):
728
+ def __init__(self, **kwargs: Any) -> None:
729
+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
730
+ kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
731
+ kwargs.setdefault("follow_redirects", True)
732
+ super().__init__(**kwargs)
733
+
734
+
735
+ if TYPE_CHECKING:
736
+ DefaultHttpxClient = httpx.Client
737
+ """An alias to `httpx.Client` that provides the same defaults that this SDK
738
+ uses internally.
739
+
740
+ This is useful because overriding the `http_client` with your own instance of
741
+ `httpx.Client` will result in httpx's defaults being used, not ours.
742
+ """
743
+ else:
744
+ DefaultHttpxClient = _DefaultHttpxClient
745
+
746
+
747
+ class SyncHttpxClientWrapper(DefaultHttpxClient):
748
+ def __del__(self) -> None:
749
+ try:
750
+ self.close()
751
+ except Exception:
752
+ pass
753
+
754
+
755
+ class SyncAPIClient(BaseClient[httpx.Client, Stream[Any]]):
756
+ _client: httpx.Client
757
+ _default_stream_cls: type[Stream[Any]] | None = None
758
+
759
+ def __init__(
760
+ self,
761
+ *,
762
+ version: str,
763
+ base_url: str | URL,
764
+ max_retries: int = DEFAULT_MAX_RETRIES,
765
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
766
+ transport: Transport | None = None,
767
+ proxies: ProxiesTypes | None = None,
768
+ limits: Limits | None = None,
769
+ http_client: httpx.Client | None = None,
770
+ custom_headers: Mapping[str, str] | None = None,
771
+ custom_query: Mapping[str, object] | None = None,
772
+ _strict_response_validation: bool,
773
+ ) -> None:
774
+ if limits is not None:
775
+ warnings.warn(
776
+ "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead",
777
+ category=DeprecationWarning,
778
+ stacklevel=3,
779
+ )
780
+ if http_client is not None:
781
+ raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`")
782
+ else:
783
+ limits = DEFAULT_CONNECTION_LIMITS
784
+
785
+ if transport is not None:
786
+ warnings.warn(
787
+ "The `transport` argument is deprecated. The `http_client` argument should be passed instead",
788
+ category=DeprecationWarning,
789
+ stacklevel=3,
790
+ )
791
+ if http_client is not None:
792
+ raise ValueError("The `http_client` argument is mutually exclusive with `transport`")
793
+
794
+ if proxies is not None:
795
+ warnings.warn(
796
+ "The `proxies` argument is deprecated. The `http_client` argument should be passed instead",
797
+ category=DeprecationWarning,
798
+ stacklevel=3,
799
+ )
800
+ if http_client is not None:
801
+ raise ValueError("The `http_client` argument is mutually exclusive with `proxies`")
802
+
803
+ if not is_given(timeout):
804
+ # if the user passed in a custom http client with a non-default
805
+ # timeout set then we use that timeout.
806
+ #
807
+ # note: there is an edge case here where the user passes in a client
808
+ # where they've explicitly set the timeout to match the default timeout
809
+ # as this check is structural, meaning that we'll think they didn't
810
+ # pass in a timeout and will ignore it
811
+ if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT:
812
+ timeout = http_client.timeout
813
+ else:
814
+ timeout = DEFAULT_TIMEOUT
815
+
816
+ if http_client is not None and not isinstance(http_client, httpx.Client): # pyright: ignore[reportUnnecessaryIsInstance]
817
+ raise TypeError(
818
+ f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}"
819
+ )
820
+
821
+ super().__init__(
822
+ version=version,
823
+ limits=limits,
824
+ # cast to a valid type because mypy doesn't understand our type narrowing
825
+ timeout=cast(Timeout, timeout),
826
+ proxies=proxies,
827
+ base_url=base_url,
828
+ transport=transport,
829
+ max_retries=max_retries,
830
+ custom_query=custom_query,
831
+ custom_headers=custom_headers,
832
+ _strict_response_validation=_strict_response_validation,
833
+ )
834
+ self._client = http_client or SyncHttpxClientWrapper(
835
+ base_url=base_url,
836
+ # cast to a valid type because mypy doesn't understand our type narrowing
837
+ timeout=cast(Timeout, timeout),
838
+ proxies=proxies,
839
+ transport=transport,
840
+ limits=limits,
841
+ follow_redirects=True,
842
+ )
843
+
844
+ def is_closed(self) -> bool:
845
+ return self._client.is_closed
846
+
847
+ def close(self) -> None:
848
+ """Close the underlying HTTPX client.
849
+
850
+ The client will *not* be usable after this.
851
+ """
852
+ # If an error is thrown while constructing a client, self._client
853
+ # may not be present
854
+ if hasattr(self, "_client"):
855
+ self._client.close()
856
+
857
+ def __enter__(self: _T) -> _T:
858
+ return self
859
+
860
+ def __exit__(
861
+ self,
862
+ exc_type: type[BaseException] | None,
863
+ exc: BaseException | None,
864
+ exc_tb: TracebackType | None,
865
+ ) -> None:
866
+ self.close()
867
+
868
+ def _prepare_options(
869
+ self,
870
+ options: FinalRequestOptions, # noqa: ARG002
871
+ ) -> None:
872
+ """Hook for mutating the given options"""
873
+ return None
874
+
875
+ def _prepare_request(
876
+ self,
877
+ request: httpx.Request, # noqa: ARG002
878
+ ) -> None:
879
+ """This method is used as a callback for mutating the `Request` object
880
+ after it has been constructed.
881
+ This is useful for cases where you want to add certain headers based off of
882
+ the request properties, e.g. `url`, `method` etc.
883
+ """
884
+ return None
885
+
886
+ @overload
887
+ def request(
888
+ self,
889
+ cast_to: Type[ResponseT],
890
+ options: FinalRequestOptions,
891
+ remaining_retries: Optional[int] = None,
892
+ *,
893
+ stream: Literal[True],
894
+ stream_cls: Type[_StreamT],
895
+ ) -> _StreamT:
896
+ ...
897
+
898
+ @overload
899
+ def request(
900
+ self,
901
+ cast_to: Type[ResponseT],
902
+ options: FinalRequestOptions,
903
+ remaining_retries: Optional[int] = None,
904
+ *,
905
+ stream: Literal[False] = False,
906
+ ) -> ResponseT:
907
+ ...
908
+
909
+ @overload
910
+ def request(
911
+ self,
912
+ cast_to: Type[ResponseT],
913
+ options: FinalRequestOptions,
914
+ remaining_retries: Optional[int] = None,
915
+ *,
916
+ stream: bool = False,
917
+ stream_cls: Type[_StreamT] | None = None,
918
+ ) -> ResponseT | _StreamT:
919
+ ...
920
+
921
+ def request(
922
+ self,
923
+ cast_to: Type[ResponseT],
924
+ options: FinalRequestOptions,
925
+ remaining_retries: Optional[int] = None,
926
+ *,
927
+ stream: bool = False,
928
+ stream_cls: type[_StreamT] | None = None,
929
+ ) -> ResponseT | _StreamT:
930
+ return self._request(
931
+ cast_to=cast_to,
932
+ options=options,
933
+ stream=stream,
934
+ stream_cls=stream_cls,
935
+ remaining_retries=remaining_retries,
936
+ )
937
+
938
+ def _request(
939
+ self,
940
+ *,
941
+ cast_to: Type[ResponseT],
942
+ options: FinalRequestOptions,
943
+ remaining_retries: int | None,
944
+ stream: bool,
945
+ stream_cls: type[_StreamT] | None,
946
+ ) -> ResponseT | _StreamT:
947
+ cast_to = self._maybe_override_cast_to(cast_to, options)
948
+ self._prepare_options(options)
949
+
950
+ retries = self._remaining_retries(remaining_retries, options)
951
+ request = self._build_request(options)
952
+ self._prepare_request(request)
953
+
954
+ kwargs: HttpxSendArgs = {}
955
+ if self.custom_auth is not None:
956
+ kwargs["auth"] = self.custom_auth
957
+
958
+ log.debug("Sending HTTP Request: %s %s", request.method, request.url)
959
+
960
+ try:
961
+ response = self._client.send(
962
+ request,
963
+ stream=stream or self._should_stream_response_body(request=request),
964
+ **kwargs,
965
+ )
966
+ except httpx.TimeoutException as err:
967
+ log.debug("Encountered httpx.TimeoutException", exc_info=True)
968
+
969
+ if retries > 0:
970
+ return self._retry_request(
971
+ options,
972
+ cast_to,
973
+ retries,
974
+ stream=stream,
975
+ stream_cls=stream_cls,
976
+ response_headers=None,
977
+ )
978
+
979
+ log.debug("Raising timeout error")
980
+ raise APITimeoutError(request=request) from err
981
+ except Exception as err:
982
+ log.debug("Encountered Exception", exc_info=True)
983
+
984
+ if retries > 0:
985
+ return self._retry_request(
986
+ options,
987
+ cast_to,
988
+ retries,
989
+ stream=stream,
990
+ stream_cls=stream_cls,
991
+ response_headers=None,
992
+ )
993
+
994
+ log.debug("Raising connection error")
995
+ raise APIConnectionError(request=request) from err
996
+
997
+ log.debug(
998
+ 'HTTP Response: %s %s "%i %s" %s',
999
+ request.method,
1000
+ request.url,
1001
+ response.status_code,
1002
+ response.reason_phrase,
1003
+ response.headers,
1004
+ )
1005
+
1006
+ try:
1007
+ response.raise_for_status()
1008
+ except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code
1009
+ log.debug("Encountered httpx.HTTPStatusError", exc_info=True)
1010
+
1011
+ if retries > 0 and self._should_retry(err.response):
1012
+ err.response.close()
1013
+ return self._retry_request(
1014
+ options,
1015
+ cast_to,
1016
+ retries,
1017
+ err.response.headers,
1018
+ stream=stream,
1019
+ stream_cls=stream_cls,
1020
+ )
1021
+
1022
+ # If the response is streamed then we need to explicitly read the response
1023
+ # to completion before attempting to access the response text.
1024
+ if not err.response.is_closed:
1025
+ err.response.read()
1026
+
1027
+ log.debug("Re-raising status error")
1028
+ raise self._make_status_error_from_response(err.response) from None
1029
+
1030
+ return self._process_response(
1031
+ cast_to=cast_to,
1032
+ options=options,
1033
+ response=response,
1034
+ stream=stream,
1035
+ stream_cls=stream_cls,
1036
+ )
1037
+
1038
+ def _retry_request(
1039
+ self,
1040
+ options: FinalRequestOptions,
1041
+ cast_to: Type[ResponseT],
1042
+ remaining_retries: int,
1043
+ response_headers: httpx.Headers | None,
1044
+ *,
1045
+ stream: bool,
1046
+ stream_cls: type[_StreamT] | None,
1047
+ ) -> ResponseT | _StreamT:
1048
+ remaining = remaining_retries - 1
1049
+ if remaining == 1:
1050
+ log.debug("1 retry left")
1051
+ else:
1052
+ log.debug("%i retries left", remaining)
1053
+
1054
+ timeout = self._calculate_retry_timeout(remaining, options, response_headers)
1055
+ log.info("Retrying request to %s in %f seconds", options.url, timeout)
1056
+
1057
+ # In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a
1058
+ # different thread if necessary.
1059
+ time.sleep(timeout)
1060
+
1061
+ return self._request(
1062
+ options=options,
1063
+ cast_to=cast_to,
1064
+ remaining_retries=remaining,
1065
+ stream=stream,
1066
+ stream_cls=stream_cls,
1067
+ )
1068
+
1069
+ def _process_response(
1070
+ self,
1071
+ *,
1072
+ cast_to: Type[ResponseT],
1073
+ options: FinalRequestOptions,
1074
+ response: httpx.Response,
1075
+ stream: bool,
1076
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
1077
+ ) -> ResponseT:
1078
+ origin = get_origin(cast_to) or cast_to
1079
+
1080
+ if inspect.isclass(origin) and issubclass(origin, BaseAPIResponse):
1081
+ if not issubclass(origin, APIResponse):
1082
+ raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}")
1083
+
1084
+ response_cls = cast("type[BaseAPIResponse[Any]]", cast_to)
1085
+ return cast(
1086
+ ResponseT,
1087
+ response_cls(
1088
+ raw=response,
1089
+ client=self,
1090
+ cast_to=extract_response_type(response_cls),
1091
+ stream=stream,
1092
+ stream_cls=stream_cls,
1093
+ options=options,
1094
+ ),
1095
+ )
1096
+
1097
+ if cast_to == httpx.Response:
1098
+ return cast(ResponseT, response)
1099
+
1100
+ api_response = APIResponse(
1101
+ raw=response,
1102
+ client=self,
1103
+ cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
1104
+ stream=stream,
1105
+ stream_cls=stream_cls,
1106
+ options=options,
1107
+ )
1108
+ if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
1109
+ return cast(ResponseT, api_response)
1110
+
1111
+ return api_response.parse()
1112
+
1113
+ def _request_api_list(
1114
+ self,
1115
+ model: Type[object],
1116
+ page: Type[SyncPageT],
1117
+ options: FinalRequestOptions,
1118
+ ) -> SyncPageT:
1119
+ def _parser(resp: SyncPageT) -> SyncPageT:
1120
+ resp._set_private_attributes(
1121
+ client=self,
1122
+ model=model,
1123
+ options=options,
1124
+ )
1125
+ return resp
1126
+
1127
+ options.post_parser = _parser
1128
+
1129
+ return self.request(page, options, stream=False)
1130
+
1131
+ @overload
1132
+ def get(
1133
+ self,
1134
+ path: str,
1135
+ *,
1136
+ cast_to: Type[ResponseT],
1137
+ options: RequestOptions = {},
1138
+ stream: Literal[False] = False,
1139
+ ) -> ResponseT:
1140
+ ...
1141
+
1142
+ @overload
1143
+ def get(
1144
+ self,
1145
+ path: str,
1146
+ *,
1147
+ cast_to: Type[ResponseT],
1148
+ options: RequestOptions = {},
1149
+ stream: Literal[True],
1150
+ stream_cls: type[_StreamT],
1151
+ ) -> _StreamT:
1152
+ ...
1153
+
1154
+ @overload
1155
+ def get(
1156
+ self,
1157
+ path: str,
1158
+ *,
1159
+ cast_to: Type[ResponseT],
1160
+ options: RequestOptions = {},
1161
+ stream: bool,
1162
+ stream_cls: type[_StreamT] | None = None,
1163
+ ) -> ResponseT | _StreamT:
1164
+ ...
1165
+
1166
+ def get(
1167
+ self,
1168
+ path: str,
1169
+ *,
1170
+ cast_to: Type[ResponseT],
1171
+ options: RequestOptions = {},
1172
+ stream: bool = False,
1173
+ stream_cls: type[_StreamT] | None = None,
1174
+ ) -> ResponseT | _StreamT:
1175
+ opts = FinalRequestOptions.construct(method="get", url=path, **options)
1176
+ # cast is required because mypy complains about returning Any even though
1177
+ # it understands the type variables
1178
+ return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
1179
+
1180
+ @overload
1181
+ def post(
1182
+ self,
1183
+ path: str,
1184
+ *,
1185
+ cast_to: Type[ResponseT],
1186
+ body: Body | None = None,
1187
+ options: RequestOptions = {},
1188
+ files: RequestFiles | None = None,
1189
+ stream: Literal[False] = False,
1190
+ ) -> ResponseT:
1191
+ ...
1192
+
1193
+ @overload
1194
+ def post(
1195
+ self,
1196
+ path: str,
1197
+ *,
1198
+ cast_to: Type[ResponseT],
1199
+ body: Body | None = None,
1200
+ options: RequestOptions = {},
1201
+ files: RequestFiles | None = None,
1202
+ stream: Literal[True],
1203
+ stream_cls: type[_StreamT],
1204
+ ) -> _StreamT:
1205
+ ...
1206
+
1207
+ @overload
1208
+ def post(
1209
+ self,
1210
+ path: str,
1211
+ *,
1212
+ cast_to: Type[ResponseT],
1213
+ body: Body | None = None,
1214
+ options: RequestOptions = {},
1215
+ files: RequestFiles | None = None,
1216
+ stream: bool,
1217
+ stream_cls: type[_StreamT] | None = None,
1218
+ ) -> ResponseT | _StreamT:
1219
+ ...
1220
+
1221
+ def post(
1222
+ self,
1223
+ path: str,
1224
+ *,
1225
+ cast_to: Type[ResponseT],
1226
+ body: Body | None = None,
1227
+ options: RequestOptions = {},
1228
+ files: RequestFiles | None = None,
1229
+ stream: bool = False,
1230
+ stream_cls: type[_StreamT] | None = None,
1231
+ ) -> ResponseT | _StreamT:
1232
+ opts = FinalRequestOptions.construct(
1233
+ method="post", url=path, json_data=body, files=to_httpx_files(files), **options
1234
+ )
1235
+ return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
1236
+
1237
+ def patch(
1238
+ self,
1239
+ path: str,
1240
+ *,
1241
+ cast_to: Type[ResponseT],
1242
+ body: Body | None = None,
1243
+ options: RequestOptions = {},
1244
+ ) -> ResponseT:
1245
+ opts = FinalRequestOptions.construct(method="patch", url=path, json_data=body, **options)
1246
+ return self.request(cast_to, opts)
1247
+
1248
+ def put(
1249
+ self,
1250
+ path: str,
1251
+ *,
1252
+ cast_to: Type[ResponseT],
1253
+ body: Body | None = None,
1254
+ files: RequestFiles | None = None,
1255
+ options: RequestOptions = {},
1256
+ ) -> ResponseT:
1257
+ opts = FinalRequestOptions.construct(
1258
+ method="put", url=path, json_data=body, files=to_httpx_files(files), **options
1259
+ )
1260
+ return self.request(cast_to, opts)
1261
+
1262
+ def delete(
1263
+ self,
1264
+ path: str,
1265
+ *,
1266
+ cast_to: Type[ResponseT],
1267
+ body: Body | None = None,
1268
+ options: RequestOptions = {},
1269
+ ) -> ResponseT:
1270
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options)
1271
+ return self.request(cast_to, opts)
1272
+
1273
+ def get_api_list(
1274
+ self,
1275
+ path: str,
1276
+ *,
1277
+ model: Type[object],
1278
+ page: Type[SyncPageT],
1279
+ body: Body | None = None,
1280
+ options: RequestOptions = {},
1281
+ method: str = "get",
1282
+ ) -> SyncPageT:
1283
+ opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options)
1284
+ return self._request_api_list(model, page, opts)
1285
+
1286
+
1287
+ class _DefaultAsyncHttpxClient(httpx.AsyncClient):
1288
+ def __init__(self, **kwargs: Any) -> None:
1289
+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
1290
+ kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
1291
+ kwargs.setdefault("follow_redirects", True)
1292
+ super().__init__(**kwargs)
1293
+
1294
+
1295
+ if TYPE_CHECKING:
1296
+ DefaultAsyncHttpxClient = httpx.AsyncClient
1297
+ """An alias to `httpx.AsyncClient` that provides the same defaults that this SDK
1298
+ uses internally.
1299
+
1300
+ This is useful because overriding the `http_client` with your own instance of
1301
+ `httpx.AsyncClient` will result in httpx's defaults being used, not ours.
1302
+ """
1303
+ else:
1304
+ DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient
1305
+
1306
+
1307
+ class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient):
1308
+ def __del__(self) -> None:
1309
+ try:
1310
+ # TODO(someday): support non asyncio runtimes here
1311
+ asyncio.get_running_loop().create_task(self.aclose())
1312
+ except Exception:
1313
+ pass
1314
+
1315
+
1316
+ class AsyncAPIClient(BaseClient[httpx.AsyncClient, AsyncStream[Any]]):
1317
+ _client: httpx.AsyncClient
1318
+ _default_stream_cls: type[AsyncStream[Any]] | None = None
1319
+
1320
+ def __init__(
1321
+ self,
1322
+ *,
1323
+ version: str,
1324
+ base_url: str | URL,
1325
+ _strict_response_validation: bool,
1326
+ max_retries: int = DEFAULT_MAX_RETRIES,
1327
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
1328
+ transport: AsyncTransport | None = None,
1329
+ proxies: ProxiesTypes | None = None,
1330
+ limits: Limits | None = None,
1331
+ http_client: httpx.AsyncClient | None = None,
1332
+ custom_headers: Mapping[str, str] | None = None,
1333
+ custom_query: Mapping[str, object] | None = None,
1334
+ ) -> None:
1335
+ if limits is not None:
1336
+ warnings.warn(
1337
+ "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead",
1338
+ category=DeprecationWarning,
1339
+ stacklevel=3,
1340
+ )
1341
+ if http_client is not None:
1342
+ raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`")
1343
+ else:
1344
+ limits = DEFAULT_CONNECTION_LIMITS
1345
+
1346
+ if transport is not None:
1347
+ warnings.warn(
1348
+ "The `transport` argument is deprecated. The `http_client` argument should be passed instead",
1349
+ category=DeprecationWarning,
1350
+ stacklevel=3,
1351
+ )
1352
+ if http_client is not None:
1353
+ raise ValueError("The `http_client` argument is mutually exclusive with `transport`")
1354
+
1355
+ if proxies is not None:
1356
+ warnings.warn(
1357
+ "The `proxies` argument is deprecated. The `http_client` argument should be passed instead",
1358
+ category=DeprecationWarning,
1359
+ stacklevel=3,
1360
+ )
1361
+ if http_client is not None:
1362
+ raise ValueError("The `http_client` argument is mutually exclusive with `proxies`")
1363
+
1364
+ if not is_given(timeout):
1365
+ # if the user passed in a custom http client with a non-default
1366
+ # timeout set then we use that timeout.
1367
+ #
1368
+ # note: there is an edge case here where the user passes in a client
1369
+ # where they've explicitly set the timeout to match the default timeout
1370
+ # as this check is structural, meaning that we'll think they didn't
1371
+ # pass in a timeout and will ignore it
1372
+ if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT:
1373
+ timeout = http_client.timeout
1374
+ else:
1375
+ timeout = DEFAULT_TIMEOUT
1376
+
1377
+ if http_client is not None and not isinstance(http_client, httpx.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance]
1378
+ raise TypeError(
1379
+ f"Invalid `http_client` argument; Expected an instance of `httpx.AsyncClient` but got {type(http_client)}"
1380
+ )
1381
+
1382
+ super().__init__(
1383
+ version=version,
1384
+ base_url=base_url,
1385
+ limits=limits,
1386
+ # cast to a valid type because mypy doesn't understand our type narrowing
1387
+ timeout=cast(Timeout, timeout),
1388
+ proxies=proxies,
1389
+ transport=transport,
1390
+ max_retries=max_retries,
1391
+ custom_query=custom_query,
1392
+ custom_headers=custom_headers,
1393
+ _strict_response_validation=_strict_response_validation,
1394
+ )
1395
+ self._client = http_client or AsyncHttpxClientWrapper(
1396
+ base_url=base_url,
1397
+ # cast to a valid type because mypy doesn't understand our type narrowing
1398
+ timeout=cast(Timeout, timeout),
1399
+ proxies=proxies,
1400
+ transport=transport,
1401
+ limits=limits,
1402
+ follow_redirects=True,
1403
+ )
1404
+
1405
+ def is_closed(self) -> bool:
1406
+ return self._client.is_closed
1407
+
1408
+ async def close(self) -> None:
1409
+ """Close the underlying HTTPX client.
1410
+
1411
+ The client will *not* be usable after this.
1412
+ """
1413
+ await self._client.aclose()
1414
+
1415
+ async def __aenter__(self: _T) -> _T:
1416
+ return self
1417
+
1418
+ async def __aexit__(
1419
+ self,
1420
+ exc_type: type[BaseException] | None,
1421
+ exc: BaseException | None,
1422
+ exc_tb: TracebackType | None,
1423
+ ) -> None:
1424
+ await self.close()
1425
+
1426
+ async def _prepare_options(
1427
+ self,
1428
+ options: FinalRequestOptions, # noqa: ARG002
1429
+ ) -> None:
1430
+ """Hook for mutating the given options"""
1431
+ return None
1432
+
1433
+ async def _prepare_request(
1434
+ self,
1435
+ request: httpx.Request, # noqa: ARG002
1436
+ ) -> None:
1437
+ """This method is used as a callback for mutating the `Request` object
1438
+ after it has been constructed.
1439
+ This is useful for cases where you want to add certain headers based off of
1440
+ the request properties, e.g. `url`, `method` etc.
1441
+ """
1442
+ return None
1443
+
1444
+ @overload
1445
+ async def request(
1446
+ self,
1447
+ cast_to: Type[ResponseT],
1448
+ options: FinalRequestOptions,
1449
+ *,
1450
+ stream: Literal[False] = False,
1451
+ remaining_retries: Optional[int] = None,
1452
+ ) -> ResponseT:
1453
+ ...
1454
+
1455
+ @overload
1456
+ async def request(
1457
+ self,
1458
+ cast_to: Type[ResponseT],
1459
+ options: FinalRequestOptions,
1460
+ *,
1461
+ stream: Literal[True],
1462
+ stream_cls: type[_AsyncStreamT],
1463
+ remaining_retries: Optional[int] = None,
1464
+ ) -> _AsyncStreamT:
1465
+ ...
1466
+
1467
+ @overload
1468
+ async def request(
1469
+ self,
1470
+ cast_to: Type[ResponseT],
1471
+ options: FinalRequestOptions,
1472
+ *,
1473
+ stream: bool,
1474
+ stream_cls: type[_AsyncStreamT] | None = None,
1475
+ remaining_retries: Optional[int] = None,
1476
+ ) -> ResponseT | _AsyncStreamT:
1477
+ ...
1478
+
1479
+ async def request(
1480
+ self,
1481
+ cast_to: Type[ResponseT],
1482
+ options: FinalRequestOptions,
1483
+ *,
1484
+ stream: bool = False,
1485
+ stream_cls: type[_AsyncStreamT] | None = None,
1486
+ remaining_retries: Optional[int] = None,
1487
+ ) -> ResponseT | _AsyncStreamT:
1488
+ return await self._request(
1489
+ cast_to=cast_to,
1490
+ options=options,
1491
+ stream=stream,
1492
+ stream_cls=stream_cls,
1493
+ remaining_retries=remaining_retries,
1494
+ )
1495
+
1496
+ async def _request(
1497
+ self,
1498
+ cast_to: Type[ResponseT],
1499
+ options: FinalRequestOptions,
1500
+ *,
1501
+ stream: bool,
1502
+ stream_cls: type[_AsyncStreamT] | None,
1503
+ remaining_retries: int | None,
1504
+ ) -> ResponseT | _AsyncStreamT:
1505
+ if self._platform is None:
1506
+ # `get_platform` can make blocking IO calls so we
1507
+ # execute it earlier while we are in an async context
1508
+ self._platform = await asyncify(get_platform)()
1509
+
1510
+ cast_to = self._maybe_override_cast_to(cast_to, options)
1511
+ await self._prepare_options(options)
1512
+
1513
+ retries = self._remaining_retries(remaining_retries, options)
1514
+ request = self._build_request(options)
1515
+ await self._prepare_request(request)
1516
+
1517
+ kwargs: HttpxSendArgs = {}
1518
+ if self.custom_auth is not None:
1519
+ kwargs["auth"] = self.custom_auth
1520
+
1521
+ try:
1522
+ response = await self._client.send(
1523
+ request,
1524
+ stream=stream or self._should_stream_response_body(request=request),
1525
+ **kwargs,
1526
+ )
1527
+ except httpx.TimeoutException as err:
1528
+ log.debug("Encountered httpx.TimeoutException", exc_info=True)
1529
+
1530
+ if retries > 0:
1531
+ return await self._retry_request(
1532
+ options,
1533
+ cast_to,
1534
+ retries,
1535
+ stream=stream,
1536
+ stream_cls=stream_cls,
1537
+ response_headers=None,
1538
+ )
1539
+
1540
+ log.debug("Raising timeout error")
1541
+ raise APITimeoutError(request=request) from err
1542
+ except Exception as err:
1543
+ log.debug("Encountered Exception", exc_info=True)
1544
+
1545
+ if retries > 0:
1546
+ return await self._retry_request(
1547
+ options,
1548
+ cast_to,
1549
+ retries,
1550
+ stream=stream,
1551
+ stream_cls=stream_cls,
1552
+ response_headers=None,
1553
+ )
1554
+
1555
+ log.debug("Raising connection error")
1556
+ raise APIConnectionError(request=request) from err
1557
+
1558
+ log.debug(
1559
+ 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase
1560
+ )
1561
+
1562
+ try:
1563
+ response.raise_for_status()
1564
+ except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code
1565
+ log.debug("Encountered httpx.HTTPStatusError", exc_info=True)
1566
+
1567
+ if retries > 0 and self._should_retry(err.response):
1568
+ await err.response.aclose()
1569
+ return await self._retry_request(
1570
+ options,
1571
+ cast_to,
1572
+ retries,
1573
+ err.response.headers,
1574
+ stream=stream,
1575
+ stream_cls=stream_cls,
1576
+ )
1577
+
1578
+ # If the response is streamed then we need to explicitly read the response
1579
+ # to completion before attempting to access the response text.
1580
+ if not err.response.is_closed:
1581
+ await err.response.aread()
1582
+
1583
+ log.debug("Re-raising status error")
1584
+ raise self._make_status_error_from_response(err.response) from None
1585
+
1586
+ return await self._process_response(
1587
+ cast_to=cast_to,
1588
+ options=options,
1589
+ response=response,
1590
+ stream=stream,
1591
+ stream_cls=stream_cls,
1592
+ )
1593
+
1594
+ async def _retry_request(
1595
+ self,
1596
+ options: FinalRequestOptions,
1597
+ cast_to: Type[ResponseT],
1598
+ remaining_retries: int,
1599
+ response_headers: httpx.Headers | None,
1600
+ *,
1601
+ stream: bool,
1602
+ stream_cls: type[_AsyncStreamT] | None,
1603
+ ) -> ResponseT | _AsyncStreamT:
1604
+ remaining = remaining_retries - 1
1605
+ if remaining == 1:
1606
+ log.debug("1 retry left")
1607
+ else:
1608
+ log.debug("%i retries left", remaining)
1609
+
1610
+ timeout = self._calculate_retry_timeout(remaining, options, response_headers)
1611
+ log.info("Retrying request to %s in %f seconds", options.url, timeout)
1612
+
1613
+ await anyio.sleep(timeout)
1614
+
1615
+ return await self._request(
1616
+ options=options,
1617
+ cast_to=cast_to,
1618
+ remaining_retries=remaining,
1619
+ stream=stream,
1620
+ stream_cls=stream_cls,
1621
+ )
1622
+
1623
+ async def _process_response(
1624
+ self,
1625
+ *,
1626
+ cast_to: Type[ResponseT],
1627
+ options: FinalRequestOptions,
1628
+ response: httpx.Response,
1629
+ stream: bool,
1630
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
1631
+ ) -> ResponseT:
1632
+ origin = get_origin(cast_to) or cast_to
1633
+
1634
+ if inspect.isclass(origin) and issubclass(origin, BaseAPIResponse):
1635
+ if not issubclass(origin, AsyncAPIResponse):
1636
+ raise TypeError(f"API Response types must subclass {AsyncAPIResponse}; Received {origin}")
1637
+
1638
+ response_cls = cast("type[BaseAPIResponse[Any]]", cast_to)
1639
+ return cast(
1640
+ "ResponseT",
1641
+ response_cls(
1642
+ raw=response,
1643
+ client=self,
1644
+ cast_to=extract_response_type(response_cls),
1645
+ stream=stream,
1646
+ stream_cls=stream_cls,
1647
+ options=options,
1648
+ ),
1649
+ )
1650
+
1651
+ if cast_to == httpx.Response:
1652
+ return cast(ResponseT, response)
1653
+
1654
+ api_response = AsyncAPIResponse(
1655
+ raw=response,
1656
+ client=self,
1657
+ cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
1658
+ stream=stream,
1659
+ stream_cls=stream_cls,
1660
+ options=options,
1661
+ )
1662
+ if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
1663
+ return cast(ResponseT, api_response)
1664
+
1665
+ return await api_response.parse()
1666
+
1667
+ def _request_api_list(
1668
+ self,
1669
+ model: Type[_T],
1670
+ page: Type[AsyncPageT],
1671
+ options: FinalRequestOptions,
1672
+ ) -> AsyncPaginator[_T, AsyncPageT]:
1673
+ return AsyncPaginator(client=self, options=options, page_cls=page, model=model)
1674
+
1675
+ @overload
1676
+ async def get(
1677
+ self,
1678
+ path: str,
1679
+ *,
1680
+ cast_to: Type[ResponseT],
1681
+ options: RequestOptions = {},
1682
+ stream: Literal[False] = False,
1683
+ ) -> ResponseT:
1684
+ ...
1685
+
1686
+ @overload
1687
+ async def get(
1688
+ self,
1689
+ path: str,
1690
+ *,
1691
+ cast_to: Type[ResponseT],
1692
+ options: RequestOptions = {},
1693
+ stream: Literal[True],
1694
+ stream_cls: type[_AsyncStreamT],
1695
+ ) -> _AsyncStreamT:
1696
+ ...
1697
+
1698
+ @overload
1699
+ async def get(
1700
+ self,
1701
+ path: str,
1702
+ *,
1703
+ cast_to: Type[ResponseT],
1704
+ options: RequestOptions = {},
1705
+ stream: bool,
1706
+ stream_cls: type[_AsyncStreamT] | None = None,
1707
+ ) -> ResponseT | _AsyncStreamT:
1708
+ ...
1709
+
1710
+ async def get(
1711
+ self,
1712
+ path: str,
1713
+ *,
1714
+ cast_to: Type[ResponseT],
1715
+ options: RequestOptions = {},
1716
+ stream: bool = False,
1717
+ stream_cls: type[_AsyncStreamT] | None = None,
1718
+ ) -> ResponseT | _AsyncStreamT:
1719
+ opts = FinalRequestOptions.construct(method="get", url=path, **options)
1720
+ return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
1721
+
1722
+ @overload
1723
+ async def post(
1724
+ self,
1725
+ path: str,
1726
+ *,
1727
+ cast_to: Type[ResponseT],
1728
+ body: Body | None = None,
1729
+ files: RequestFiles | None = None,
1730
+ options: RequestOptions = {},
1731
+ stream: Literal[False] = False,
1732
+ ) -> ResponseT:
1733
+ ...
1734
+
1735
+ @overload
1736
+ async def post(
1737
+ self,
1738
+ path: str,
1739
+ *,
1740
+ cast_to: Type[ResponseT],
1741
+ body: Body | None = None,
1742
+ files: RequestFiles | None = None,
1743
+ options: RequestOptions = {},
1744
+ stream: Literal[True],
1745
+ stream_cls: type[_AsyncStreamT],
1746
+ ) -> _AsyncStreamT:
1747
+ ...
1748
+
1749
+ @overload
1750
+ async def post(
1751
+ self,
1752
+ path: str,
1753
+ *,
1754
+ cast_to: Type[ResponseT],
1755
+ body: Body | None = None,
1756
+ files: RequestFiles | None = None,
1757
+ options: RequestOptions = {},
1758
+ stream: bool,
1759
+ stream_cls: type[_AsyncStreamT] | None = None,
1760
+ ) -> ResponseT | _AsyncStreamT:
1761
+ ...
1762
+
1763
+ async def post(
1764
+ self,
1765
+ path: str,
1766
+ *,
1767
+ cast_to: Type[ResponseT],
1768
+ body: Body | None = None,
1769
+ files: RequestFiles | None = None,
1770
+ options: RequestOptions = {},
1771
+ stream: bool = False,
1772
+ stream_cls: type[_AsyncStreamT] | None = None,
1773
+ ) -> ResponseT | _AsyncStreamT:
1774
+ opts = FinalRequestOptions.construct(
1775
+ method="post", url=path, json_data=body, files=await async_to_httpx_files(files), **options
1776
+ )
1777
+ return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
1778
+
1779
+ async def patch(
1780
+ self,
1781
+ path: str,
1782
+ *,
1783
+ cast_to: Type[ResponseT],
1784
+ body: Body | None = None,
1785
+ options: RequestOptions = {},
1786
+ ) -> ResponseT:
1787
+ opts = FinalRequestOptions.construct(method="patch", url=path, json_data=body, **options)
1788
+ return await self.request(cast_to, opts)
1789
+
1790
+ async def put(
1791
+ self,
1792
+ path: str,
1793
+ *,
1794
+ cast_to: Type[ResponseT],
1795
+ body: Body | None = None,
1796
+ files: RequestFiles | None = None,
1797
+ options: RequestOptions = {},
1798
+ ) -> ResponseT:
1799
+ opts = FinalRequestOptions.construct(
1800
+ method="put", url=path, json_data=body, files=await async_to_httpx_files(files), **options
1801
+ )
1802
+ return await self.request(cast_to, opts)
1803
+
1804
+ async def delete(
1805
+ self,
1806
+ path: str,
1807
+ *,
1808
+ cast_to: Type[ResponseT],
1809
+ body: Body | None = None,
1810
+ options: RequestOptions = {},
1811
+ ) -> ResponseT:
1812
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options)
1813
+ return await self.request(cast_to, opts)
1814
+
1815
+ def get_api_list(
1816
+ self,
1817
+ path: str,
1818
+ *,
1819
+ model: Type[_T],
1820
+ page: Type[AsyncPageT],
1821
+ body: Body | None = None,
1822
+ options: RequestOptions = {},
1823
+ method: str = "get",
1824
+ ) -> AsyncPaginator[_T, AsyncPageT]:
1825
+ opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options)
1826
+ return self._request_api_list(model, page, opts)
1827
+
1828
+
1829
+ def make_request_options(
1830
+ *,
1831
+ query: Query | None = None,
1832
+ extra_headers: Headers | None = None,
1833
+ extra_query: Query | None = None,
1834
+ extra_body: Body | None = None,
1835
+ idempotency_key: str | None = None,
1836
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
1837
+ post_parser: PostParser | NotGiven = NOT_GIVEN,
1838
+ ) -> RequestOptions:
1839
+ """Create a dict of type RequestOptions without keys of NotGiven values."""
1840
+ options: RequestOptions = {}
1841
+ if extra_headers is not None:
1842
+ options["headers"] = extra_headers
1843
+
1844
+ if extra_body is not None:
1845
+ options["extra_json"] = cast(AnyMapping, extra_body)
1846
+
1847
+ if query is not None:
1848
+ options["params"] = query
1849
+
1850
+ if extra_query is not None:
1851
+ options["params"] = {**options.get("params", {}), **extra_query}
1852
+
1853
+ if not isinstance(timeout, NotGiven):
1854
+ options["timeout"] = timeout
1855
+
1856
+ if idempotency_key is not None:
1857
+ options["idempotency_key"] = idempotency_key
1858
+
1859
+ if is_given(post_parser):
1860
+ # internal
1861
+ options["post_parser"] = post_parser # type: ignore
1862
+
1863
+ return options
1864
+
1865
+
1866
+ class OtherPlatform:
1867
+ def __init__(self, name: str) -> None:
1868
+ self.name = name
1869
+
1870
+ @override
1871
+ def __str__(self) -> str:
1872
+ return f"Other:{self.name}"
1873
+
1874
+
1875
+ Platform = Union[
1876
+ OtherPlatform,
1877
+ Literal[
1878
+ "MacOS",
1879
+ "Linux",
1880
+ "Windows",
1881
+ "FreeBSD",
1882
+ "OpenBSD",
1883
+ "iOS",
1884
+ "Android",
1885
+ "Unknown",
1886
+ ],
1887
+ ]
1888
+
1889
+
1890
+ def get_platform() -> Platform:
1891
+ try:
1892
+ system = platform.system().lower()
1893
+ platform_name = platform.platform().lower()
1894
+ except Exception:
1895
+ return "Unknown"
1896
+
1897
+ if "iphone" in platform_name or "ipad" in platform_name:
1898
+ # Tested using Python3IDE on an iPhone 11 and Pythonista on an iPad 7
1899
+ # system is Darwin and platform_name is a string like:
1900
+ # - Darwin-21.6.0-iPhone12,1-64bit
1901
+ # - Darwin-21.6.0-iPad7,11-64bit
1902
+ return "iOS"
1903
+
1904
+ if system == "darwin":
1905
+ return "MacOS"
1906
+
1907
+ if system == "windows":
1908
+ return "Windows"
1909
+
1910
+ if "android" in platform_name:
1911
+ # Tested using Pydroid 3
1912
+ # system is Linux and platform_name is a string like 'Linux-5.10.81-android12-9-00001-geba40aecb3b7-ab8534902-aarch64-with-libc'
1913
+ return "Android"
1914
+
1915
+ if system == "linux":
1916
+ # https://distro.readthedocs.io/en/latest/#distro.id
1917
+ distro_id = distro.id()
1918
+ if distro_id == "freebsd":
1919
+ return "FreeBSD"
1920
+
1921
+ if distro_id == "openbsd":
1922
+ return "OpenBSD"
1923
+
1924
+ return "Linux"
1925
+
1926
+ if platform_name:
1927
+ return OtherPlatform(platform_name)
1928
+
1929
+ return "Unknown"
1930
+
1931
+
1932
+ @lru_cache(maxsize=None)
1933
+ def platform_headers(version: str, *, platform: Platform | None) -> Dict[str, str]:
1934
+ return {
1935
+ "X-Stainless-Lang": "python",
1936
+ "X-Stainless-Package-Version": version,
1937
+ "X-Stainless-OS": str(platform or get_platform()),
1938
+ "X-Stainless-Arch": str(get_architecture()),
1939
+ "X-Stainless-Runtime": get_python_runtime(),
1940
+ "X-Stainless-Runtime-Version": get_python_version(),
1941
+ }
1942
+
1943
+
1944
+ class OtherArch:
1945
+ def __init__(self, name: str) -> None:
1946
+ self.name = name
1947
+
1948
+ @override
1949
+ def __str__(self) -> str:
1950
+ return f"other:{self.name}"
1951
+
1952
+
1953
+ Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]]
1954
+
1955
+
1956
+ def get_python_runtime() -> str:
1957
+ try:
1958
+ return platform.python_implementation()
1959
+ except Exception:
1960
+ return "unknown"
1961
+
1962
+
1963
+ def get_python_version() -> str:
1964
+ try:
1965
+ return platform.python_version()
1966
+ except Exception:
1967
+ return "unknown"
1968
+
1969
+
1970
+ def get_architecture() -> Arch:
1971
+ try:
1972
+ python_bitness, _ = platform.architecture()
1973
+ machine = platform.machine().lower()
1974
+ except Exception:
1975
+ return "unknown"
1976
+
1977
+ if machine in ("arm64", "aarch64"):
1978
+ return "arm64"
1979
+
1980
+ # TODO: untested
1981
+ if machine == "arm":
1982
+ return "arm"
1983
+
1984
+ if machine == "x86_64":
1985
+ return "x64"
1986
+
1987
+ # TODO: untested
1988
+ if python_bitness == "32bit":
1989
+ return "x32"
1990
+
1991
+ if machine:
1992
+ return OtherArch(machine)
1993
+
1994
+ return "unknown"
1995
+
1996
+
1997
+ def _merge_mappings(
1998
+ obj1: Mapping[_T_co, Union[_T, Omit]],
1999
+ obj2: Mapping[_T_co, Union[_T, Omit]],
2000
+ ) -> Dict[_T_co, _T]:
2001
+ """Merge two mappings of the same type, removing any values that are instances of `Omit`.
2002
+
2003
+ In cases with duplicate keys the second mapping takes precedence.
2004
+ """
2005
+ merged = {**obj1, **obj2}
2006
+ return {key: value for key, value in merged.items() if not isinstance(value, Omit)}