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