studyfetch-sdk 0.1.0a1__py3-none-any.whl

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