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,489 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import base64
5
+ import pathlib
6
+ from typing import Any, Mapping, TypeVar, cast
7
+ from datetime import date, datetime
8
+ from typing_extensions import (
9
+ Literal,
10
+ get_args,
11
+ override,
12
+ get_type_hints as _get_type_hints,
13
+ )
14
+
15
+ import anyio
16
+ import pydantic
17
+
18
+ from ._utils import (
19
+ is_list,
20
+ is_given,
21
+ lru_cache,
22
+ is_mapping,
23
+ is_iterable,
24
+ )
25
+ from .._files import is_base64_file_input
26
+ from ._typing import (
27
+ is_list_type,
28
+ is_union_type,
29
+ extract_type_arg,
30
+ is_iterable_type,
31
+ is_required_type,
32
+ is_annotated_type,
33
+ strip_annotated_type,
34
+ )
35
+ from .._compat import get_origin, model_dump, is_typeddict
36
+
37
+ _T = TypeVar("_T")
38
+
39
+ PropertyFormat = Literal["iso8601", "base64", "custom"]
40
+
41
+
42
+ class PropertyInfo:
43
+ """Metadata class to be used in Annotated types to provide information about a given type.
44
+
45
+ For example:
46
+
47
+ class MyParams(TypedDict):
48
+ account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')]
49
+
50
+ This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API.
51
+ """
52
+
53
+ alias: str | None
54
+ format: PropertyFormat | None
55
+ format_template: str | None
56
+ discriminator: str | None
57
+
58
+ def __init__(
59
+ self,
60
+ *,
61
+ alias: str | None = None,
62
+ format: PropertyFormat | None = None,
63
+ format_template: str | None = None,
64
+ discriminator: str | None = None,
65
+ ) -> None:
66
+ self.alias = alias
67
+ self.format = format
68
+ self.format_template = format_template
69
+ self.discriminator = discriminator
70
+
71
+ @override
72
+ def __repr__(self) -> str:
73
+ return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')"
74
+
75
+
76
+ def maybe_transform(
77
+ data: object,
78
+ expected_type: object,
79
+ ) -> Any | None:
80
+ """Wrapper over `transform()` that allows `None` to be passed.
81
+
82
+ See `transform()` for more details.
83
+ """
84
+ if data is None:
85
+ return None
86
+ return transform(data, expected_type)
87
+
88
+
89
+ # Wrapper over _transform_recursive providing fake types
90
+ def transform(
91
+ data: _T,
92
+ expected_type: object,
93
+ ) -> _T:
94
+ """Transform dictionaries based off of type information from the given type, for example:
95
+
96
+ ```py
97
+ class Params(TypedDict, total=False):
98
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
99
+
100
+
101
+ transformed = transform({"card_id": "<my card ID>"}, Params)
102
+ # {'cardID': '<my card ID>'}
103
+ ```
104
+
105
+ Any keys / data that does not have type information given will be included as is.
106
+
107
+ It should be noted that the transformations that this function does are not represented in the type system.
108
+ """
109
+ transformed = _transform_recursive(data, annotation=cast(type, expected_type))
110
+ return cast(_T, transformed)
111
+
112
+
113
+ @lru_cache(maxsize=8096)
114
+ def _get_annotated_type(type_: type) -> type | None:
115
+ """If the given type is an `Annotated` type then it is returned, if not `None` is returned.
116
+
117
+ This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]`
118
+ """
119
+ if is_required_type(type_):
120
+ # Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]`
121
+ type_ = get_args(type_)[0]
122
+
123
+ if is_annotated_type(type_):
124
+ return type_
125
+
126
+ return None
127
+
128
+
129
+ def _maybe_transform_key(key: str, type_: type) -> str:
130
+ """Transform the given `data` based on the annotations provided in `type_`.
131
+
132
+ Note: this function only looks at `Annotated` types that contain `PropertyInfo` metadata.
133
+ """
134
+ annotated_type = _get_annotated_type(type_)
135
+ if annotated_type is None:
136
+ # no `Annotated` definition for this type, no transformation needed
137
+ return key
138
+
139
+ # ignore the first argument as it is the actual type
140
+ annotations = get_args(annotated_type)[1:]
141
+ for annotation in annotations:
142
+ if isinstance(annotation, PropertyInfo) and annotation.alias is not None:
143
+ return annotation.alias
144
+
145
+ return key
146
+
147
+
148
+ def _no_transform_needed(annotation: type) -> bool:
149
+ return annotation == float or annotation == int
150
+
151
+
152
+ def _transform_recursive(
153
+ data: object,
154
+ *,
155
+ annotation: type,
156
+ inner_type: type | None = None,
157
+ ) -> object:
158
+ """Transform the given data against the expected type.
159
+
160
+ Args:
161
+ annotation: The direct type annotation given to the particular piece of data.
162
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
163
+
164
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
165
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
166
+ the list can be transformed using the metadata from the container type.
167
+
168
+ Defaults to the same value as the `annotation` argument.
169
+ """
170
+ if inner_type is None:
171
+ inner_type = annotation
172
+
173
+ stripped_type = strip_annotated_type(inner_type)
174
+ origin = get_origin(stripped_type) or stripped_type
175
+ if is_typeddict(stripped_type) and is_mapping(data):
176
+ return _transform_typeddict(data, stripped_type)
177
+
178
+ if origin == dict and is_mapping(data):
179
+ items_type = get_args(stripped_type)[1]
180
+ return {
181
+ key: _transform_recursive(value, annotation=items_type)
182
+ for key, value in data.items()
183
+ }
184
+
185
+ if (
186
+ # List[T]
187
+ (is_list_type(stripped_type) and is_list(data))
188
+ # Iterable[T]
189
+ or (
190
+ is_iterable_type(stripped_type)
191
+ and is_iterable(data)
192
+ and not isinstance(data, str)
193
+ )
194
+ ):
195
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
196
+ # intended as an iterable, so we don't transform it.
197
+ if isinstance(data, dict):
198
+ return cast(object, data)
199
+
200
+ inner_type = extract_type_arg(stripped_type, 0)
201
+ if _no_transform_needed(inner_type):
202
+ # for some types there is no need to transform anything, so we can get a small
203
+ # perf boost from skipping that work.
204
+ #
205
+ # but we still need to convert to a list to ensure the data is json-serializable
206
+ if is_list(data):
207
+ return data
208
+ return list(data)
209
+
210
+ return [
211
+ _transform_recursive(d, annotation=annotation, inner_type=inner_type)
212
+ for d in data
213
+ ]
214
+
215
+ if is_union_type(stripped_type):
216
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
217
+ #
218
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
219
+ # in different subtypes.
220
+ for subtype in get_args(stripped_type):
221
+ data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
222
+ return data
223
+
224
+ if isinstance(data, pydantic.BaseModel):
225
+ return model_dump(data, exclude_unset=True, mode="json")
226
+
227
+ annotated_type = _get_annotated_type(annotation)
228
+ if annotated_type is None:
229
+ return data
230
+
231
+ # ignore the first argument as it is the actual type
232
+ annotations = get_args(annotated_type)[1:]
233
+ for annotation in annotations:
234
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
235
+ return _format_data(data, annotation.format, annotation.format_template)
236
+
237
+ return data
238
+
239
+
240
+ def _format_data(
241
+ data: object, format_: PropertyFormat, format_template: str | None
242
+ ) -> object:
243
+ if isinstance(data, (date, datetime)):
244
+ if format_ == "iso8601":
245
+ return data.isoformat()
246
+
247
+ if format_ == "custom" and format_template is not None:
248
+ return data.strftime(format_template)
249
+
250
+ if format_ == "base64" and is_base64_file_input(data):
251
+ binary: str | bytes | None = None
252
+
253
+ if isinstance(data, pathlib.Path):
254
+ binary = data.read_bytes()
255
+ elif isinstance(data, io.IOBase):
256
+ binary = data.read()
257
+
258
+ if isinstance(binary, str): # type: ignore[unreachable]
259
+ binary = binary.encode()
260
+
261
+ if not isinstance(binary, bytes):
262
+ raise RuntimeError(
263
+ f"Could not read bytes from {data}; Received {type(binary)}"
264
+ )
265
+
266
+ return base64.b64encode(binary).decode("ascii")
267
+
268
+ return data
269
+
270
+
271
+ def _transform_typeddict(
272
+ data: Mapping[str, object],
273
+ expected_type: type,
274
+ ) -> Mapping[str, object]:
275
+ result: dict[str, object] = {}
276
+ annotations = get_type_hints(expected_type, include_extras=True)
277
+ for key, value in data.items():
278
+ if not is_given(value):
279
+ # we don't need to include `NotGiven` values here as they'll
280
+ # be stripped out before the request is sent anyway
281
+ continue
282
+
283
+ type_ = annotations.get(key)
284
+ if type_ is None:
285
+ # we do not have a type annotation for this field, leave it as is
286
+ result[key] = value
287
+ else:
288
+ result[_maybe_transform_key(key, type_)] = _transform_recursive(
289
+ value, annotation=type_
290
+ )
291
+ return result
292
+
293
+
294
+ async def async_maybe_transform(
295
+ data: object,
296
+ expected_type: object,
297
+ ) -> Any | None:
298
+ """Wrapper over `async_transform()` that allows `None` to be passed.
299
+
300
+ See `async_transform()` for more details.
301
+ """
302
+ if data is None:
303
+ return None
304
+ return await async_transform(data, expected_type)
305
+
306
+
307
+ async def async_transform(
308
+ data: _T,
309
+ expected_type: object,
310
+ ) -> _T:
311
+ """Transform dictionaries based off of type information from the given type, for example:
312
+
313
+ ```py
314
+ class Params(TypedDict, total=False):
315
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
316
+
317
+
318
+ transformed = transform({"card_id": "<my card ID>"}, Params)
319
+ # {'cardID': '<my card ID>'}
320
+ ```
321
+
322
+ Any keys / data that does not have type information given will be included as is.
323
+
324
+ It should be noted that the transformations that this function does are not represented in the type system.
325
+ """
326
+ transformed = await _async_transform_recursive(
327
+ data, annotation=cast(type, expected_type)
328
+ )
329
+ return cast(_T, transformed)
330
+
331
+
332
+ async def _async_transform_recursive(
333
+ data: object,
334
+ *,
335
+ annotation: type,
336
+ inner_type: type | None = None,
337
+ ) -> object:
338
+ """Transform the given data against the expected type.
339
+
340
+ Args:
341
+ annotation: The direct type annotation given to the particular piece of data.
342
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
343
+
344
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
345
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
346
+ the list can be transformed using the metadata from the container type.
347
+
348
+ Defaults to the same value as the `annotation` argument.
349
+ """
350
+ if inner_type is None:
351
+ inner_type = annotation
352
+
353
+ stripped_type = strip_annotated_type(inner_type)
354
+ origin = get_origin(stripped_type) or stripped_type
355
+ if is_typeddict(stripped_type) and is_mapping(data):
356
+ return await _async_transform_typeddict(data, stripped_type)
357
+
358
+ if origin == dict and is_mapping(data):
359
+ items_type = get_args(stripped_type)[1]
360
+ return {
361
+ key: _transform_recursive(value, annotation=items_type)
362
+ for key, value in data.items()
363
+ }
364
+
365
+ if (
366
+ # List[T]
367
+ (is_list_type(stripped_type) and is_list(data))
368
+ # Iterable[T]
369
+ or (
370
+ is_iterable_type(stripped_type)
371
+ and is_iterable(data)
372
+ and not isinstance(data, str)
373
+ )
374
+ ):
375
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
376
+ # intended as an iterable, so we don't transform it.
377
+ if isinstance(data, dict):
378
+ return cast(object, data)
379
+
380
+ inner_type = extract_type_arg(stripped_type, 0)
381
+ if _no_transform_needed(inner_type):
382
+ # for some types there is no need to transform anything, so we can get a small
383
+ # perf boost from skipping that work.
384
+ #
385
+ # but we still need to convert to a list to ensure the data is json-serializable
386
+ if is_list(data):
387
+ return data
388
+ return list(data)
389
+
390
+ return [
391
+ await _async_transform_recursive(
392
+ d, annotation=annotation, inner_type=inner_type
393
+ )
394
+ for d in data
395
+ ]
396
+
397
+ if is_union_type(stripped_type):
398
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
399
+ #
400
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
401
+ # in different subtypes.
402
+ for subtype in get_args(stripped_type):
403
+ data = await _async_transform_recursive(
404
+ data, annotation=annotation, inner_type=subtype
405
+ )
406
+ return data
407
+
408
+ if isinstance(data, pydantic.BaseModel):
409
+ return model_dump(data, exclude_unset=True, mode="json")
410
+
411
+ annotated_type = _get_annotated_type(annotation)
412
+ if annotated_type is None:
413
+ return data
414
+
415
+ # ignore the first argument as it is the actual type
416
+ annotations = get_args(annotated_type)[1:]
417
+ for annotation in annotations:
418
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
419
+ return await _async_format_data(
420
+ data, annotation.format, annotation.format_template
421
+ )
422
+
423
+ return data
424
+
425
+
426
+ async def _async_format_data(
427
+ data: object, format_: PropertyFormat, format_template: str | None
428
+ ) -> object:
429
+ if isinstance(data, (date, datetime)):
430
+ if format_ == "iso8601":
431
+ return data.isoformat()
432
+
433
+ if format_ == "custom" and format_template is not None:
434
+ return data.strftime(format_template)
435
+
436
+ if format_ == "base64" and is_base64_file_input(data):
437
+ binary: str | bytes | None = None
438
+
439
+ if isinstance(data, pathlib.Path):
440
+ binary = await anyio.Path(data).read_bytes()
441
+ elif isinstance(data, io.IOBase):
442
+ binary = data.read()
443
+
444
+ if isinstance(binary, str): # type: ignore[unreachable]
445
+ binary = binary.encode()
446
+
447
+ if not isinstance(binary, bytes):
448
+ raise RuntimeError(
449
+ f"Could not read bytes from {data}; Received {type(binary)}"
450
+ )
451
+
452
+ return base64.b64encode(binary).decode("ascii")
453
+
454
+ return data
455
+
456
+
457
+ async def _async_transform_typeddict(
458
+ data: Mapping[str, object],
459
+ expected_type: type,
460
+ ) -> Mapping[str, object]:
461
+ result: dict[str, object] = {}
462
+ annotations = get_type_hints(expected_type, include_extras=True)
463
+ for key, value in data.items():
464
+ if not is_given(value):
465
+ # we don't need to include `NotGiven` values here as they'll
466
+ # be stripped out before the request is sent anyway
467
+ continue
468
+
469
+ type_ = annotations.get(key)
470
+ if type_ is None:
471
+ # we do not have a type annotation for this field, leave it as is
472
+ result[key] = value
473
+ else:
474
+ result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(
475
+ value, annotation=type_
476
+ )
477
+ return result
478
+
479
+
480
+ @lru_cache(maxsize=8096)
481
+ def get_type_hints(
482
+ obj: Any,
483
+ globalns: dict[str, Any] | None = None,
484
+ localns: Mapping[str, Any] | None = None,
485
+ include_extras: bool = False,
486
+ ) -> dict[str, Any]:
487
+ return _get_type_hints(
488
+ obj, globalns=globalns, localns=localns, include_extras=include_extras
489
+ )
@@ -0,0 +1,171 @@
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 sys
15
+ import typing
16
+ import typing_extensions
17
+ from typing import TypeVar, Iterable, cast
18
+ from collections import abc as _c_abc
19
+ from typing import Any
20
+ from typing_extensions import (
21
+ Required,
22
+ Annotated,
23
+ get_args,
24
+ get_origin,
25
+ )
26
+
27
+ from ._utils import lru_cache
28
+ from .._types import InheritsGeneric
29
+ from .._compat import is_union as _is_union
30
+
31
+
32
+ def is_annotated_type(typ: type) -> bool:
33
+ return get_origin(typ) == Annotated
34
+
35
+
36
+ def is_list_type(typ: type) -> bool:
37
+ return (get_origin(typ) or typ) == list
38
+
39
+
40
+ def is_iterable_type(typ: type) -> bool:
41
+ """If the given type is `typing.Iterable[T]`"""
42
+ origin = get_origin(typ) or typ
43
+ return origin == Iterable or origin == _c_abc.Iterable
44
+
45
+
46
+ def is_union_type(typ: type) -> bool:
47
+ return _is_union(get_origin(typ))
48
+
49
+
50
+ def is_required_type(typ: type) -> bool:
51
+ return get_origin(typ) == Required
52
+
53
+
54
+ def is_typevar(typ: type) -> bool:
55
+ # type ignore is required because type checkers
56
+ # think this expression will always return False
57
+ return type(typ) is TypeVar # type: ignore
58
+
59
+
60
+ _TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (
61
+ typing_extensions.TypeAliasType,
62
+ )
63
+ if sys.version_info >= (3, 12):
64
+ _TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType)
65
+
66
+
67
+ def is_type_alias_type(tp: Any) -> bool:
68
+ """Return whether the provided argument is an instance of `TypeAliasType`.
69
+
70
+ example:
71
+ ```python
72
+ type Int = int
73
+ is_type_alias_type(Int)
74
+ # > True
75
+
76
+ Str = TypeAliasType("Str", str)
77
+ is_type_alias_type(Str)
78
+ # > True
79
+ ```
80
+ """
81
+ return isinstance(tp, _TYPE_ALIAS_TYPES)
82
+
83
+
84
+ # Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]]
85
+ @lru_cache(maxsize=8096)
86
+ def strip_annotated_type(typ: type) -> type:
87
+ if is_required_type(typ) or is_annotated_type(typ):
88
+ return strip_annotated_type(cast(type, get_args(typ)[0]))
89
+
90
+ return typ
91
+
92
+
93
+ def extract_type_arg(typ: type, index: int) -> type:
94
+ args = get_args(typ)
95
+ try:
96
+ return cast(type, args[index])
97
+ except IndexError as err:
98
+ raise RuntimeError(
99
+ f"Expected type {typ} to have a type argument at index {index} but it did not"
100
+ ) from err
101
+
102
+
103
+ def extract_type_var_from_base(
104
+ typ: type,
105
+ *,
106
+ generic_bases: tuple[type, ...],
107
+ index: int,
108
+ failure_message: str | None = None,
109
+ ) -> type:
110
+ """Given a type like `Foo[T]`, returns the generic type variable `T`.
111
+
112
+ This also handles the case where a concrete subclass is given, e.g.
113
+ ```py
114
+ class MyResponse(Foo[bytes]):
115
+ ...
116
+
117
+ extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes
118
+ ```
119
+
120
+ And where a generic subclass is given:
121
+ ```py
122
+ _T = TypeVar('_T')
123
+ class MyResponse(Foo[_T]):
124
+ ...
125
+
126
+ extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes
127
+ ```
128
+ """
129
+ cls = cast(object, get_origin(typ) or typ)
130
+ if cls in generic_bases:
131
+ # we're given the class directly
132
+ return extract_type_arg(typ, index)
133
+
134
+ # if a subclass is given
135
+ # ---
136
+ # this is needed as __orig_bases__ is not present in the typeshed stubs
137
+ # because it is intended to be for internal use only, however there does
138
+ # not seem to be a way to resolve generic TypeVars for inherited subclasses
139
+ # without using it.
140
+ if isinstance(cls, InheritsGeneric):
141
+ target_base_class: Any | None = None
142
+ for base in cls.__orig_bases__:
143
+ if base.__origin__ in generic_bases:
144
+ target_base_class = base
145
+ break
146
+
147
+ if target_base_class is None:
148
+ raise RuntimeError(
149
+ "Could not find the generic base class;\n"
150
+ "This should never happen;\n"
151
+ f"Does {cls} inherit from one of {generic_bases} ?"
152
+ )
153
+
154
+ extracted = extract_type_arg(target_base_class, index)
155
+ if is_typevar(extracted):
156
+ # If the extracted type argument is itself a type variable
157
+ # then that means the subclass itself is generic, so we have
158
+ # to resolve the type argument from the class itself, not
159
+ # the base class.
160
+ #
161
+ # Note: if there is more than 1 type argument, the subclass could
162
+ # change the ordering of the type arguments, this is not currently
163
+ # supported.
164
+ return extract_type_arg(typ, index)
165
+
166
+ return extracted
167
+
168
+ raise RuntimeError(
169
+ failure_message
170
+ or f"Could not resolve inner type variable at index {index} for {typ}"
171
+ )