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