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,615 @@
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import functools
5
+ import inspect
6
+ import logging
7
+ import pydantic
8
+ from types import TracebackType
9
+ from typing import (
10
+ Any,
11
+ Union,
12
+ Generic,
13
+ TypeVar,
14
+ Iterator,
15
+ AsyncIterator,
16
+ cast,
17
+ Callable,
18
+ Awaitable,
19
+ TYPE_CHECKING,
20
+ overload,
21
+ )
22
+
23
+ import httpx
24
+ from typing_extensions import ParamSpec, override, get_origin
25
+ from ._types import NoneType
26
+ from ._constants import CLIENT_REQUEST_HEADER, RAW_RESPONSE_HEADER # type: ignore
27
+ from ._exceptions import ArkError
28
+ from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type
29
+ from ._streaming import (
30
+ Stream,
31
+ AsyncStream,
32
+ is_stream_class_type,
33
+ extract_stream_chunk_type,
34
+ )
35
+ from ._models import BaseModel, is_basemodel, add_request_id
36
+
37
+ if TYPE_CHECKING:
38
+ from ._request_options import RequestOptions
39
+ from ._base_client import BaseClient
40
+
41
+ P = ParamSpec("P")
42
+ R = TypeVar("R")
43
+ _T = TypeVar("_T")
44
+ _APIResponseT = TypeVar("_APIResponseT", bound="ArkAPIResponse[Any]")
45
+ _AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="ArkAsyncAPIResponse[Any]")
46
+ _DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]])
47
+
48
+ log: logging.Logger = logging.getLogger(__name__)
49
+
50
+
51
+ class BaseAPIResponse(Generic[R]):
52
+ _cast_to: type[R]
53
+ _client: BaseClient
54
+ _parsed_by_type: dict[type[Any], Any]
55
+ _is_sse_stream: bool
56
+ _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None
57
+ _request_id: str
58
+ _options: RequestOptions
59
+
60
+ http_response: httpx.Response
61
+
62
+ def __init__(
63
+ self,
64
+ *,
65
+ raw: httpx.Response,
66
+ cast_to: type[R],
67
+ client: BaseClient,
68
+ stream: bool,
69
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
70
+ options: RequestOptions,
71
+ ) -> None:
72
+ self._cast_to = cast_to
73
+ self._client = client
74
+ self._parsed_by_type = {}
75
+ self._is_sse_stream = stream
76
+ self._stream_cls = stream_cls
77
+ self.http_response = raw
78
+ self._options = options
79
+
80
+ @property
81
+ def request_id(self) -> str:
82
+ return self.http_response.headers.get(CLIENT_REQUEST_HEADER)
83
+
84
+ @property
85
+ def headers(self) -> httpx.Headers:
86
+ return self.http_response.headers
87
+
88
+ @property
89
+ def http_request(self) -> httpx.Request:
90
+ return self.http_response.request
91
+
92
+ @property
93
+ def status_code(self) -> int:
94
+ return self.http_response.status_code
95
+
96
+ @property
97
+ def url(self) -> httpx.URL:
98
+ return self.http_response.url
99
+
100
+ @property
101
+ def method(self) -> str:
102
+ return self.http_request.method
103
+
104
+ @property
105
+ def http_version(self) -> str:
106
+ return self.http_response.http_version
107
+
108
+ @property
109
+ def elapsed(self) -> datetime.timedelta:
110
+ return self.http_response.elapsed
111
+
112
+ @property
113
+ def is_closed(self) -> bool:
114
+ return self.http_response.is_closed
115
+
116
+ @override
117
+ def __repr__(self) -> str:
118
+ return f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>"
119
+
120
+ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
121
+ cast_to = to if to is not None else self._cast_to
122
+
123
+ # unwrap `TypeAlias('Name', T)` -> `T`
124
+ if is_type_alias_type(cast_to):
125
+ cast_to = cast_to.__value__ # type: ignore[unreachable]
126
+
127
+ # unwrap `Annotated[T, ...]` -> `T`
128
+ if cast_to and is_annotated_type(cast_to):
129
+ cast_to = extract_type_arg(cast_to, 0)
130
+
131
+ origin = get_origin(cast_to) or cast_to
132
+
133
+ if self._is_sse_stream:
134
+ if to:
135
+ if not is_stream_class_type(to):
136
+ raise TypeError(
137
+ f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}"
138
+ )
139
+
140
+ return cast(
141
+ _T,
142
+ to(
143
+ cast_to=extract_stream_chunk_type(
144
+ to,
145
+ failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]",
146
+ ),
147
+ response=self.http_response,
148
+ client=cast(Any, self._client),
149
+ ),
150
+ )
151
+
152
+ if self._stream_cls:
153
+ return cast(
154
+ R,
155
+ self._stream_cls(
156
+ cast_to=extract_stream_chunk_type(self._stream_cls),
157
+ response=self.http_response,
158
+ client=cast(Any, self._client),
159
+ ),
160
+ )
161
+
162
+ stream_cls = cast(
163
+ "type[Stream[Any]] | type[AsyncStream[Any]] | None",
164
+ self._client._default_stream_cls,
165
+ )
166
+ if stream_cls is None:
167
+ raise MissingStreamClassError()
168
+
169
+ return cast(
170
+ R,
171
+ stream_cls(
172
+ cast_to=cast_to,
173
+ response=self.http_response,
174
+ client=cast(Any, self._client),
175
+ ),
176
+ )
177
+
178
+ if cast_to is NoneType:
179
+ return cast(R, None)
180
+
181
+ response = self.http_response
182
+ if cast_to == str:
183
+ return cast(R, response.text)
184
+
185
+ if cast_to == bytes:
186
+ return cast(R, response.content)
187
+
188
+ if cast_to == int:
189
+ return cast(R, int(response.text))
190
+
191
+ if cast_to == float:
192
+ return cast(R, float(response.text))
193
+
194
+ if cast_to == bool:
195
+ return cast(R, response.text.lower() == "true")
196
+
197
+ # handle the legacy binary response case
198
+ if (
199
+ inspect.isclass(cast_to)
200
+ and cast_to.__name__ == "HttpxBinaryResponseContent"
201
+ ):
202
+ return cast(R, cast_to(response)) # type: ignore
203
+
204
+ if origin == ArkAPIResponse:
205
+ raise RuntimeError("Unexpected state - cast_to is `APIResponse`")
206
+
207
+ if inspect.isclass(origin) and issubclass(origin, httpx.Response):
208
+ # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
209
+ # and pass that class to our request functions. We cannot change the variance to be either
210
+ # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
211
+ # the response class ourselves but that is something that should be supported directly in httpx
212
+ # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
213
+ if cast_to != httpx.Response:
214
+ raise ValueError(
215
+ "Subclasses of httpx.Response cannot be passed to `cast_to`"
216
+ )
217
+ return cast(R, response)
218
+
219
+ if (
220
+ inspect.isclass(origin) # pyright: ignore[reportUnknownArgumentType]
221
+ and not issubclass(origin, BaseModel)
222
+ and issubclass(origin, pydantic.BaseModel)
223
+ ):
224
+ raise TypeError("Pydantic models must subclass our base model type")
225
+
226
+ if (
227
+ cast_to is not object
228
+ and origin is not list
229
+ and origin is not dict
230
+ and origin is not Union
231
+ and not issubclass(origin, BaseModel)
232
+ ):
233
+ raise RuntimeError(
234
+ f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
235
+ )
236
+
237
+ # split is required to handle cases where additional information is included
238
+ # in the response, e.g. application/json; charset=utf-8
239
+ content_type, *_ = response.headers.get("content-type", "*").split(";")
240
+ if content_type != "application/json":
241
+ if is_basemodel(cast_to):
242
+ try:
243
+ data = response.json()
244
+ except Exception as exc:
245
+ log.debug(
246
+ "Could not read JSON from response data due to %s - %s",
247
+ type(exc),
248
+ exc,
249
+ )
250
+ else:
251
+ return self._client._process_response_data(
252
+ data=data,
253
+ cast_to=cast_to, # type: ignore
254
+ response=response,
255
+ )
256
+
257
+ # If the API responds with content that isn't JSON then we just return
258
+ # the (decoded) text without performing any parsing so that you can still
259
+ # handle the response however you need to.
260
+ return response.text # type: ignore
261
+
262
+ data = response.json()
263
+
264
+ return self._client._process_response_data(
265
+ data=data,
266
+ cast_to=cast_to, # type: ignore
267
+ response=response,
268
+ )
269
+
270
+
271
+ class ArkAPIResponse(BaseAPIResponse[R]):
272
+ @property
273
+ def request_id(self) -> str:
274
+ return self.http_response.headers.get(CLIENT_REQUEST_HEADER, "")
275
+
276
+ def parse(self, *, to: type[_T] | None = None) -> R | _T:
277
+ """Returns the rich python representation of this response's data.
278
+
279
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
280
+
281
+ You can customise the type that the response is parsed into through
282
+ the `to` argument, e.g.
283
+
284
+ ```py
285
+ class MyModel(BaseModel):
286
+ foo: str
287
+
288
+
289
+ obj = response.parse(to=MyModel)
290
+ print(obj.foo)
291
+ ```
292
+
293
+ We support parsing:
294
+ - `BaseModel`
295
+ - `dict`
296
+ - `list`
297
+ - `Union`
298
+ - `str`
299
+ - `int`
300
+ - `float`
301
+ - `httpx.Response`
302
+ """
303
+ cache_key = to if to is not None else self._cast_to
304
+ cached = self._parsed_by_type.get(cache_key)
305
+ if cached is not None:
306
+ return cached # type: ignore[no-any-return]
307
+
308
+ if not self._is_sse_stream:
309
+ self.read()
310
+
311
+ parsed = self._parse(to=to)
312
+ if is_given(self._options.post_parser):
313
+ parsed = self._options.post_parser(parsed)
314
+
315
+ if isinstance(parsed, BaseModel):
316
+ add_request_id(parsed, self.request_id)
317
+
318
+ self._parsed_by_type[cache_key] = parsed
319
+ return cast(R, parsed)
320
+
321
+ def read(self) -> bytes:
322
+ try:
323
+ return self.http_response.read()
324
+ except httpx.StreamConsumed as exc:
325
+ raise StreamAlreadyConsumed() from exc
326
+
327
+ def text(self) -> str:
328
+ self.read()
329
+ return self.http_response.text
330
+
331
+ def json(self) -> object:
332
+ self.read()
333
+ return self.http_response.json()
334
+
335
+ def close(self) -> None:
336
+ self.http_response.close()
337
+
338
+ def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
339
+ for chunk in self.http_response.iter_bytes(chunk_size):
340
+ yield chunk
341
+
342
+ def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
343
+ for chunk in self.http_response.iter_text(chunk_size):
344
+ yield chunk
345
+
346
+ def iter_lines(self) -> Iterator[str]:
347
+ for chunk in self.http_response.iter_lines():
348
+ yield chunk
349
+
350
+
351
+ class ArkAsyncAPIResponse(BaseAPIResponse[R]):
352
+ @property
353
+ def request_id(self) -> str:
354
+ return self.http_response.headers.get(CLIENT_REQUEST_HEADER, "")
355
+
356
+ @overload
357
+ async def parse(self, *, to: type[_T]) -> _T: ...
358
+
359
+ @overload
360
+ async def parse(self) -> R: ...
361
+
362
+ async def parse(self, *, to: type[_T] | None = None) -> R | _T:
363
+ """Returns the rich python representation of this response's data.
364
+
365
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
366
+
367
+ You can customise the type that the response is parsed into through
368
+ the `to` argument, e.g.
369
+
370
+ ```py
371
+ class MyModel(BaseModel):
372
+ foo: str
373
+
374
+
375
+ obj = response.parse(to=MyModel)
376
+ print(obj.foo)
377
+ ```
378
+
379
+ We support parsing:
380
+ - `BaseModel`
381
+ - `dict`
382
+ - `list`
383
+ - `Union`
384
+ - `str`
385
+ - `httpx.Response`
386
+ """
387
+ cache_key = to if to is not None else self._cast_to
388
+ cached = self._parsed_by_type.get(cache_key)
389
+ if cached is not None:
390
+ return cached # type: ignore[no-any-return]
391
+
392
+ if not self._is_sse_stream:
393
+ await self.read()
394
+
395
+ parsed = self._parse(to=to)
396
+ if is_given(self._options.post_parser):
397
+ parsed = self._options.post_parser(parsed)
398
+
399
+ if isinstance(parsed, BaseModel):
400
+ add_request_id(parsed, self.request_id)
401
+
402
+ self._parsed_by_type[cache_key] = parsed
403
+ return cast(R, parsed)
404
+
405
+ async def read(self) -> bytes:
406
+ """Read and return the binary response content."""
407
+ try:
408
+ return await self.http_response.aread()
409
+ except httpx.StreamConsumed as exc:
410
+ # the default error raised by httpx isn't very
411
+ # helpful in our case so we re-raise it with
412
+ # a different error message
413
+ raise StreamAlreadyConsumed() from exc
414
+
415
+ async def text(self) -> str:
416
+ """Read and decode the response content into a string."""
417
+ await self.read()
418
+ return self.http_response.text
419
+
420
+ async def json(self) -> object:
421
+ """Read and decode the JSON response content."""
422
+ await self.read()
423
+ return self.http_response.json()
424
+
425
+ async def close(self) -> None:
426
+ """Close the response and release the connection.
427
+
428
+ Automatically called if the response body is read to completion.
429
+ """
430
+ await self.http_response.aclose()
431
+
432
+ async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
433
+ """
434
+ A byte-iterator over the decoded response content.
435
+
436
+ This automatically handles gzip, deflate and brotli encoded responses.
437
+ """
438
+ async for chunk in self.http_response.aiter_bytes(chunk_size):
439
+ yield chunk
440
+
441
+ async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
442
+ """A str-iterator over the decoded response content
443
+ that handles both gzip, deflate, etc but also detects the content's
444
+ string encoding.
445
+ """
446
+ async for chunk in self.http_response.aiter_text(chunk_size):
447
+ yield chunk
448
+
449
+ async def iter_lines(self) -> AsyncIterator[str]:
450
+ """Like `iter_text()` but will only yield chunks for each line"""
451
+ async for chunk in self.http_response.aiter_lines():
452
+ yield chunk
453
+
454
+
455
+ class MissingStreamClassError(TypeError):
456
+ def __init__(self) -> None:
457
+ super().__init__(
458
+ "The `stream` argument was set to `True` but the `stream_cls` argument was not given."
459
+ )
460
+
461
+
462
+ class StreamAlreadyConsumed(ArkError):
463
+ def __init__(self) -> None:
464
+ message = (
465
+ "Attempted to read or stream some content, but the content has "
466
+ "already been streamed. "
467
+ "This could be due to attempting to stream the response "
468
+ "content more than once."
469
+ "\n\n"
470
+ "You can fix this by manually accumulating the response content while streaming "
471
+ "or by calling `.read()` before starting to stream."
472
+ )
473
+ super().__init__(message)
474
+
475
+
476
+ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, ArkAPIResponse[R]]:
477
+ """Higher order function that takes one of our bound API methods and wraps it
478
+ to support returning the raw `APIResponse` object directly.
479
+ """
480
+
481
+ @functools.wraps(func)
482
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ArkAPIResponse[R]:
483
+ extra_headers: dict[str, str] = {
484
+ **(cast(Any, kwargs.get("extra_headers")) or {})
485
+ }
486
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
487
+
488
+ kwargs["extra_headers"] = extra_headers
489
+
490
+ return cast(ArkAPIResponse[R], func(*args, **kwargs))
491
+
492
+ return wrapped
493
+
494
+
495
+ def async_to_raw_response_wrapper(
496
+ func: Callable[P, Awaitable[R]],
497
+ ) -> Callable[P, Awaitable[ArkAsyncAPIResponse[R]]]:
498
+ """Higher order function that takes one of our bound API methods and wraps it
499
+ to support returning the raw `APIResponse` object directly.
500
+ """
501
+
502
+ @functools.wraps(func)
503
+ async def wrapped(*args: P.args, **kwargs: P.kwargs) -> ArkAsyncAPIResponse[R]:
504
+ extra_headers: dict[str, str] = {
505
+ **(cast(Any, kwargs.get("extra_headers")) or {})
506
+ }
507
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
508
+
509
+ kwargs["extra_headers"] = extra_headers
510
+
511
+ return cast(ArkAsyncAPIResponse[R], await func(*args, **kwargs))
512
+
513
+ return wrapped
514
+
515
+
516
+ def to_streamed_response_wrapper(
517
+ func: Callable[P, R],
518
+ ) -> Callable[P, ResponseContextManager[ArkAPIResponse[R]]]:
519
+ """Higher order function that takes one of our bound API methods and wraps it
520
+ to support streaming and returning the raw `APIResponse` object directly.
521
+ """
522
+
523
+ @functools.wraps(func)
524
+ def wrapped(
525
+ *args: P.args, **kwargs: P.kwargs
526
+ ) -> ResponseContextManager[ArkAPIResponse[R]]:
527
+ extra_headers: dict[str, str] = {
528
+ **(cast(Any, kwargs.get("extra_headers")) or {})
529
+ }
530
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
531
+
532
+ kwargs["extra_headers"] = extra_headers
533
+
534
+ make_request = functools.partial(func, *args, **kwargs)
535
+
536
+ return ResponseContextManager(
537
+ cast(Callable[[], ArkAPIResponse[R]], make_request)
538
+ )
539
+
540
+ return wrapped
541
+
542
+
543
+ def async_to_streamed_response_wrapper(
544
+ func: Callable[P, Awaitable[R]],
545
+ ) -> Callable[P, AsyncResponseContextManager[ArkAsyncAPIResponse[R]]]:
546
+ """Higher order function that takes one of our bound API methods and wraps it
547
+ to support streaming and returning the raw `APIResponse` object directly.
548
+ """
549
+
550
+ @functools.wraps(func)
551
+ def wrapped(
552
+ *args: P.args, **kwargs: P.kwargs
553
+ ) -> AsyncResponseContextManager[ArkAsyncAPIResponse[R]]:
554
+ extra_headers: dict[str, str] = {
555
+ **(cast(Any, kwargs.get("extra_headers")) or {})
556
+ }
557
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
558
+
559
+ kwargs["extra_headers"] = extra_headers
560
+
561
+ make_request = func(*args, **kwargs)
562
+
563
+ return AsyncResponseContextManager(
564
+ cast(Awaitable[ArkAsyncAPIResponse[R]], make_request)
565
+ )
566
+
567
+ return wrapped
568
+
569
+
570
+ class ResponseContextManager(Generic[_APIResponseT]):
571
+ """Context manager for ensuring that a request is not made
572
+ until it is entered and that the response will always be closed
573
+ when the context manager exits
574
+ """
575
+
576
+ def __init__(self, request_func: Callable[[], _APIResponseT]) -> None:
577
+ self._request_func = request_func
578
+ self.__response: _APIResponseT | None = None
579
+
580
+ def __enter__(self) -> _APIResponseT:
581
+ self.__response = self._request_func()
582
+ return self.__response
583
+
584
+ def __exit__(
585
+ self,
586
+ exc_type: type[BaseException] | None,
587
+ exc: BaseException | None,
588
+ exc_tb: TracebackType | None,
589
+ ) -> None:
590
+ if self.__response is not None:
591
+ self.__response.close()
592
+
593
+
594
+ class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]):
595
+ """Context manager for ensuring that a request is not made
596
+ until it is entered and that the response will always be closed
597
+ when the context manager exits
598
+ """
599
+
600
+ def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None:
601
+ self._api_request = api_request
602
+ self.__response: _AsyncAPIResponseT | None = None
603
+
604
+ async def __aenter__(self) -> _AsyncAPIResponseT:
605
+ self.__response = await self._api_request
606
+ return self.__response
607
+
608
+ async def __aexit__(
609
+ self,
610
+ exc_type: type[BaseException] | None,
611
+ exc: BaseException | None,
612
+ exc_tb: TracebackType | None,
613
+ ) -> None:
614
+ if self.__response is not None:
615
+ await self.__response.close()