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