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,451 @@
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 os
15
+ import inspect
16
+ import logging
17
+ import datetime
18
+ import functools
19
+ from typing import (
20
+ TYPE_CHECKING,
21
+ Any,
22
+ Union,
23
+ Generic,
24
+ TypeVar,
25
+ Callable,
26
+ Iterator,
27
+ AsyncIterator,
28
+ cast,
29
+ overload,
30
+ )
31
+ from typing_extensions import Awaitable, ParamSpec, override, get_origin
32
+
33
+ import httpx
34
+ import pydantic
35
+
36
+ from ._types import NoneType
37
+ from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type
38
+ from ._models import BaseModel, is_basemodel, add_request_id
39
+ from ._constants import RAW_RESPONSE_HEADER
40
+ from ._streaming import (
41
+ Stream,
42
+ AsyncStream,
43
+ is_stream_class_type,
44
+ extract_stream_chunk_type,
45
+ )
46
+
47
+ if TYPE_CHECKING:
48
+ from ._request_options import RequestOptions
49
+ from ._base_client import BaseClient
50
+
51
+ P = ParamSpec("P")
52
+ R = TypeVar("R")
53
+ _T = TypeVar("_T")
54
+
55
+ log: logging.Logger = logging.getLogger(__name__)
56
+
57
+
58
+ class LegacyAPIResponse(Generic[R]):
59
+ """This is a legacy class as it will be replaced by `APIResponse`
60
+ and `AsyncAPIResponse` in the `_response.py` file in the next major
61
+ release.
62
+
63
+ For the sync client this will mostly be the same with the exception
64
+ of `content` & `text` will be methods instead of properties. In the
65
+ async client, all methods will be async.
66
+
67
+ A migration script will be provided & the migration in general should
68
+ be smooth.
69
+ """
70
+
71
+ _cast_to: type[R]
72
+ _client: BaseClient[Any, Any]
73
+ _parsed_by_type: dict[type[Any], Any]
74
+ _stream: bool
75
+ _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None
76
+ _options: RequestOptions
77
+
78
+ http_response: httpx.Response
79
+
80
+ retries_taken: int
81
+ """The number of retries made. If no retries happened this will be `0`"""
82
+
83
+ def __init__(
84
+ self,
85
+ *,
86
+ raw: httpx.Response,
87
+ cast_to: type[R],
88
+ client: BaseClient[Any, Any],
89
+ stream: bool,
90
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
91
+ options: RequestOptions,
92
+ retries_taken: int = 0,
93
+ ) -> None:
94
+ self._cast_to = cast_to
95
+ self._client = client
96
+ self._parsed_by_type = {}
97
+ self._stream = stream
98
+ self._stream_cls = stream_cls
99
+ self._options = options
100
+ self.http_response = raw
101
+ self.retries_taken = retries_taken
102
+
103
+ @property
104
+ def request_id(self) -> str | None:
105
+ return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return]
106
+
107
+ @overload
108
+ def parse(self, *, to: type[_T]) -> _T: ...
109
+
110
+ @overload
111
+ def parse(self) -> R: ...
112
+
113
+ def parse(self, *, to: type[_T] | None = None) -> R | _T:
114
+ cache_key = to if to is not None else self._cast_to
115
+ cached = self._parsed_by_type.get(cache_key)
116
+ if cached is not None:
117
+ return cached # type: ignore[no-any-return]
118
+
119
+ parsed = self._parse(to=to)
120
+ if is_given(self._options.post_parser):
121
+ parsed = self._options.post_parser(parsed)
122
+
123
+ if isinstance(parsed, BaseModel):
124
+ add_request_id(parsed, self.request_id)
125
+
126
+ self._parsed_by_type[cache_key] = parsed
127
+ return cast(R, parsed)
128
+
129
+ @property
130
+ def headers(self) -> httpx.Headers:
131
+ return self.http_response.headers
132
+
133
+ @property
134
+ def http_request(self) -> httpx.Request:
135
+ return self.http_response.request
136
+
137
+ @property
138
+ def status_code(self) -> int:
139
+ return self.http_response.status_code
140
+
141
+ @property
142
+ def url(self) -> httpx.URL:
143
+ return self.http_response.url
144
+
145
+ @property
146
+ def method(self) -> str:
147
+ return self.http_request.method
148
+
149
+ @property
150
+ def content(self) -> bytes:
151
+ """Return the binary response content.
152
+
153
+ NOTE: this will be removed in favour of `.read()` in the
154
+ next major version.
155
+ """
156
+ return self.http_response.content
157
+
158
+ @property
159
+ def text(self) -> str:
160
+ """Return the decoded response content.
161
+
162
+ NOTE: this will be turned into a method in the next major version.
163
+ """
164
+ return self.http_response.text
165
+
166
+ @property
167
+ def http_version(self) -> str:
168
+ return self.http_response.http_version
169
+
170
+ @property
171
+ def is_closed(self) -> bool:
172
+ return self.http_response.is_closed
173
+
174
+ @property
175
+ def elapsed(self) -> datetime.timedelta:
176
+ """The time taken for the complete request/response cycle to complete."""
177
+ return self.http_response.elapsed
178
+
179
+ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
180
+ cast_to = to if to is not None else self._cast_to
181
+
182
+ # unwrap `TypeAlias('Name', T)` -> `T`
183
+ if is_type_alias_type(cast_to):
184
+ cast_to = cast_to.__value__ # type: ignore[unreachable]
185
+
186
+ # unwrap `Annotated[T, ...]` -> `T`
187
+ if cast_to and is_annotated_type(cast_to):
188
+ cast_to = extract_type_arg(cast_to, 0)
189
+
190
+ origin = get_origin(cast_to) or cast_to
191
+
192
+ if self._stream:
193
+ if to:
194
+ if not is_stream_class_type(to):
195
+ raise TypeError(
196
+ f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}"
197
+ )
198
+
199
+ return cast(
200
+ _T,
201
+ to(
202
+ cast_to=extract_stream_chunk_type(
203
+ to,
204
+ failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]",
205
+ ),
206
+ response=self.http_response,
207
+ client=cast(Any, self._client),
208
+ ),
209
+ )
210
+
211
+ if self._stream_cls:
212
+ return cast(
213
+ R,
214
+ self._stream_cls(
215
+ cast_to=extract_stream_chunk_type(self._stream_cls),
216
+ response=self.http_response,
217
+ client=cast(Any, self._client),
218
+ ),
219
+ )
220
+
221
+ stream_cls = cast(
222
+ "type[Stream[Any]] | type[AsyncStream[Any]] | None",
223
+ self._client._default_stream_cls,
224
+ )
225
+ if stream_cls is None:
226
+ raise MissingStreamClassError()
227
+
228
+ return cast(
229
+ R,
230
+ stream_cls(
231
+ cast_to=cast_to,
232
+ response=self.http_response,
233
+ client=cast(Any, self._client),
234
+ ),
235
+ )
236
+
237
+ if cast_to is NoneType:
238
+ return cast(R, None)
239
+
240
+ response = self.http_response
241
+ if cast_to == str:
242
+ return cast(R, response.text)
243
+
244
+ if cast_to == int:
245
+ return cast(R, int(response.text))
246
+
247
+ if cast_to == float:
248
+ return cast(R, float(response.text))
249
+
250
+ if cast_to == bool:
251
+ return cast(R, response.text.lower() == "true")
252
+
253
+ if inspect.isclass(origin) and issubclass(origin, HttpxBinaryResponseContent):
254
+ return cast(R, cast_to(response)) # type: ignore
255
+
256
+ if origin == LegacyAPIResponse:
257
+ raise RuntimeError("Unexpected state - cast_to is `APIResponse`")
258
+
259
+ if inspect.isclass(
260
+ origin # pyright: ignore[reportUnknownArgumentType]
261
+ ) and issubclass(origin, httpx.Response):
262
+ # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
263
+ # and pass that class to our request functions. We cannot change the variance to be either
264
+ # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
265
+ # the response class ourselves but that is something that should be supported directly in httpx
266
+ # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
267
+ if cast_to != httpx.Response:
268
+ raise ValueError(
269
+ "Subclasses of httpx.Response cannot be passed to `cast_to`"
270
+ )
271
+ return cast(R, response)
272
+
273
+ if (
274
+ inspect.isclass(origin) # pyright: ignore[reportUnknownArgumentType]
275
+ and not issubclass(origin, BaseModel)
276
+ and issubclass(origin, pydantic.BaseModel)
277
+ ):
278
+ raise TypeError("Pydantic models must subclass our base model type.")
279
+
280
+ if (
281
+ cast_to is not object
282
+ and origin is not list
283
+ and origin is not dict
284
+ and origin is not Union
285
+ and not issubclass(origin, BaseModel)
286
+ ):
287
+ raise RuntimeError(
288
+ f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
289
+ )
290
+
291
+ # split is required to handle cases where additional information is included
292
+ # in the response, e.g. application/json; charset=utf-8
293
+ content_type, *_ = response.headers.get("content-type", "*").split(";")
294
+ if content_type != "application/json":
295
+ if is_basemodel(cast_to):
296
+ try:
297
+ data = response.json()
298
+ except Exception as exc:
299
+ log.debug(
300
+ "Could not read JSON from response data due to %s - %s",
301
+ type(exc),
302
+ exc,
303
+ )
304
+ else:
305
+ return self._client._process_response_data(
306
+ data=data,
307
+ cast_to=cast_to, # type: ignore
308
+ response=response,
309
+ )
310
+
311
+ # If the API responds with content that isn't JSON then we just return
312
+ # the (decoded) text without performing any parsing so that you can still
313
+ # handle the response however you need to.
314
+ return response.text # type: ignore
315
+
316
+ data = response.json()
317
+
318
+ return self._client._process_response_data(
319
+ data=data,
320
+ cast_to=cast_to, # type: ignore
321
+ response=response,
322
+ )
323
+
324
+ @override
325
+ def __repr__(self) -> str:
326
+ return f"<APIResponse [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>"
327
+
328
+
329
+ class MissingStreamClassError(TypeError):
330
+ def __init__(self) -> None:
331
+ super().__init__(
332
+ "The `stream` argument was set to `True` but the `stream_cls` argument was not given.",
333
+ )
334
+
335
+
336
+ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyAPIResponse[R]]:
337
+ """Higher order function that takes one of our bound API methods and wraps it
338
+ to support returning the raw `APIResponse` object directly.
339
+ """
340
+
341
+ @functools.wraps(func)
342
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]:
343
+ extra_headers: dict[str, str] = {
344
+ **(cast(Any, kwargs.get("extra_headers")) or {})
345
+ }
346
+ extra_headers[RAW_RESPONSE_HEADER] = "true"
347
+
348
+ kwargs["extra_headers"] = extra_headers
349
+
350
+ return cast(LegacyAPIResponse[R], func(*args, **kwargs))
351
+
352
+ return wrapped
353
+
354
+
355
+ def async_to_raw_response_wrapper(
356
+ func: Callable[P, Awaitable[R]],
357
+ ) -> Callable[P, Awaitable[LegacyAPIResponse[R]]]:
358
+ """Higher order function that takes one of our bound API methods and wraps it
359
+ to support returning the raw `APIResponse` object directly.
360
+ """
361
+
362
+ @functools.wraps(func)
363
+ async def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]:
364
+ extra_headers: dict[str, str] = {
365
+ **(cast(Any, kwargs.get("extra_headers")) or {})
366
+ }
367
+ extra_headers[RAW_RESPONSE_HEADER] = "true"
368
+
369
+ kwargs["extra_headers"] = extra_headers
370
+
371
+ return cast(LegacyAPIResponse[R], await func(*args, **kwargs))
372
+
373
+ return wrapped
374
+
375
+
376
+ class HttpxBinaryResponseContent:
377
+ response: httpx.Response
378
+
379
+ def __init__(self, response: httpx.Response) -> None:
380
+ self.response = response
381
+
382
+ @property
383
+ def content(self) -> bytes:
384
+ return self.response.content
385
+
386
+ @property
387
+ def text(self) -> str:
388
+ return self.response.text
389
+
390
+ @property
391
+ def encoding(self) -> str | None:
392
+ return self.response.encoding
393
+
394
+ @property
395
+ def charset_encoding(self) -> str | None:
396
+ return self.response.charset_encoding
397
+
398
+ def json(self, **kwargs: Any) -> Any:
399
+ return self.response.json(**kwargs)
400
+
401
+ def read(self) -> bytes:
402
+ return self.response.read()
403
+
404
+ def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
405
+ return self.response.iter_bytes(chunk_size)
406
+
407
+ def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
408
+ return self.response.iter_text(chunk_size)
409
+
410
+ def iter_lines(self) -> Iterator[str]:
411
+ return self.response.iter_lines()
412
+
413
+ def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]:
414
+ return self.response.iter_raw(chunk_size)
415
+
416
+ def write_to_file(
417
+ self,
418
+ file: str | os.PathLike[str],
419
+ ) -> None:
420
+ """Write the output to the given file.
421
+
422
+ Accepts a filename or any path-like object, e.g. pathlib.Path
423
+
424
+ Note: if you want to stream the data to the file instead of writing
425
+ all at once then you should use `.with_streaming_response` when making
426
+ the API request, e.g. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')`
427
+ """
428
+ with open(file, mode="wb") as f:
429
+ for data in self.response.iter_bytes():
430
+ f.write(data)
431
+
432
+ def close(self) -> None:
433
+ return self.response.close()
434
+
435
+ async def aread(self) -> bytes:
436
+ return await self.response.aread()
437
+
438
+ async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
439
+ return self.response.aiter_bytes(chunk_size)
440
+
441
+ async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
442
+ return self.response.aiter_text(chunk_size)
443
+
444
+ async def aiter_lines(self) -> AsyncIterator[str]:
445
+ return self.response.aiter_lines()
446
+
447
+ async def aiter_raw(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
448
+ return self.response.aiter_raw(chunk_size)
449
+
450
+ async def aclose(self) -> None:
451
+ return await self.response.aclose()