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