byteplussdk-arkruntime 3.0.64__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 (240) hide show
  1. byteplussdk_arkruntime-3.0.64.dist-info/METADATA +36 -0
  2. byteplussdk_arkruntime-3.0.64.dist-info/RECORD +240 -0
  3. byteplussdk_arkruntime-3.0.64.dist-info/WHEEL +5 -0
  4. byteplussdk_arkruntime-3.0.64.dist-info/licenses/LICENSE.txt +203 -0
  5. byteplussdk_arkruntime-3.0.64.dist-info/top_level.txt +1 -0
  6. byteplussdkarkruntime/__init__.py +7 -0
  7. byteplussdkarkruntime/_base_client.py +1439 -0
  8. byteplussdkarkruntime/_client.py +570 -0
  9. byteplussdkarkruntime/_compat.py +245 -0
  10. byteplussdkarkruntime/_constants.py +43 -0
  11. byteplussdkarkruntime/_exceptions.py +202 -0
  12. byteplussdkarkruntime/_files.py +149 -0
  13. byteplussdkarkruntime/_legacy_response.py +451 -0
  14. byteplussdkarkruntime/_models.py +734 -0
  15. byteplussdkarkruntime/_qs.py +168 -0
  16. byteplussdkarkruntime/_request_options.py +117 -0
  17. byteplussdkarkruntime/_resource.py +47 -0
  18. byteplussdkarkruntime/_response.py +615 -0
  19. byteplussdkarkruntime/_streaming.py +470 -0
  20. byteplussdkarkruntime/_types.py +210 -0
  21. byteplussdkarkruntime/_utils/__init__.py +58 -0
  22. byteplussdkarkruntime/_utils/_key_agreement.py +207 -0
  23. byteplussdkarkruntime/_utils/_logs.py +24 -0
  24. byteplussdkarkruntime/_utils/_model_breaker.py +83 -0
  25. byteplussdkarkruntime/_utils/_streams.py +12 -0
  26. byteplussdkarkruntime/_utils/_transform.py +489 -0
  27. byteplussdkarkruntime/_utils/_typing.py +171 -0
  28. byteplussdkarkruntime/_utils/_utils.py +497 -0
  29. byteplussdkarkruntime/common/__init__.py +14 -0
  30. byteplussdkarkruntime/common/_parsing/__init__.py +22 -0
  31. byteplussdkarkruntime/common/_parsing/_completions.py +290 -0
  32. byteplussdkarkruntime/common/_parsing/_responses.py +189 -0
  33. byteplussdkarkruntime/common/_pydantic.py +192 -0
  34. byteplussdkarkruntime/common/_tools.py +67 -0
  35. byteplussdkarkruntime/common/streaming/__init__.py +12 -0
  36. byteplussdkarkruntime/common/streaming/_deltas.py +86 -0
  37. byteplussdkarkruntime/common/streaming/chat/__init__.py +33 -0
  38. byteplussdkarkruntime/common/streaming/chat/_completions.py +772 -0
  39. byteplussdkarkruntime/common/streaming/chat/_events.py +103 -0
  40. byteplussdkarkruntime/common/streaming/chat/_types.py +36 -0
  41. byteplussdkarkruntime/pagination.py +134 -0
  42. byteplussdkarkruntime/resources/__init__.py +48 -0
  43. byteplussdkarkruntime/resources/batch/__init__.py +3 -0
  44. byteplussdkarkruntime/resources/batch/_utils.py +155 -0
  45. byteplussdkarkruntime/resources/batch/batch.py +37 -0
  46. byteplussdkarkruntime/resources/batch/chat/__init__.py +3 -0
  47. byteplussdkarkruntime/resources/batch/chat/chat.py +19 -0
  48. byteplussdkarkruntime/resources/batch/chat/completions.py +329 -0
  49. byteplussdkarkruntime/resources/batch/embeddings.py +105 -0
  50. byteplussdkarkruntime/resources/batch/multimodal_embeddings.py +111 -0
  51. byteplussdkarkruntime/resources/batch_chat/__init__.py +3 -0
  52. byteplussdkarkruntime/resources/batch_chat/chat.py +21 -0
  53. byteplussdkarkruntime/resources/batch_chat/completions.py +328 -0
  54. byteplussdkarkruntime/resources/beta/__init__.py +12 -0
  55. byteplussdkarkruntime/resources/beta/beta.py +81 -0
  56. byteplussdkarkruntime/resources/beta/chat/__init__.py +21 -0
  57. byteplussdkarkruntime/resources/beta/chat/chat.py +31 -0
  58. byteplussdkarkruntime/resources/beta/chat/completions.py +454 -0
  59. byteplussdkarkruntime/resources/chat/__init__.py +3 -0
  60. byteplussdkarkruntime/resources/chat/chat.py +21 -0
  61. byteplussdkarkruntime/resources/chat/completions.py +258 -0
  62. byteplussdkarkruntime/resources/content_generation/__init__.py +6 -0
  63. byteplussdkarkruntime/resources/content_generation/content_generation.py +17 -0
  64. byteplussdkarkruntime/resources/content_generation/tasks.py +348 -0
  65. byteplussdkarkruntime/resources/context/__init__.py +3 -0
  66. byteplussdkarkruntime/resources/context/completions.py +221 -0
  67. byteplussdkarkruntime/resources/context/context.py +98 -0
  68. byteplussdkarkruntime/resources/embeddings.py +110 -0
  69. byteplussdkarkruntime/resources/encryption.py +215 -0
  70. byteplussdkarkruntime/resources/files.py +592 -0
  71. byteplussdkarkruntime/resources/images/__init__.py +6 -0
  72. byteplussdkarkruntime/resources/images/images.py +335 -0
  73. byteplussdkarkruntime/resources/multimodal_embeddings.py +113 -0
  74. byteplussdkarkruntime/resources/responses/__init__.py +16 -0
  75. byteplussdkarkruntime/resources/responses/input_items.py +248 -0
  76. byteplussdkarkruntime/resources/responses/responses.py +417 -0
  77. byteplussdkarkruntime/types/__init__.py +28 -0
  78. byteplussdkarkruntime/types/chat/__init__.py +78 -0
  79. byteplussdkarkruntime/types/chat/chat_completion.py +93 -0
  80. byteplussdkarkruntime/types/chat/chat_completion_assistant_message_param.py +61 -0
  81. byteplussdkarkruntime/types/chat/chat_completion_audio.py +22 -0
  82. byteplussdkarkruntime/types/chat/chat_completion_chunk.py +165 -0
  83. byteplussdkarkruntime/types/chat/chat_completion_content_part_image_param.py +20 -0
  84. byteplussdkarkruntime/types/chat/chat_completion_content_part_param.py +30 -0
  85. byteplussdkarkruntime/types/chat/chat_completion_content_part_text_param.py +13 -0
  86. byteplussdkarkruntime/types/chat/chat_completion_content_part_video_param.py +32 -0
  87. byteplussdkarkruntime/types/chat/chat_completion_function_call_option_param.py +10 -0
  88. byteplussdkarkruntime/types/chat/chat_completion_function_message_param.py +17 -0
  89. byteplussdkarkruntime/types/chat/chat_completion_message.py +56 -0
  90. byteplussdkarkruntime/types/chat/chat_completion_message_param.py +19 -0
  91. byteplussdkarkruntime/types/chat/chat_completion_message_tool_call.py +29 -0
  92. byteplussdkarkruntime/types/chat/chat_completion_message_tool_call_param.py +29 -0
  93. byteplussdkarkruntime/types/chat/chat_completion_named_tool_choice_param.py +17 -0
  94. byteplussdkarkruntime/types/chat/chat_completion_role.py +5 -0
  95. byteplussdkarkruntime/types/chat/chat_completion_stream_options_param.py +19 -0
  96. byteplussdkarkruntime/types/chat/chat_completion_system_message_param.py +34 -0
  97. byteplussdkarkruntime/types/chat/chat_completion_token_logprob.py +55 -0
  98. byteplussdkarkruntime/types/chat/chat_completion_tool_choice_option_param.py +12 -0
  99. byteplussdkarkruntime/types/chat/chat_completion_tool_message_param.py +37 -0
  100. byteplussdkarkruntime/types/chat/chat_completion_tool_param.py +14 -0
  101. byteplussdkarkruntime/types/chat/chat_completion_user_message_param.py +34 -0
  102. byteplussdkarkruntime/types/chat/completion_create_params.py +258 -0
  103. byteplussdkarkruntime/types/chat/parsed_chat_completion.py +52 -0
  104. byteplussdkarkruntime/types/chat/parsed_function_tool_call.py +34 -0
  105. byteplussdkarkruntime/types/completion_usage.py +33 -0
  106. byteplussdkarkruntime/types/content_generation/__init__.py +0 -0
  107. byteplussdkarkruntime/types/content_generation/content_generation_task.py +106 -0
  108. byteplussdkarkruntime/types/content_generation/content_generation_task_id.py +11 -0
  109. byteplussdkarkruntime/types/content_generation/create_task_content_param.py +72 -0
  110. byteplussdkarkruntime/types/content_generation/list_content_generation_tasks_response.py +24 -0
  111. byteplussdkarkruntime/types/context/__init__.py +8 -0
  112. byteplussdkarkruntime/types/context/context_chat_completion.py +33 -0
  113. byteplussdkarkruntime/types/context/context_chat_completion_chunk.py +41 -0
  114. byteplussdkarkruntime/types/context/context_create_params.py +37 -0
  115. byteplussdkarkruntime/types/context/create_context_response.py +25 -0
  116. byteplussdkarkruntime/types/context/truncation_strategy.py +13 -0
  117. byteplussdkarkruntime/types/create_embedding_response.py +36 -0
  118. byteplussdkarkruntime/types/embedding.py +21 -0
  119. byteplussdkarkruntime/types/file_create_params.py +49 -0
  120. byteplussdkarkruntime/types/file_deleted.py +24 -0
  121. byteplussdkarkruntime/types/file_list_params.py +43 -0
  122. byteplussdkarkruntime/types/file_object.py +69 -0
  123. byteplussdkarkruntime/types/file_purpose.py +16 -0
  124. byteplussdkarkruntime/types/images/__init__.py +3 -0
  125. byteplussdkarkruntime/types/images/image_gen_completed_event.py +59 -0
  126. byteplussdkarkruntime/types/images/image_gen_generating_event.py +53 -0
  127. byteplussdkarkruntime/types/images/image_gen_stream_event.py +24 -0
  128. byteplussdkarkruntime/types/images/images.py +99 -0
  129. byteplussdkarkruntime/types/multimodal_embedding/__init__.py +15 -0
  130. byteplussdkarkruntime/types/multimodal_embedding/embedding_content_part_image_param.py +17 -0
  131. byteplussdkarkruntime/types/multimodal_embedding/embedding_content_part_text_param.py +13 -0
  132. byteplussdkarkruntime/types/multimodal_embedding/embedding_data.py +15 -0
  133. byteplussdkarkruntime/types/multimodal_embedding/embedding_input.py +12 -0
  134. byteplussdkarkruntime/types/multimodal_embedding/embedding_response.py +29 -0
  135. byteplussdkarkruntime/types/multimodal_embedding/embedding_usage.py +23 -0
  136. byteplussdkarkruntime/types/responses/__init__.py +133 -0
  137. byteplussdkarkruntime/types/responses/easy_input_message.py +36 -0
  138. byteplussdkarkruntime/types/responses/easy_input_message_param.py +37 -0
  139. byteplussdkarkruntime/types/responses/function_tool.py +35 -0
  140. byteplussdkarkruntime/types/responses/function_tool_param.py +35 -0
  141. byteplussdkarkruntime/types/responses/input_item_list_params.py +47 -0
  142. byteplussdkarkruntime/types/responses/mcp_input_item_param.py +109 -0
  143. byteplussdkarkruntime/types/responses/mcp_tool.py +80 -0
  144. byteplussdkarkruntime/types/responses/mcp_tool_param.py +78 -0
  145. byteplussdkarkruntime/types/responses/response.py +152 -0
  146. byteplussdkarkruntime/types/responses/response_annotation_added_event.py +36 -0
  147. byteplussdkarkruntime/types/responses/response_caching.py +25 -0
  148. byteplussdkarkruntime/types/responses/response_caching_param.py +22 -0
  149. byteplussdkarkruntime/types/responses/response_completed_event.py +26 -0
  150. byteplussdkarkruntime/types/responses/response_content_part_added_event.py +39 -0
  151. byteplussdkarkruntime/types/responses/response_content_part_done_event.py +39 -0
  152. byteplussdkarkruntime/types/responses/response_create_params.py +26 -0
  153. byteplussdkarkruntime/types/responses/response_created_event.py +26 -0
  154. byteplussdkarkruntime/types/responses/response_error.py +25 -0
  155. byteplussdkarkruntime/types/responses/response_error_event.py +32 -0
  156. byteplussdkarkruntime/types/responses/response_failed_event.py +26 -0
  157. byteplussdkarkruntime/types/responses/response_format_text_config.py +25 -0
  158. byteplussdkarkruntime/types/responses/response_format_text_config_param.py +25 -0
  159. byteplussdkarkruntime/types/responses/response_function_call_arguments_delta_event.py +33 -0
  160. byteplussdkarkruntime/types/responses/response_function_call_arguments_done_event.py +30 -0
  161. byteplussdkarkruntime/types/responses/response_function_tool_call.py +42 -0
  162. byteplussdkarkruntime/types/responses/response_function_tool_call_item.py +20 -0
  163. byteplussdkarkruntime/types/responses/response_function_tool_call_output_item.py +39 -0
  164. byteplussdkarkruntime/types/responses/response_function_tool_call_param.py +31 -0
  165. byteplussdkarkruntime/types/responses/response_in_progress_event.py +26 -0
  166. byteplussdkarkruntime/types/responses/response_includable.py +19 -0
  167. byteplussdkarkruntime/types/responses/response_incomplete_details.py +30 -0
  168. byteplussdkarkruntime/types/responses/response_incomplete_event.py +26 -0
  169. byteplussdkarkruntime/types/responses/response_input_content.py +24 -0
  170. byteplussdkarkruntime/types/responses/response_input_content_param.py +23 -0
  171. byteplussdkarkruntime/types/responses/response_input_image.py +38 -0
  172. byteplussdkarkruntime/types/responses/response_input_image_param.py +42 -0
  173. byteplussdkarkruntime/types/responses/response_input_image_pixel_limit_param.py +29 -0
  174. byteplussdkarkruntime/types/responses/response_input_message_content_list.py +20 -0
  175. byteplussdkarkruntime/types/responses/response_input_message_content_list_param.py +26 -0
  176. byteplussdkarkruntime/types/responses/response_input_message_item.py +43 -0
  177. byteplussdkarkruntime/types/responses/response_input_param.py +51 -0
  178. byteplussdkarkruntime/types/responses/response_input_text.py +25 -0
  179. byteplussdkarkruntime/types/responses/response_input_text_param.py +25 -0
  180. byteplussdkarkruntime/types/responses/response_input_video_param.py +34 -0
  181. byteplussdkarkruntime/types/responses/response_item.py +40 -0
  182. byteplussdkarkruntime/types/responses/response_item_list.py +36 -0
  183. byteplussdkarkruntime/types/responses/response_mcp_call_arguments_delta_event.py +37 -0
  184. byteplussdkarkruntime/types/responses/response_mcp_call_arguments_done_event.py +34 -0
  185. byteplussdkarkruntime/types/responses/response_mcp_call_completed_event.py +31 -0
  186. byteplussdkarkruntime/types/responses/response_mcp_call_failed_event.py +31 -0
  187. byteplussdkarkruntime/types/responses/response_mcp_call_in_progress_event.py +31 -0
  188. byteplussdkarkruntime/types/responses/response_mcp_item.py +110 -0
  189. byteplussdkarkruntime/types/responses/response_mcp_list_tools_completed_event.py +31 -0
  190. byteplussdkarkruntime/types/responses/response_mcp_list_tools_failed_event.py +31 -0
  191. byteplussdkarkruntime/types/responses/response_mcp_list_tools_in_progress_event.py +31 -0
  192. byteplussdkarkruntime/types/responses/response_output_item.py +36 -0
  193. byteplussdkarkruntime/types/responses/response_output_item_added_event.py +29 -0
  194. byteplussdkarkruntime/types/responses/response_output_item_done_event.py +29 -0
  195. byteplussdkarkruntime/types/responses/response_output_message.py +43 -0
  196. byteplussdkarkruntime/types/responses/response_output_text.py +61 -0
  197. byteplussdkarkruntime/types/responses/response_output_text_param.py +77 -0
  198. byteplussdkarkruntime/types/responses/response_reasoning_item.py +46 -0
  199. byteplussdkarkruntime/types/responses/response_reasoning_item_param.py +37 -0
  200. byteplussdkarkruntime/types/responses/response_reasoning_summary_part_added_event.py +42 -0
  201. byteplussdkarkruntime/types/responses/response_reasoning_summary_part_done_event.py +42 -0
  202. byteplussdkarkruntime/types/responses/response_reasoning_summary_text_delta_event.py +34 -0
  203. byteplussdkarkruntime/types/responses/response_reasoning_summary_text_done_event.py +34 -0
  204. byteplussdkarkruntime/types/responses/response_status.py +17 -0
  205. byteplussdkarkruntime/types/responses/response_stream_event.py +93 -0
  206. byteplussdkarkruntime/types/responses/response_text_config.py +28 -0
  207. byteplussdkarkruntime/types/responses/response_text_config_param.py +31 -0
  208. byteplussdkarkruntime/types/responses/response_text_delta_event.py +34 -0
  209. byteplussdkarkruntime/types/responses/response_text_done_event.py +34 -0
  210. byteplussdkarkruntime/types/responses/response_tool_usage.py +32 -0
  211. byteplussdkarkruntime/types/responses/response_usage.py +54 -0
  212. byteplussdkarkruntime/types/responses/response_web_search_call_completed_event.py +29 -0
  213. byteplussdkarkruntime/types/responses/response_web_search_call_in_progress_event.py +29 -0
  214. byteplussdkarkruntime/types/responses/response_web_search_call_searching_event.py +29 -0
  215. byteplussdkarkruntime/types/responses/response_web_search_item.py +43 -0
  216. byteplussdkarkruntime/types/responses/tool.py +25 -0
  217. byteplussdkarkruntime/types/responses/tool_choice_function.py +25 -0
  218. byteplussdkarkruntime/types/responses/tool_choice_function_param.py +25 -0
  219. byteplussdkarkruntime/types/responses/tool_choice_mcp_param.py +29 -0
  220. byteplussdkarkruntime/types/responses/tool_choice_options.py +17 -0
  221. byteplussdkarkruntime/types/responses/tool_param.py +24 -0
  222. byteplussdkarkruntime/types/responses/web_search_tool.py +49 -0
  223. byteplussdkarkruntime/types/responses/web_search_tool_param.py +46 -0
  224. byteplussdkarkruntime/types/shared/__init__.py +21 -0
  225. byteplussdkarkruntime/types/shared/reasoning.py +10 -0
  226. byteplussdkarkruntime/types/shared/reasoning_effort.py +16 -0
  227. byteplussdkarkruntime/types/shared/response_format_json_object.py +22 -0
  228. byteplussdkarkruntime/types/shared/response_format_json_schema.py +56 -0
  229. byteplussdkarkruntime/types/shared/response_format_text.py +22 -0
  230. byteplussdkarkruntime/types/shared/thinking.py +25 -0
  231. byteplussdkarkruntime/types/shared_params/__init__.py +13 -0
  232. byteplussdkarkruntime/types/shared_params/function_definition.py +34 -0
  233. byteplussdkarkruntime/types/shared_params/function_parameters.py +9 -0
  234. byteplussdkarkruntime/types/shared_params/metadata.py +20 -0
  235. byteplussdkarkruntime/types/shared_params/reasoning.py +12 -0
  236. byteplussdkarkruntime/types/shared_params/reasoning_effort.py +8 -0
  237. byteplussdkarkruntime/types/shared_params/response_format_json_object.py +22 -0
  238. byteplussdkarkruntime/types/shared_params/response_format_json_schema.py +54 -0
  239. byteplussdkarkruntime/types/shared_params/response_format_text.py +22 -0
  240. byteplussdkarkruntime/types/shared_params/thinking.py +22 -0
@@ -0,0 +1,1439 @@
1
+ # Copyright (c) [2025] [OpenAI]
2
+ # Copyright (c) [2025] [ByteDance Ltd. and/or its affiliates.]
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # This file has been modified by [ByteDance Ltd. and/or its affiliates.] on 2025.7
6
+ #
7
+ # Original file was released under Apache License Version 2.0, with the full license text
8
+ # available at https://github.com/openai/openai-python/blob/main/LICENSE.
9
+ #
10
+ # This modified file is released under the same license.
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import json
16
+ import logging
17
+ import time
18
+ from random import random
19
+ from types import TracebackType
20
+ from typing import (
21
+ TYPE_CHECKING,
22
+ Any,
23
+ Dict,
24
+ Type,
25
+ Union,
26
+ Generic,
27
+ Mapping,
28
+ TypeVar,
29
+ Iterable,
30
+ Iterator,
31
+ Optional,
32
+ Generator,
33
+ AsyncIterator,
34
+ cast,
35
+ )
36
+ from typing_extensions import override
37
+
38
+ import anyio
39
+ import httpx
40
+ import pydantic
41
+
42
+ from pydantic import PrivateAttr
43
+ from httpx import URL, Timeout, Limits
44
+ from httpx._types import RequestFiles
45
+
46
+ from . import _exceptions # type: ignore
47
+ from ._qs import Querystring
48
+ from ._constants import (
49
+ DEFAULT_MAX_RETRIES,
50
+ DEFAULT_TIMEOUT,
51
+ INITIAL_RETRY_DELAY,
52
+ MAX_RETRY_DELAY,
53
+ RAW_RESPONSE_HEADER,
54
+ DEFAULT_CONNECTION_LIMITS,
55
+ CLIENT_REQUEST_HEADER,
56
+ VERSION,
57
+ )
58
+ from ._exceptions import (
59
+ ArkAPITimeoutError,
60
+ ArkAPIConnectionError,
61
+ ArkAPIStatusError,
62
+ ArkAPIResponseValidationError,
63
+ )
64
+ from ._files import to_httpx_files, async_to_httpx_files
65
+ from ._models import construct_type, GenericModel
66
+ from ._request_options import RequestOptions, ExtraRequestOptions
67
+ from ._response import ArkAPIResponse, ArkAsyncAPIResponse
68
+ from ._streaming import SSEDecoder, SSEBytesDecoder, Stream, AsyncStream
69
+ from ._types import (
70
+ ResponseT,
71
+ NotGiven,
72
+ NOT_GIVEN,
73
+ PostParser,
74
+ Body,
75
+ Query,
76
+ HttpxRequestFiles,
77
+ )
78
+ from ._utils._utils import _gen_request_id, is_given, is_mapping, is_dict, is_list
79
+ from ._compat import model_copy, PYDANTIC_V2, model_dump
80
+
81
+ SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]")
82
+ AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]")
83
+
84
+ _T = TypeVar("_T")
85
+ _T_co = TypeVar("_T_co", covariant=True)
86
+
87
+ _StreamT = TypeVar("_StreamT", bound=Stream[Any])
88
+ _AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any])
89
+
90
+ log: logging.Logger = logging.getLogger(__name__)
91
+
92
+
93
+ class _DefaultHttpxClient(httpx.Client):
94
+ def __init__(self, **kwargs: Any) -> None:
95
+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
96
+ kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
97
+ kwargs.setdefault("follow_redirects", True)
98
+ super().__init__(**kwargs)
99
+
100
+
101
+ if TYPE_CHECKING:
102
+ DefaultHttpxClient = httpx.Client
103
+ """An alias to `httpx.Client` that provides the same defaults that this SDK
104
+ uses internally.
105
+
106
+ This is useful because overriding the `http_client` with your own instance of
107
+ `httpx.Client` will result in httpx's defaults being used, not ours.
108
+ """
109
+ else:
110
+ DefaultHttpxClient = _DefaultHttpxClient
111
+
112
+
113
+ class SyncHttpxClientWrapper(DefaultHttpxClient):
114
+ def __del__(self) -> None:
115
+ try:
116
+ self.close()
117
+ except Exception:
118
+ pass
119
+
120
+
121
+ def make_request_options(
122
+ *,
123
+ query: Dict[str, Any] | None = None,
124
+ extra_headers: Dict[str, str] | None = None,
125
+ extra_query: Dict[str, Any] | None = None,
126
+ extra_body: Dict[str, Any] | None = None,
127
+ timeout: float | httpx.Timeout | None = None,
128
+ post_parser: PostParser | NotGiven = NOT_GIVEN,
129
+ ) -> ExtraRequestOptions:
130
+ options: ExtraRequestOptions = {}
131
+ if extra_headers is not None:
132
+ options["headers"] = extra_headers
133
+
134
+ if extra_body is not None:
135
+ options["extra_body"] = extra_body
136
+
137
+ if query is not None:
138
+ options["params"] = query
139
+
140
+ if extra_query is not None:
141
+ options["params"] = {**options.get("params", {}), **extra_query}
142
+
143
+ if timeout:
144
+ options["timeout"] = timeout
145
+
146
+ if is_given(post_parser):
147
+ # internal
148
+ options["post_parser"] = post_parser # type: ignore
149
+
150
+ return options
151
+
152
+
153
+ _HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient])
154
+
155
+
156
+ class BaseClient(Generic[_HttpxClientT]):
157
+ _client: _HttpxClientT
158
+ _base_url: URL
159
+ max_retries: int
160
+ timeout: Union[float, Timeout, None]
161
+ _limits: Union[httpx.Limits, None]
162
+
163
+ def __init__(
164
+ self,
165
+ *,
166
+ base_url: str | URL,
167
+ max_retries: int = DEFAULT_MAX_RETRIES,
168
+ timeout: float | Timeout | None = DEFAULT_TIMEOUT,
169
+ limits: Limits | None = None,
170
+ custom_headers: Dict[str, str] | None = None,
171
+ custom_query: Dict[str, Any] | None = None,
172
+ ) -> None:
173
+ self._base_url = self._enforce_trailing_slash(URL(base_url))
174
+ self.max_retries = max_retries
175
+ self.timeout = timeout
176
+ self._limits = limits
177
+ self._custom_headers = custom_headers or {}
178
+ self._custom_query = custom_query or {}
179
+
180
+ if max_retries is None: # pyright: ignore[reportUnnecessaryComparison]
181
+ raise TypeError(
182
+ "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`"
183
+ )
184
+
185
+ @property
186
+ def qs(self) -> Querystring:
187
+ return Querystring()
188
+
189
+ @property
190
+ def auth_headers(self) -> dict[str, str]:
191
+ return {}
192
+
193
+ @property
194
+ def user_agent(self) -> str:
195
+ return "byteplus-sdk-python/" + VERSION
196
+
197
+ def default_headers(self) -> Dict[str, str]:
198
+ return {
199
+ "Accept": "application/json",
200
+ "Content-Type": "application/json",
201
+ "User-Agent": self.user_agent,
202
+ CLIENT_REQUEST_HEADER: _gen_request_id(),
203
+ **self.auth_headers,
204
+ **self._custom_headers,
205
+ }
206
+
207
+ def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder:
208
+ return SSEDecoder()
209
+
210
+ def _build_headers(self, options: RequestOptions) -> httpx.Headers:
211
+ custom_headers = options.headers or {}
212
+ headers_dict = {**self.default_headers(), **custom_headers}
213
+ headers = httpx.Headers(headers_dict)
214
+
215
+ return headers
216
+
217
+ def _prepare_url(self, url: str) -> URL:
218
+ merge_url = URL(url)
219
+ if merge_url.is_relative_url:
220
+ merge_raw_path = self._base_url.raw_path + merge_url.raw_path.lstrip(b"/")
221
+ return self._base_url.copy_with(raw_path=merge_raw_path)
222
+
223
+ return merge_url
224
+
225
+ def _should_stream_response_body(self, request: httpx.Request) -> bool:
226
+ return request.headers.get(RAW_RESPONSE_HEADER) == "stream"
227
+
228
+ def _build_request(
229
+ self,
230
+ options: RequestOptions,
231
+ *,
232
+ retries_taken: int = 0,
233
+ ) -> httpx.Request:
234
+ if log.isEnabledFor(logging.DEBUG):
235
+ log.debug("Request options: %s", model_dump(options, exclude_unset=True))
236
+
237
+ kwargs: dict[str, Any] = {}
238
+
239
+ body = options.body
240
+ if options.extra_body is not None:
241
+ if body is None:
242
+ body = options.extra_body
243
+ elif isinstance(body, Dict):
244
+ body = {**body, **options.extra_body}
245
+ else:
246
+ raise RuntimeError(
247
+ f"Unexpected JSON data type, {type(body)}, cannot merge with `extra_body`"
248
+ )
249
+
250
+ headers = self._build_headers(options)
251
+ params = options.params
252
+ content_type = headers.get("Content-Type")
253
+ files = options.files
254
+
255
+ # If the given Content-Type header is multipart/form-data then it
256
+ # has to be removed so that httpx can generate the header with
257
+ # additional information for us as it has to be in this form
258
+ # for the server to be able to correctly parse the request:
259
+ # multipart/form-data; boundary=---abc--
260
+ if content_type is not None and content_type.startswith("multipart/form-data"):
261
+ if "boundary" not in content_type:
262
+ # only remove the header if the boundary hasn't been explicitly set
263
+ # as the caller doesn't want httpx to come up with their own boundary
264
+ headers.pop("Content-Type")
265
+
266
+ # As we are now sending multipart/form-data instead of application/json
267
+ # we need to tell httpx to use it, https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
268
+ if body:
269
+ if not is_dict(body):
270
+ raise TypeError(
271
+ f"Expected query input to be a dictionary for multipart requests but got {type(body)} instead."
272
+ )
273
+ kwargs["data"] = self._serialize_multipartform(body)
274
+
275
+ # httpx determines whether or not to send a "multipart/form-data"
276
+ # request based on the truthiness of the "files" argument.
277
+ # This gets around that issue by generating a dict value that
278
+ # evaluates to true.
279
+ #
280
+ # https://github.com/encode/httpx/discussions/2399#discussioncomment-3814186
281
+ if not files:
282
+ files = cast(HttpxRequestFiles, ForceMultipartDict())
283
+
284
+ prepared_url = self._prepare_url(options.url)
285
+ if "_" in prepared_url.host:
286
+ # work around https://github.com/encode/httpx/discussions/2880
287
+ kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")}
288
+
289
+ is_body_allowed = options.method.lower() != "get"
290
+
291
+ if is_body_allowed:
292
+ if isinstance(body, bytes):
293
+ kwargs["content"] = body
294
+ else:
295
+ kwargs["json"] = body if is_given(body) else None
296
+ kwargs["files"] = files
297
+ else:
298
+ headers.pop("Content-Type", None)
299
+ kwargs.pop("data", None)
300
+
301
+ # TODO: report this error to httpx
302
+ return self._client.build_request( # pyright: ignore[reportUnknownMemberType]
303
+ headers=headers,
304
+ timeout=self.timeout
305
+ if isinstance(options.timeout, NotGiven)
306
+ else options.timeout,
307
+ method=options.method,
308
+ url=prepared_url,
309
+ # the `Query` type that we use is incompatible with qs'
310
+ # `Params` type as it needs to be typed as `Mapping[str, object]`
311
+ # so that passing a `TypedDict` doesn't cause an error.
312
+ # https://github.com/microsoft/pyright/issues/3526#event-6715453066
313
+ params=self.qs.stringify(cast(Mapping[str, Any], params))
314
+ if params
315
+ else None,
316
+ **kwargs,
317
+ )
318
+
319
+ def _serialize_multipartform(
320
+ self, data: Mapping[object, object]
321
+ ) -> dict[str, object]:
322
+ items = self.qs.stringify_items(
323
+ # TODO: type ignore is required as stringify_items is well typed but we can't be
324
+ # well typed without heavy validation.
325
+ data, # type: ignore
326
+ array_format="brackets",
327
+ )
328
+ serialized: dict[str, object] = {}
329
+ for key, value in items:
330
+ existing = serialized.get(key)
331
+
332
+ if not existing:
333
+ serialized[key] = value
334
+ continue
335
+
336
+ # If a value has already been set for this key then that
337
+ # means we're sending data like `array[]=[1, 2, 3]` and we
338
+ # need to tell httpx that we want to send multiple values with
339
+ # the same key which is done by using a list or a tuple.
340
+ #
341
+ # Note: 2d arrays should never result in the same key at both
342
+ # levels so it's safe to assume that if the value is a list,
343
+ # it was because we changed it to be a list.
344
+ if is_list(existing):
345
+ existing.append(value)
346
+ else:
347
+ serialized[key] = [existing, value]
348
+
349
+ return serialized
350
+
351
+ def _calculate_retry_timeout(
352
+ self,
353
+ remaining_retries: int,
354
+ options: RequestOptions,
355
+ response_headers: Optional[httpx.Headers] = None,
356
+ ) -> float:
357
+ max_retries = options.max_retries if options.max_retries else self.max_retries
358
+
359
+ nb_retries = max_retries - remaining_retries
360
+
361
+ # Apply exponential backoff, but not more than the max.
362
+ sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY)
363
+
364
+ # Apply some jitter, plus-or-minus half a second.
365
+ jitter = 1 - 0.25 * random()
366
+ timeout = sleep_seconds * jitter
367
+ return timeout if timeout >= 0 else 0
368
+
369
+ def _should_retry(self, response: httpx.Response) -> bool:
370
+ # Note: this is not a standard header
371
+ should_retry_header = response.headers.get("x-should-retry")
372
+
373
+ # If the server explicitly says whether or not to retry, obey.
374
+ if should_retry_header == "true":
375
+ log.debug("Retrying as header `x-should-retry` is set to `true`")
376
+ return True
377
+ if should_retry_header == "false":
378
+ log.debug("Not retrying as header `x-should-retry` is set to `false`")
379
+ return False
380
+
381
+ # Retry on request timeouts.
382
+ if response.status_code == 408:
383
+ log.debug("Retrying due to status code %i", response.status_code)
384
+ return True
385
+
386
+ # Retry on lock timeouts.
387
+ if response.status_code == 409:
388
+ log.debug("Retrying due to status code %i", response.status_code)
389
+ return True
390
+
391
+ # Retry on rate limits.
392
+ if response.status_code == 429:
393
+ log.debug("Retrying due to status code %i", response.status_code)
394
+ return True
395
+
396
+ # Retry internal errors.
397
+ if response.status_code >= 500:
398
+ log.debug("Retrying due to status code %i", response.status_code)
399
+ return True
400
+
401
+ log.debug("Not retrying")
402
+ return False
403
+
404
+ def _make_status_error(
405
+ self, err_msg: str, *, body: object, response: httpx.Response, request_id: str
406
+ ) -> ArkAPIStatusError:
407
+ data = body.get("error", body) if isinstance(body, Dict) else body
408
+ if response.status_code == 400:
409
+ return _exceptions.ArkBadRequestError(
410
+ err_msg, response=response, body=data, request_id=request_id
411
+ )
412
+
413
+ if response.status_code == 401:
414
+ return _exceptions.ArkAuthenticationError(
415
+ err_msg, response=response, body=data, request_id=request_id
416
+ )
417
+
418
+ if response.status_code == 403:
419
+ return _exceptions.ArkPermissionDeniedError(
420
+ err_msg, response=response, body=data, request_id=request_id
421
+ )
422
+
423
+ if response.status_code == 404:
424
+ return _exceptions.ArkNotFoundError(
425
+ err_msg, response=response, body=data, request_id=request_id
426
+ )
427
+
428
+ if response.status_code == 409:
429
+ return _exceptions.ArkConflictError(
430
+ err_msg, response=response, body=data, request_id=request_id
431
+ )
432
+
433
+ if response.status_code == 422:
434
+ return _exceptions.ArkUnprocessableEntityError(
435
+ err_msg, response=response, body=data, request_id=request_id
436
+ )
437
+
438
+ if response.status_code == 429:
439
+ return _exceptions.ArkRateLimitError(
440
+ err_msg, response=response, body=data, request_id=request_id
441
+ )
442
+
443
+ if response.status_code >= 500:
444
+ return _exceptions.ArkInternalServerError(
445
+ err_msg, response=response, body=data, request_id=request_id
446
+ )
447
+ return ArkAPIStatusError(
448
+ err_msg, response=response, body=data, request_id=request_id
449
+ )
450
+
451
+ def _make_status_error_from_response(
452
+ self, response: httpx.Response, request_id: str
453
+ ) -> ArkAPIStatusError:
454
+ if response.is_closed and not response.is_stream_consumed:
455
+ body = None
456
+ err_msg = f"Error code: {response.status_code}"
457
+ else:
458
+ err_text = response.text.strip()
459
+ body = err_text
460
+
461
+ try:
462
+ body = json.loads(err_text)
463
+ err_msg = f"Error code: {response.status_code} - {body}"
464
+ except Exception:
465
+ err_msg = err_text or f"Error code: {response.status_code}"
466
+
467
+ return self._make_status_error(
468
+ err_msg, body=body, response=response, request_id=request_id
469
+ )
470
+
471
+ def _enforce_trailing_slash(self, url: URL) -> URL:
472
+ if url.raw_path.endswith(b"/"):
473
+ return url
474
+ return url.copy_with(raw_path=url.raw_path + b"/")
475
+
476
+ def _process_response_data(
477
+ self,
478
+ *,
479
+ data: object,
480
+ cast_to: type[ResponseT],
481
+ response: httpx.Response,
482
+ ) -> ResponseT:
483
+ request_id = (
484
+ response.headers.get(CLIENT_REQUEST_HEADER, "") if response else None
485
+ )
486
+ if data is None:
487
+ return cast(ResponseT, None)
488
+
489
+ if cast_to is object:
490
+ return cast(ResponseT, data)
491
+
492
+ try:
493
+ return cast(ResponseT, construct_type(type_=cast_to, value=data))
494
+ except pydantic.ValidationError as err:
495
+ raise ArkAPIResponseValidationError(
496
+ response=response, body=data, request_id=request_id
497
+ ) from err
498
+
499
+ def _remaining_retries(
500
+ self,
501
+ remaining_retries: Optional[int],
502
+ options: RequestOptions,
503
+ ) -> int:
504
+ return (
505
+ remaining_retries
506
+ if remaining_retries is not None
507
+ else options.get_max_retries(self.max_retries)
508
+ )
509
+
510
+
511
+ class SyncAPIClient(BaseClient):
512
+ _client: httpx.Client
513
+
514
+ def __init__(
515
+ self,
516
+ *,
517
+ base_url: str | URL,
518
+ max_retries: int = DEFAULT_MAX_RETRIES,
519
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
520
+ http_client: httpx.Client | None = None,
521
+ custom_headers: Dict[str, str] | None = None,
522
+ custom_query: Dict[str, object] | None = None,
523
+ ) -> None:
524
+ if http_client is not None and not isinstance(http_client, httpx.Client): # pyright: ignore[reportUnnecessaryIsInstance]
525
+ raise TypeError(
526
+ f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}"
527
+ )
528
+
529
+ super().__init__(
530
+ base_url=base_url,
531
+ timeout=cast(Timeout, timeout),
532
+ max_retries=max_retries,
533
+ custom_query=custom_query,
534
+ custom_headers=custom_headers,
535
+ )
536
+
537
+ self._client = http_client or SyncHttpxClientWrapper(
538
+ base_url=self._enforce_trailing_slash(URL(base_url)),
539
+ timeout=cast(Timeout, timeout),
540
+ )
541
+
542
+ def _request(
543
+ self,
544
+ *,
545
+ cast_to: Type[ResponseT],
546
+ options: RequestOptions,
547
+ remaining_retries: int | None,
548
+ stream: bool,
549
+ stream_cls: type[_StreamT] | None,
550
+ ) -> ResponseT | _StreamT:
551
+ retries = self._remaining_retries(remaining_retries, options)
552
+ request = self._build_request(options)
553
+ req_id = request.headers.get(CLIENT_REQUEST_HEADER, "")
554
+ try:
555
+ response = self._client.send(
556
+ request,
557
+ stream=stream or self._should_stream_response_body(request=request),
558
+ )
559
+ except httpx.TimeoutException as err:
560
+ if retries > 0:
561
+ return self._retry_request(
562
+ options,
563
+ cast_to,
564
+ retries,
565
+ stream=stream,
566
+ stream_cls=stream_cls,
567
+ response_headers=None,
568
+ )
569
+
570
+ log.debug("Raising timeout error")
571
+ raise ArkAPITimeoutError(request=request, request_id=req_id) from err
572
+ except Exception as err:
573
+ log.debug("Encountered Exception", exc_info=True)
574
+
575
+ if retries > 0:
576
+ return self._retry_request(
577
+ options,
578
+ cast_to,
579
+ retries,
580
+ stream=stream,
581
+ stream_cls=stream_cls,
582
+ response_headers=None,
583
+ )
584
+
585
+ log.debug("Raising connection error")
586
+ raise ArkAPIConnectionError(request=request, request_id=req_id) from err
587
+
588
+ log.debug(
589
+ 'HTTP Request: %s %s "%i %s"',
590
+ request.method,
591
+ request.url,
592
+ response.status_code,
593
+ response.reason_phrase,
594
+ )
595
+
596
+ try:
597
+ response.raise_for_status()
598
+ except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code
599
+ log.debug("Encountered httpx.HTTPStatusError", exc_info=True)
600
+
601
+ if retries > 0 and self._should_retry(err.response):
602
+ err.response.close()
603
+ return self._retry_request(
604
+ options,
605
+ cast_to,
606
+ retries,
607
+ err.response.headers,
608
+ stream=stream,
609
+ stream_cls=stream_cls,
610
+ )
611
+
612
+ # If the response is streamed then we need to explicitly read the response
613
+ # to completion before attempting to access the response text.
614
+ if not err.response.is_closed:
615
+ err.response.read()
616
+
617
+ log.debug("Re-raising status error")
618
+ raise self._make_status_error_from_response(
619
+ err.response, request_id=req_id
620
+ ) from None
621
+
622
+ return self._process_response(
623
+ cast_to=cast_to,
624
+ response=response,
625
+ stream=stream,
626
+ stream_cls=stream_cls,
627
+ options=options,
628
+ )
629
+
630
+ def _retry_request(
631
+ self,
632
+ options: RequestOptions,
633
+ cast_to: Type[ResponseT],
634
+ remaining_retries: int,
635
+ response_headers: httpx.Headers | None,
636
+ *,
637
+ stream: bool,
638
+ stream_cls: type[_StreamT] | None,
639
+ ) -> ResponseT | _StreamT:
640
+ remaining = remaining_retries - 1
641
+ if remaining == 1:
642
+ log.info("1 retry left")
643
+ else:
644
+ log.info("%i retries left", remaining)
645
+
646
+ timeout = self._calculate_retry_timeout(remaining, options, response_headers)
647
+ log.info("Retrying request to %s in %f seconds", options.url, timeout)
648
+
649
+ # In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a
650
+ # different thread if necessary.
651
+ time.sleep(timeout)
652
+
653
+ return self._request(
654
+ options=options,
655
+ cast_to=cast_to,
656
+ remaining_retries=remaining,
657
+ stream=stream,
658
+ stream_cls=stream_cls,
659
+ )
660
+
661
+ def _process_response(
662
+ self,
663
+ *,
664
+ cast_to: Type[ResponseT],
665
+ options: RequestOptions,
666
+ response: httpx.Response,
667
+ stream: bool,
668
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
669
+ ) -> ResponseT:
670
+ if cast_to == httpx.Response:
671
+ return cast(ResponseT, response)
672
+
673
+ api_response = ArkAPIResponse(
674
+ raw=response,
675
+ client=self,
676
+ cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
677
+ stream=stream,
678
+ stream_cls=stream_cls,
679
+ options=options,
680
+ )
681
+ if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
682
+ return cast(ResponseT, api_response)
683
+
684
+ return api_response.parse()
685
+
686
+ def post(
687
+ self,
688
+ path: str,
689
+ *,
690
+ cast_to: Type[ResponseT],
691
+ body: Dict | None = None,
692
+ options: ExtraRequestOptions = {},
693
+ files: RequestFiles | None = None,
694
+ stream: bool = False,
695
+ stream_cls: type[_StreamT] | None = None,
696
+ ) -> ResponseT | _StreamT:
697
+ opts = RequestOptions.construct( # type: ignore
698
+ method="post",
699
+ url=path,
700
+ files=to_httpx_files(files),
701
+ body=body,
702
+ **options,
703
+ )
704
+
705
+ return cast(
706
+ ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
707
+ )
708
+
709
+ def get(
710
+ self,
711
+ path: str,
712
+ *,
713
+ cast_to: Type[ResponseT],
714
+ params: list[tuple[str, str]] | None = None,
715
+ options: ExtraRequestOptions = {},
716
+ stream: bool = False,
717
+ stream_cls: type[_StreamT] | None = None,
718
+ ) -> ResponseT | _StreamT:
719
+ opts = RequestOptions.construct(
720
+ method="get",
721
+ url=path,
722
+ params=params,
723
+ **options,
724
+ )
725
+
726
+ return cast(
727
+ ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
728
+ )
729
+
730
+ def delete(
731
+ self,
732
+ path: str,
733
+ *,
734
+ cast_to: Type[ResponseT],
735
+ params: list[tuple[str, str]] | None = None,
736
+ options: ExtraRequestOptions = {},
737
+ ) -> ResponseT:
738
+ opts = RequestOptions.construct( # type: ignore
739
+ method="delete",
740
+ url=path,
741
+ params=params,
742
+ **options,
743
+ )
744
+
745
+ return cast(ResponseT, self.request(cast_to, opts))
746
+
747
+ def post_without_retry(
748
+ self,
749
+ path: str,
750
+ *,
751
+ cast_to: Type[ResponseT],
752
+ body: Dict | None = None,
753
+ options: ExtraRequestOptions = {},
754
+ files: RequestFiles | None = None,
755
+ stream: bool = False,
756
+ stream_cls: type[_StreamT] | None = None,
757
+ ) -> ResponseT | _StreamT:
758
+ opts = RequestOptions.construct( # type: ignore
759
+ method="post",
760
+ url=path,
761
+ body=body,
762
+ files=files,
763
+ **options,
764
+ )
765
+
766
+ return cast(
767
+ ResponseT,
768
+ self.request(
769
+ cast_to, opts, remaining_retries=0, stream=stream, stream_cls=stream_cls
770
+ ),
771
+ )
772
+
773
+ def get_api_list(
774
+ self,
775
+ path: str,
776
+ *,
777
+ model: Type[object],
778
+ page: Type[SyncPageT],
779
+ body: Body | None = None,
780
+ options: ExtraRequestOptions = {},
781
+ method: str = "get",
782
+ ) -> AsyncPageT:
783
+ opts = RequestOptions.construct(
784
+ method=method, url=path, json_data=body, **options
785
+ )
786
+ return self._request_api_list(model, page, opts)
787
+
788
+ def _request_api_list(
789
+ self,
790
+ model: Type[object],
791
+ page: Type[SyncPageT],
792
+ options: RequestOptions,
793
+ ) -> AsyncPageT:
794
+ def _parser(resp: AsyncPageT) -> SyncPageT:
795
+ resp._set_private_attributes(
796
+ client=self,
797
+ model=model,
798
+ options=options,
799
+ )
800
+ return resp
801
+
802
+ options.post_parser = _parser
803
+ return self.request(page, options, stream=False)
804
+
805
+ def request(
806
+ self,
807
+ cast_to: Type[ResponseT],
808
+ options: RequestOptions,
809
+ remaining_retries: Optional[int] = None,
810
+ *,
811
+ stream: bool = False,
812
+ stream_cls: type[_StreamT] | None = None,
813
+ ) -> ResponseT | _StreamT:
814
+ return self._request(
815
+ cast_to=cast_to,
816
+ options=options,
817
+ stream=stream,
818
+ stream_cls=stream_cls,
819
+ remaining_retries=remaining_retries,
820
+ )
821
+
822
+ def is_closed(self) -> bool:
823
+ return self._client.is_closed
824
+
825
+ def close(self) -> None:
826
+ """Close the underlying HTTPX client.
827
+
828
+ The client will *not* be usable after this.
829
+ """
830
+ # If an error is thrown while constructing a client, self._client
831
+ # may not be present
832
+ if hasattr(self, "_client"):
833
+ self._client.close()
834
+
835
+ def __enter__(self: _T) -> _T:
836
+ return self
837
+
838
+ def __exit__(
839
+ self,
840
+ exc_type: type[BaseException] | None,
841
+ exc: BaseException | None,
842
+ exc_tb: TracebackType | None,
843
+ ) -> None:
844
+ self.close()
845
+
846
+
847
+ class _DefaultAsyncHttpxClient(httpx.AsyncClient):
848
+ def __init__(self, **kwargs: Any) -> None:
849
+ kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
850
+ kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
851
+ kwargs.setdefault("follow_redirects", True)
852
+ super().__init__(**kwargs)
853
+
854
+
855
+ if TYPE_CHECKING:
856
+ DefaultAsyncHttpxClient = httpx.AsyncClient
857
+ """An alias to `httpx.AsyncClient` that provides the same defaults that this SDK
858
+ uses internally.
859
+
860
+ This is useful because overriding the `http_client` with your own instance of
861
+ `httpx.AsyncClient` will result in httpx's defaults being used, not ours.
862
+ """
863
+ else:
864
+ DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient
865
+
866
+
867
+ class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient):
868
+ def __del__(self) -> None:
869
+ try:
870
+ # TODO(someday): support non asyncio runtimes here
871
+ asyncio.get_running_loop().create_task(self.aclose())
872
+ except Exception:
873
+ pass
874
+
875
+
876
+ class AsyncAPIClient(BaseClient):
877
+ _client: httpx.AsyncClient
878
+
879
+ def __init__(
880
+ self,
881
+ *,
882
+ base_url: str | URL,
883
+ max_retries: int = DEFAULT_MAX_RETRIES,
884
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
885
+ http_client: httpx.AsyncClient | None = None,
886
+ custom_headers: Dict[str, str] | None = None,
887
+ custom_query: Dict[str, object] | None = None,
888
+ ) -> None:
889
+ if http_client is not None and not isinstance(http_client, httpx.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance]
890
+ raise TypeError(
891
+ f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}"
892
+ )
893
+
894
+ super().__init__(
895
+ base_url=base_url,
896
+ timeout=cast(Timeout, timeout),
897
+ max_retries=max_retries,
898
+ custom_query=custom_query,
899
+ custom_headers=custom_headers,
900
+ )
901
+
902
+ self._client = http_client or AsyncHttpxClientWrapper(
903
+ base_url=self._enforce_trailing_slash(URL(base_url)),
904
+ timeout=cast(Timeout, timeout),
905
+ )
906
+
907
+ async def post(
908
+ self,
909
+ path: str,
910
+ *,
911
+ cast_to: Type[ResponseT],
912
+ body: Dict | None = None,
913
+ options: ExtraRequestOptions = {},
914
+ files: RequestFiles | None = None,
915
+ stream: bool = False,
916
+ stream_cls: type[_AsyncStreamT] | None = None,
917
+ ) -> ResponseT | _AsyncStreamT:
918
+ opts = RequestOptions.construct(
919
+ method="post",
920
+ url=path,
921
+ body=body,
922
+ files=await async_to_httpx_files(files),
923
+ **options,
924
+ )
925
+
926
+ return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
927
+
928
+ async def get(
929
+ self,
930
+ path: str,
931
+ *,
932
+ cast_to: Type[ResponseT],
933
+ params: list[tuple[str, str]] | None = None,
934
+ options: ExtraRequestOptions = {},
935
+ stream: bool = False,
936
+ stream_cls: type[_AsyncStreamT] | None = None,
937
+ ) -> ResponseT | _AsyncStreamT:
938
+ opts = RequestOptions.construct(
939
+ method="get",
940
+ url=path,
941
+ params=params,
942
+ **options,
943
+ )
944
+
945
+ return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
946
+
947
+ async def delete(
948
+ self,
949
+ path: str,
950
+ *,
951
+ cast_to: Type[ResponseT],
952
+ params: list[tuple[str, str]] | None = None,
953
+ options: ExtraRequestOptions = {},
954
+ ) -> ResponseT:
955
+ opts = RequestOptions.construct(
956
+ method="delete",
957
+ url=path,
958
+ params=params,
959
+ **options,
960
+ )
961
+
962
+ return await self.request(cast_to, opts)
963
+
964
+ async def post_without_retry(
965
+ self,
966
+ path: str,
967
+ *,
968
+ cast_to: Type[ResponseT],
969
+ body: Dict | None = None,
970
+ options: ExtraRequestOptions = {},
971
+ files: RequestFiles | None = None,
972
+ stream: bool = False,
973
+ stream_cls: type[_AsyncStreamT] | None = None,
974
+ ) -> ResponseT | _AsyncStreamT:
975
+ opts = RequestOptions.construct(
976
+ method="post",
977
+ url=path,
978
+ body=body,
979
+ files=files,
980
+ **options,
981
+ )
982
+
983
+ return await self.request(
984
+ cast_to, opts, remaining_retries=0, stream=stream, stream_cls=stream_cls
985
+ )
986
+
987
+ async def get_api_list(
988
+ self,
989
+ path: str,
990
+ *,
991
+ model: Type[object],
992
+ page: Type[AsyncPageT],
993
+ body: Body | None = None,
994
+ options: ExtraRequestOptions = {},
995
+ method: str = "get",
996
+ ) -> AsyncPageT:
997
+ opts = RequestOptions.construct(
998
+ method=method, url=path, json_data=body, **options
999
+ )
1000
+ return await self._request_api_list(model, page, opts)
1001
+
1002
+ async def _request_api_list(
1003
+ self,
1004
+ model: Type[object],
1005
+ page: Type[AsyncPageT],
1006
+ options: RequestOptions,
1007
+ ) -> AsyncPageT:
1008
+ def _parser(resp: AsyncPageT) -> SyncPageT:
1009
+ resp._set_private_attributes(
1010
+ client=self,
1011
+ model=model,
1012
+ options=options,
1013
+ )
1014
+ return resp
1015
+
1016
+ options.post_parser = _parser
1017
+
1018
+ return await self.request(page, options, stream=False)
1019
+
1020
+ async def request(
1021
+ self,
1022
+ cast_to: Type[ResponseT],
1023
+ options: RequestOptions,
1024
+ remaining_retries: Optional[int] = None,
1025
+ *,
1026
+ stream: bool = False,
1027
+ stream_cls: type[_StreamT] | None = None,
1028
+ ) -> ResponseT | _StreamT:
1029
+ return await self._request(
1030
+ cast_to=cast_to,
1031
+ options=options,
1032
+ stream=stream,
1033
+ stream_cls=stream_cls,
1034
+ remaining_retries=remaining_retries,
1035
+ )
1036
+
1037
+ async def _request(
1038
+ self,
1039
+ *,
1040
+ cast_to: Type[ResponseT],
1041
+ options: RequestOptions,
1042
+ remaining_retries: int | None,
1043
+ stream: bool,
1044
+ stream_cls: type[_AsyncStreamT] | None,
1045
+ ) -> ResponseT | _AsyncStreamT:
1046
+ retries = self._remaining_retries(remaining_retries, options)
1047
+ request = self._build_request(options)
1048
+ req_id = request.headers.get(CLIENT_REQUEST_HEADER, "")
1049
+ try:
1050
+ response = await self._client.send(
1051
+ request,
1052
+ stream=stream or self._should_stream_response_body(request=request),
1053
+ )
1054
+ except httpx.TimeoutException as err:
1055
+ if retries > 0:
1056
+ return await self._retry_request(
1057
+ options,
1058
+ cast_to,
1059
+ retries,
1060
+ stream=stream,
1061
+ stream_cls=stream_cls,
1062
+ response_headers=None,
1063
+ )
1064
+
1065
+ log.debug("Raising timeout error")
1066
+ raise ArkAPITimeoutError(request=request, request_id=req_id) from err
1067
+ except Exception as err:
1068
+ log.debug("Encountered Exception", exc_info=True)
1069
+
1070
+ if retries > 0:
1071
+ return await self._retry_request(
1072
+ options,
1073
+ cast_to,
1074
+ retries,
1075
+ stream=stream,
1076
+ stream_cls=stream_cls,
1077
+ response_headers=None,
1078
+ )
1079
+
1080
+ log.debug("Raising connection error")
1081
+ raise ArkAPIConnectionError(request=request, request_id=req_id) from err
1082
+
1083
+ log.debug(
1084
+ 'HTTP Request: %s %s "%i %s"',
1085
+ request.method,
1086
+ request.url,
1087
+ response.status_code,
1088
+ response.reason_phrase,
1089
+ )
1090
+
1091
+ try:
1092
+ response.raise_for_status()
1093
+ except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code
1094
+ log.debug("Encountered httpx.HTTPStatusError", exc_info=True)
1095
+
1096
+ if retries > 0 and self._should_retry(err.response):
1097
+ await err.response.aclose()
1098
+ return await self._retry_request(
1099
+ options,
1100
+ cast_to,
1101
+ retries,
1102
+ err.response.headers,
1103
+ stream=stream,
1104
+ stream_cls=stream_cls,
1105
+ )
1106
+
1107
+ # If the response is streamed then we need to explicitly read the response
1108
+ # to completion before attempting to access the response text.
1109
+ if not err.response.is_closed:
1110
+ await err.response.aread()
1111
+
1112
+ log.debug("Re-raising status error")
1113
+ raise self._make_status_error_from_response(
1114
+ err.response, request_id=req_id
1115
+ ) from None
1116
+
1117
+ return await self._process_response(
1118
+ cast_to=cast_to,
1119
+ response=response,
1120
+ stream=stream,
1121
+ stream_cls=stream_cls,
1122
+ options=options,
1123
+ )
1124
+
1125
+ async def _retry_request(
1126
+ self,
1127
+ options: RequestOptions,
1128
+ cast_to: Type[ResponseT],
1129
+ remaining_retries: int,
1130
+ response_headers: httpx.Headers | None,
1131
+ *,
1132
+ stream: bool,
1133
+ stream_cls: type[_AsyncStreamT] | None,
1134
+ ) -> ResponseT | _AsyncStreamT:
1135
+ remaining = remaining_retries - 1
1136
+ if remaining == 1:
1137
+ log.debug("1 retry left")
1138
+ else:
1139
+ log.debug("%i retries left", remaining)
1140
+
1141
+ timeout = self._calculate_retry_timeout(remaining, options, response_headers)
1142
+ log.info("Retrying request to %s in %f seconds", options.url, timeout)
1143
+
1144
+ await anyio.sleep(timeout)
1145
+
1146
+ return await self._request(
1147
+ options=options,
1148
+ cast_to=cast_to,
1149
+ remaining_retries=remaining,
1150
+ stream=stream,
1151
+ stream_cls=stream_cls,
1152
+ )
1153
+
1154
+ async def _process_response(
1155
+ self,
1156
+ *,
1157
+ cast_to: Type[ResponseT],
1158
+ options: RequestOptions,
1159
+ response: httpx.Response,
1160
+ stream: bool,
1161
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
1162
+ ) -> ResponseT:
1163
+ if cast_to == httpx.Response:
1164
+ return cast(ResponseT, response)
1165
+
1166
+ api_response = ArkAsyncAPIResponse(
1167
+ raw=response,
1168
+ client=self,
1169
+ cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
1170
+ stream=stream,
1171
+ stream_cls=stream_cls,
1172
+ options=options,
1173
+ )
1174
+ if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
1175
+ return cast(ResponseT, api_response)
1176
+
1177
+ return await api_response.parse()
1178
+
1179
+ def is_closed(self) -> bool:
1180
+ return self._client.is_closed
1181
+
1182
+ async def close(self) -> None:
1183
+ """Close the underlying HTTPX client.
1184
+
1185
+ The client will *not* be usable after this.
1186
+ """
1187
+ await self._client.aclose()
1188
+
1189
+ async def __aenter__(self: _T) -> _T:
1190
+ return self
1191
+
1192
+ async def __aexit__(
1193
+ self,
1194
+ exc_type: type[BaseException] | None,
1195
+ exc: BaseException | None,
1196
+ exc_tb: TracebackType | None,
1197
+ ) -> None:
1198
+ await self.close()
1199
+
1200
+
1201
+ class PageInfo:
1202
+ """Stores the necessary information to build the request to retrieve the next page.
1203
+
1204
+ Either `url` or `params` must be set.
1205
+ """
1206
+
1207
+ url: URL | NotGiven
1208
+ params: Query | NotGiven
1209
+ json: Body | NotGiven
1210
+
1211
+ def __init__(
1212
+ self,
1213
+ *,
1214
+ url: URL | NotGiven = NOT_GIVEN,
1215
+ json: Body | NotGiven = NOT_GIVEN,
1216
+ params: Query | NotGiven = NOT_GIVEN,
1217
+ ) -> None:
1218
+ self.url = url
1219
+ self.json = json
1220
+ self.params = params
1221
+
1222
+ @override
1223
+ def __repr__(self) -> str:
1224
+ if self.url:
1225
+ return f"{self.__class__.__name__}(url={self.url})"
1226
+ if self.json:
1227
+ return f"{self.__class__.__name__}(json={self.json})"
1228
+ return f"{self.__class__.__name__}(params={self.params})"
1229
+
1230
+
1231
+ class BasePage(GenericModel, Generic[_T]):
1232
+ """
1233
+ Defines the core interface for pagination.
1234
+
1235
+ Type Args:
1236
+ ModelT: The pydantic model that represents an item in the response.
1237
+
1238
+ Methods:
1239
+ has_next_page(): Check if there is another page available
1240
+ next_page_info(): Get the necessary information to make a request for the next page
1241
+ """
1242
+
1243
+ _options: RequestOptions = PrivateAttr()
1244
+ _model: Type[_T] = PrivateAttr()
1245
+
1246
+ def has_next_page(self) -> bool:
1247
+ items = self._get_page_items()
1248
+ if not items:
1249
+ return False
1250
+ return self.next_page_info() is not None
1251
+
1252
+ def next_page_info(self) -> Optional[PageInfo]: ...
1253
+
1254
+ def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body]
1255
+ ...
1256
+
1257
+ def _params_from_url(self, url: URL) -> httpx.QueryParams:
1258
+ # TODO: do we have to preprocess params here?
1259
+ return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params)
1260
+
1261
+ def _info_to_options(self, info: PageInfo) -> RequestOptions:
1262
+ options = model_copy(self._options)
1263
+ options._strip_raw_response_header()
1264
+
1265
+ if not isinstance(info.params, NotGiven):
1266
+ options.params = {**options.params, **info.params}
1267
+ return options
1268
+
1269
+ if not isinstance(info.url, NotGiven):
1270
+ params = self._params_from_url(info.url)
1271
+ url = info.url.copy_with(params=params)
1272
+ options.params = dict(url.params)
1273
+ options.url = str(url)
1274
+ return options
1275
+
1276
+ if not isinstance(info.json, NotGiven):
1277
+ if not is_mapping(info.json):
1278
+ raise TypeError("Pagination is only supported with mappings")
1279
+
1280
+ if not options.json_data:
1281
+ options.json_data = {**info.json}
1282
+ else:
1283
+ if not is_mapping(options.json_data):
1284
+ raise TypeError("Pagination is only supported with mappings")
1285
+
1286
+ options.json_data = {**options.json_data, **info.json}
1287
+ return options
1288
+
1289
+ raise ValueError("Unexpected PageInfo state")
1290
+
1291
+
1292
+ class BaseSyncPage(BasePage[_T], Generic[_T]):
1293
+ _client: SyncAPIClient = pydantic.PrivateAttr()
1294
+
1295
+ def _set_private_attributes(
1296
+ self,
1297
+ client: SyncAPIClient,
1298
+ model: Type[_T],
1299
+ options: RequestOptions,
1300
+ ) -> None:
1301
+ if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None:
1302
+ self.__pydantic_private__ = {}
1303
+
1304
+ self._model = model
1305
+ self._client = client
1306
+ self._options = options
1307
+
1308
+ # Pydantic uses a custom `__iter__` method to support casting BaseModels
1309
+ # to dictionaries. e.g. dict(model).
1310
+ # As we want to support `for item in page`, this is inherently incompatible
1311
+ # with the default pydantic behaviour. It is not possible to support both
1312
+ # use cases at once. Fortunately, this is not a big deal as all other pydantic
1313
+ # methods should continue to work as expected as there is an alternative method
1314
+ # to cast a model to a dictionary, model.dict(), which is used internally
1315
+ # by pydantic.
1316
+ def __iter__(self) -> Iterator[_T]: # type: ignore
1317
+ for page in self.iter_pages():
1318
+ for item in page._get_page_items():
1319
+ yield item
1320
+
1321
+ def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]:
1322
+ page = self
1323
+ while True:
1324
+ yield page
1325
+ if page.has_next_page():
1326
+ page = page.get_next_page()
1327
+ else:
1328
+ return
1329
+
1330
+ def get_next_page(self: SyncPageT) -> SyncPageT:
1331
+ info = self.next_page_info()
1332
+ if not info:
1333
+ raise RuntimeError(
1334
+ "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
1335
+ )
1336
+
1337
+ options = self._info_to_options(info)
1338
+ return self._client._request_api_list(
1339
+ self._model, page=self.__class__, options=options
1340
+ )
1341
+
1342
+
1343
+ class AsyncPaginator(Generic[_T, AsyncPageT]):
1344
+ def __init__(
1345
+ self,
1346
+ client: AsyncAPIClient,
1347
+ options: RequestOptions,
1348
+ page_cls: Type[AsyncPageT],
1349
+ model: Type[_T],
1350
+ ) -> None:
1351
+ self._model = model
1352
+ self._client = client
1353
+ self._options = options
1354
+ self._page_cls = page_cls
1355
+
1356
+ def __await__(self) -> Generator[Any, None, AsyncPageT]:
1357
+ return self._get_page().__await__()
1358
+
1359
+ async def _get_page(self) -> AsyncPageT:
1360
+ def _parser(resp: AsyncPageT) -> AsyncPageT:
1361
+ resp._set_private_attributes(
1362
+ model=self._model,
1363
+ options=self._options,
1364
+ client=self._client,
1365
+ )
1366
+ return resp
1367
+
1368
+ self._options.post_parser = _parser
1369
+
1370
+ return await self._client.request(self._page_cls, self._options)
1371
+
1372
+ async def __aiter__(self) -> AsyncIterator[_T]:
1373
+ # https://github.com/microsoft/pyright/issues/3464
1374
+ page = cast(
1375
+ AsyncPageT,
1376
+ await self, # type: ignore
1377
+ )
1378
+ async for item in page:
1379
+ yield item
1380
+
1381
+
1382
+ class BaseAsyncPage(BasePage[_T], Generic[_T]):
1383
+ _client: AsyncAPIClient = pydantic.PrivateAttr()
1384
+
1385
+ def _set_private_attributes(
1386
+ self,
1387
+ model: Type[_T],
1388
+ client: AsyncAPIClient,
1389
+ options: RequestOptions,
1390
+ ) -> None:
1391
+ if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None:
1392
+ self.__pydantic_private__ = {}
1393
+
1394
+ self._model = model
1395
+ self._client = client
1396
+ self._options = options
1397
+
1398
+ async def __aiter__(self) -> AsyncIterator[_T]:
1399
+ async for page in self.iter_pages():
1400
+ for item in page._get_page_items():
1401
+ yield item
1402
+
1403
+ async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]:
1404
+ page = self
1405
+ while True:
1406
+ yield page
1407
+ if page.has_next_page():
1408
+ page = await page.get_next_page()
1409
+ else:
1410
+ return
1411
+
1412
+ async def get_next_page(self: AsyncPageT) -> AsyncPageT:
1413
+ info = self.next_page_info()
1414
+ if not info:
1415
+ raise RuntimeError(
1416
+ "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
1417
+ )
1418
+
1419
+ options = self._info_to_options(info)
1420
+ return await self._client._request_api_list(
1421
+ self._model, page=self.__class__, options=options
1422
+ )
1423
+
1424
+
1425
+ class ForceMultipartDict(Dict[str, None]):
1426
+ def __bool__(self) -> bool:
1427
+ return True
1428
+
1429
+
1430
+ def _merge_mappings(
1431
+ obj1: Mapping[_T_co, Union[_T, None]],
1432
+ obj2: Mapping[_T_co, Union[_T, None]],
1433
+ ) -> Dict[_T_co, _T]:
1434
+ """Merge two mappings of the same type, removing any values that are instances of `Omit`.
1435
+
1436
+ In cases with duplicate keys the second mapping takes precedence.
1437
+ """
1438
+ merged = {**obj1, **obj2}
1439
+ return {key: value for key, value in merged.items() if value is not None}