spitch 0.0.7__py3-none-any.whl → 1.0.0__py3-none-any.whl

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

Potentially problematic release.


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

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