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,290 @@
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 json
15
+ from typing import TYPE_CHECKING, Any, Iterable, cast
16
+ from typing_extensions import TypeVar, TypeGuard, assert_never
17
+
18
+ import pydantic
19
+
20
+ from .._tools import PydanticFunctionTool
21
+ from ..._types import NOT_GIVEN, NotGiven
22
+ from ..._utils import is_dict, is_given
23
+ from ..._compat import PYDANTIC_V2, model_parse_json
24
+ from ..._models import construct_type_unchecked
25
+ from .._pydantic import is_basemodel_type, to_strict_json_schema, is_dataclass_like_type
26
+ from ...types.chat import (
27
+ ParsedChoice,
28
+ ChatCompletion,
29
+ ParsedFunction,
30
+ ParsedChatCompletion,
31
+ ChatCompletionMessage,
32
+ ParsedFunctionToolCall,
33
+ ChatCompletionToolParam,
34
+ ParsedChatCompletionMessage,
35
+ completion_create_params,
36
+ )
37
+ from ..._exceptions import ArkLengthFinishReasonError, ArkContentFilterFinishReasonError
38
+ from ...types.shared_params import FunctionDefinition
39
+ from ...types.chat.completion_create_params import ResponseFormat as ResponseFormatParam
40
+ from ...types.chat.chat_completion_message_tool_call import Function
41
+
42
+ ResponseFormatT = TypeVar(
43
+ "ResponseFormatT",
44
+ # if it isn't given then we don't do any parsing
45
+ default=None,
46
+ )
47
+ _default_response_format: None = None
48
+
49
+
50
+ def validate_input_tools(
51
+ tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
52
+ ) -> None:
53
+ if not is_given(tools):
54
+ return
55
+
56
+ for tool in tools:
57
+ if tool["type"] != "function":
58
+ raise ValueError(
59
+ f"Currently only `function` tool types support auto-parsing; Received `{tool['type']}`",
60
+ )
61
+
62
+ strict = tool["function"].get("strict")
63
+ if strict is not True:
64
+ raise ValueError(
65
+ f"`{tool['function']['name']}` is not strict. Only `strict` function tools can be auto-parsed"
66
+ )
67
+
68
+
69
+ def parse_chat_completion(
70
+ *,
71
+ response_format: (
72
+ type[ResponseFormatT] | completion_create_params.ResponseFormat | NotGiven
73
+ ),
74
+ input_tools: Iterable[ChatCompletionToolParam] | NotGiven,
75
+ chat_completion: ChatCompletion | ParsedChatCompletion[object],
76
+ ) -> ParsedChatCompletion[ResponseFormatT]:
77
+ if is_given(input_tools):
78
+ input_tools = [t for t in input_tools]
79
+ else:
80
+ input_tools = []
81
+
82
+ choices: list[ParsedChoice[ResponseFormatT]] = []
83
+ for choice in chat_completion.choices:
84
+ if choice.finish_reason == "length":
85
+ raise ArkLengthFinishReasonError(completion=chat_completion)
86
+
87
+ if choice.finish_reason == "content_filter":
88
+ raise ArkContentFilterFinishReasonError()
89
+
90
+ message = choice.message
91
+
92
+ tool_calls: list[ParsedFunctionToolCall] = []
93
+ if message.tool_calls:
94
+ for tool_call in message.tool_calls:
95
+ if tool_call.type == "function":
96
+ tool_call_dict = tool_call.to_dict()
97
+ tool_calls.append(
98
+ construct_type_unchecked(
99
+ value={
100
+ **tool_call_dict,
101
+ "function": {
102
+ **cast(Any, tool_call_dict["function"]),
103
+ "parsed_arguments": parse_function_tool_arguments(
104
+ input_tools=input_tools,
105
+ function=tool_call.function,
106
+ ),
107
+ },
108
+ },
109
+ type_=ParsedFunctionToolCall,
110
+ )
111
+ )
112
+ elif TYPE_CHECKING: # type: ignore[unreachable]
113
+ assert_never(tool_call)
114
+ else:
115
+ tool_calls.append(tool_call)
116
+
117
+ choices.append(
118
+ construct_type_unchecked(
119
+ type_=cast(Any, ParsedChoice)[solve_response_format_t(response_format)],
120
+ value={
121
+ **choice.to_dict(),
122
+ "message": {
123
+ **message.to_dict(),
124
+ "parsed": maybe_parse_content(
125
+ response_format=response_format,
126
+ message=message,
127
+ ),
128
+ "tool_calls": tool_calls if tool_calls else None,
129
+ },
130
+ },
131
+ )
132
+ )
133
+
134
+ return cast(
135
+ ParsedChatCompletion[ResponseFormatT],
136
+ construct_type_unchecked(
137
+ type_=cast(Any, ParsedChatCompletion)[
138
+ solve_response_format_t(response_format)
139
+ ],
140
+ value={
141
+ **chat_completion.to_dict(),
142
+ "choices": choices,
143
+ },
144
+ ),
145
+ )
146
+
147
+
148
+ def get_input_tool_by_name(
149
+ *, input_tools: list[ChatCompletionToolParam], name: str
150
+ ) -> ChatCompletionToolParam | None:
151
+ return next(
152
+ (t for t in input_tools if t.get("function", {}).get("name") == name), None
153
+ )
154
+
155
+
156
+ def parse_function_tool_arguments(
157
+ *, input_tools: list[ChatCompletionToolParam], function: Function | ParsedFunction
158
+ ) -> object:
159
+ input_tool = get_input_tool_by_name(input_tools=input_tools, name=function.name)
160
+ if not input_tool:
161
+ return None
162
+
163
+ input_fn = cast(object, input_tool.get("function"))
164
+ if isinstance(input_fn, PydanticFunctionTool):
165
+ return model_parse_json(input_fn.model, function.arguments)
166
+
167
+ input_fn = cast(FunctionDefinition, input_fn)
168
+
169
+ if not input_fn.get("strict"):
170
+ return None
171
+
172
+ return json.loads(function.arguments)
173
+
174
+
175
+ def maybe_parse_content(
176
+ *,
177
+ response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven,
178
+ message: ChatCompletionMessage | ParsedChatCompletionMessage[object],
179
+ ) -> ResponseFormatT | None:
180
+ if has_rich_response_format(response_format) and message.content:
181
+ return _parse_content(response_format, message.content)
182
+
183
+ return None
184
+
185
+
186
+ def solve_response_format_t(
187
+ response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven,
188
+ ) -> type[ResponseFormatT]:
189
+ """Return the runtime type for the given response format.
190
+
191
+ If no response format is given, or if we won't auto-parse the response format
192
+ then we default to `None`.
193
+ """
194
+ if has_rich_response_format(response_format):
195
+ return response_format
196
+
197
+ return cast("type[ResponseFormatT]", _default_response_format)
198
+
199
+
200
+ def has_parseable_input(
201
+ *,
202
+ response_format: type | ResponseFormatParam | NotGiven,
203
+ input_tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
204
+ ) -> bool:
205
+ if has_rich_response_format(response_format):
206
+ return True
207
+
208
+ for input_tool in input_tools or []:
209
+ if is_parseable_tool(input_tool):
210
+ return True
211
+
212
+ return False
213
+
214
+
215
+ def has_rich_response_format(
216
+ response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven,
217
+ ) -> TypeGuard[type[ResponseFormatT]]:
218
+ if not is_given(response_format):
219
+ return False
220
+
221
+ if is_response_format_param(response_format):
222
+ return False
223
+
224
+ return True
225
+
226
+
227
+ def is_response_format_param(response_format: object) -> TypeGuard[ResponseFormatParam]:
228
+ return is_dict(response_format)
229
+
230
+
231
+ def is_parseable_tool(input_tool: ChatCompletionToolParam) -> bool:
232
+ input_fn = cast(object, input_tool.get("function"))
233
+ if isinstance(input_fn, PydanticFunctionTool):
234
+ return True
235
+
236
+ return cast(FunctionDefinition, input_fn).get("strict") or False
237
+
238
+
239
+ def _parse_content(
240
+ response_format: type[ResponseFormatT], content: str
241
+ ) -> ResponseFormatT:
242
+ if is_basemodel_type(response_format):
243
+ return cast(ResponseFormatT, model_parse_json(response_format, content))
244
+
245
+ if is_dataclass_like_type(response_format):
246
+ if not PYDANTIC_V2:
247
+ raise TypeError(
248
+ f"Non BaseModel types are only supported with Pydantic v2 - {response_format}"
249
+ )
250
+
251
+ return pydantic.TypeAdapter(response_format).validate_json(content)
252
+
253
+ raise TypeError(
254
+ f"Unable to automatically parse response format type {response_format}"
255
+ )
256
+
257
+
258
+ def type_to_response_format_param(
259
+ response_format: type | completion_create_params.ResponseFormat | NotGiven,
260
+ ) -> ResponseFormatParam | NotGiven:
261
+ if not is_given(response_format):
262
+ return NOT_GIVEN
263
+
264
+ if is_response_format_param(response_format):
265
+ return response_format
266
+
267
+ # type checkers don't narrow the negation of a `TypeGuard` as it isn't
268
+ # a safe default behaviour but we know that at this point the `response_format`
269
+ # can only be a `type`
270
+ response_format = cast(type, response_format)
271
+
272
+ json_schema_type: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any] | None = None
273
+
274
+ if is_basemodel_type(response_format):
275
+ name = response_format.__name__
276
+ json_schema_type = response_format
277
+ elif is_dataclass_like_type(response_format):
278
+ name = response_format.__name__
279
+ json_schema_type = pydantic.TypeAdapter(response_format)
280
+ else:
281
+ raise TypeError(f"Unsupported response_format type - {response_format}")
282
+
283
+ return {
284
+ "type": "json_schema",
285
+ "json_schema": {
286
+ "schema": to_strict_json_schema(json_schema_type),
287
+ "name": name,
288
+ "strict": True,
289
+ },
290
+ }
@@ -0,0 +1,189 @@
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 json
15
+ from typing import TYPE_CHECKING, Any, List, Iterable, cast
16
+ from typing_extensions import TypeVar, assert_never
17
+
18
+ import pydantic
19
+
20
+ from .._tools import ResponsesPydanticFunctionTool
21
+ from ..._types import NotGiven
22
+ from ..._utils import is_given
23
+ from ..._compat import PYDANTIC_V2, model_parse_json
24
+ from ..._models import construct_type_unchecked
25
+ from .._pydantic import is_basemodel_type, is_dataclass_like_type
26
+ from ._completions import solve_response_format_t, type_to_response_format_param
27
+ from ...types.responses import (
28
+ Response,
29
+ ToolParam,
30
+ ParsedContent,
31
+ ParsedResponse,
32
+ FunctionToolParam,
33
+ ParsedResponseOutputItem,
34
+ ParsedResponseOutputText,
35
+ ResponseFunctionToolCall,
36
+ ParsedResponseOutputMessage,
37
+ ResponseFormatTextConfigParam,
38
+ ParsedResponseFunctionToolCall,
39
+ )
40
+ from ...types.chat.completion_create_params import ResponseFormat
41
+
42
+ TextFormatT = TypeVar(
43
+ "TextFormatT",
44
+ # if it isn't given then we don't do any parsing
45
+ default=None,
46
+ )
47
+
48
+
49
+ def type_to_text_format_param(type_: type) -> ResponseFormatTextConfigParam:
50
+ response_format_dict = type_to_response_format_param(type_)
51
+ assert is_given(response_format_dict)
52
+ response_format_dict = cast(
53
+ ResponseFormat, response_format_dict
54
+ ) # pyright: ignore[reportUnnecessaryCast]
55
+ assert response_format_dict["type"] == "json_schema"
56
+ assert "schema" in response_format_dict["json_schema"]
57
+
58
+ return {
59
+ "type": "json_schema",
60
+ "strict": True,
61
+ "name": response_format_dict["json_schema"]["name"],
62
+ "schema": response_format_dict["json_schema"]["schema"],
63
+ }
64
+
65
+
66
+ def parse_response(
67
+ *,
68
+ text_format: type[TextFormatT] | NotGiven,
69
+ input_tools: Iterable[ToolParam] | NotGiven | None,
70
+ response: Response | ParsedResponse[object],
71
+ ) -> ParsedResponse[TextFormatT]:
72
+ solved_t = solve_response_format_t(text_format)
73
+ output_list: List[ParsedResponseOutputItem[TextFormatT]] = []
74
+
75
+ for output in response.output:
76
+ if output.type == "message":
77
+ content_list: List[ParsedContent[TextFormatT]] = []
78
+ for item in output.content:
79
+ if item.type != "output_text":
80
+ content_list.append(item)
81
+ continue
82
+
83
+ content_list.append(
84
+ construct_type_unchecked(
85
+ type_=cast(Any, ParsedResponseOutputText)[solved_t],
86
+ value={
87
+ **item.to_dict(),
88
+ "parsed": parse_text(item.text, text_format=text_format),
89
+ },
90
+ )
91
+ )
92
+
93
+ output_list.append(
94
+ construct_type_unchecked(
95
+ type_=cast(Any, ParsedResponseOutputMessage)[solved_t],
96
+ value={
97
+ **output.to_dict(),
98
+ "content": content_list,
99
+ },
100
+ )
101
+ )
102
+ elif output.type == "function_call":
103
+ output_list.append(
104
+ construct_type_unchecked(
105
+ type_=ParsedResponseFunctionToolCall,
106
+ value={
107
+ **output.to_dict(),
108
+ "parsed_arguments": parse_function_tool_arguments(
109
+ input_tools=input_tools, function_call=output
110
+ ),
111
+ },
112
+ )
113
+ )
114
+ elif (
115
+ output.type == "computer_call"
116
+ or output.type == "file_search_call"
117
+ or output.type == "web_search_call"
118
+ or output.type == "reasoning"
119
+ ):
120
+ output_list.append(output)
121
+ elif TYPE_CHECKING: # type: ignore
122
+ assert_never(output)
123
+ else:
124
+ output_list.append(output)
125
+
126
+ return cast(
127
+ ParsedResponse[TextFormatT],
128
+ construct_type_unchecked(
129
+ type_=cast(Any, ParsedResponse)[solved_t],
130
+ value={
131
+ **response.to_dict(),
132
+ "output": output_list,
133
+ },
134
+ ),
135
+ )
136
+
137
+
138
+ def parse_text(
139
+ text: str, text_format: type[TextFormatT] | NotGiven
140
+ ) -> TextFormatT | None:
141
+ if not is_given(text_format):
142
+ return None
143
+
144
+ if is_basemodel_type(text_format):
145
+ return cast(TextFormatT, model_parse_json(text_format, text))
146
+
147
+ if is_dataclass_like_type(text_format):
148
+ if not PYDANTIC_V2:
149
+ raise TypeError(
150
+ f"Non BaseModel types are only supported with Pydantic v2 - {text_format}"
151
+ )
152
+
153
+ return pydantic.TypeAdapter(text_format).validate_json(text)
154
+
155
+ raise TypeError(f"Unable to automatically parse response format type {text_format}")
156
+
157
+
158
+ def get_input_tool_by_name(
159
+ *, input_tools: Iterable[ToolParam], name: str
160
+ ) -> FunctionToolParam | None:
161
+ for tool in input_tools:
162
+ if tool["type"] == "function" and tool.get("name") == name:
163
+ return tool
164
+
165
+ return None
166
+
167
+
168
+ def parse_function_tool_arguments(
169
+ *,
170
+ input_tools: Iterable[ToolParam] | NotGiven | None,
171
+ function_call: ParsedResponseFunctionToolCall | ResponseFunctionToolCall,
172
+ ) -> object:
173
+ if input_tools is None or not is_given(input_tools):
174
+ return None
175
+
176
+ input_tool = get_input_tool_by_name(
177
+ input_tools=input_tools, name=function_call.name
178
+ )
179
+ if not input_tool:
180
+ return None
181
+
182
+ tool = cast(object, input_tool)
183
+ if isinstance(tool, ResponsesPydanticFunctionTool):
184
+ return model_parse_json(tool.model, function_call.arguments)
185
+
186
+ if not input_tool.get("strict"):
187
+ return None
188
+
189
+ return json.loads(function_call.arguments)
@@ -0,0 +1,192 @@
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 inspect
15
+ from typing import Any, TypeVar
16
+ from typing_extensions import TypeGuard
17
+
18
+ import pydantic
19
+
20
+ from .._types import NOT_GIVEN
21
+ from .._utils import is_dict as _is_dict, is_list
22
+ from .._compat import PYDANTIC_V2, model_json_schema
23
+
24
+ _T = TypeVar("_T")
25
+
26
+
27
+ def to_strict_json_schema(
28
+ model: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any],
29
+ ) -> dict[str, Any]:
30
+ if inspect.isclass(model) and is_basemodel_type(model):
31
+ schema = model_json_schema(model)
32
+ elif PYDANTIC_V2 and isinstance(model, pydantic.TypeAdapter):
33
+ schema = model.json_schema()
34
+ else:
35
+ raise TypeError(
36
+ f"Non BaseModel types are only supported with Pydantic v2 - {model}"
37
+ )
38
+
39
+ return _ensure_strict_json_schema(schema, path=(), root=schema)
40
+
41
+
42
+ def _ensure_strict_json_schema(
43
+ json_schema: object,
44
+ *,
45
+ path: tuple[str, ...],
46
+ root: dict[str, object],
47
+ ) -> dict[str, Any]:
48
+ """Mutates the given JSON schema to ensure it conforms to the `strict` standard
49
+ that the API expects.
50
+ """
51
+ if not is_dict(json_schema):
52
+ raise TypeError(f"Expected {json_schema} to be a dictionary; path={path}")
53
+
54
+ defs = json_schema.get("$defs")
55
+ if is_dict(defs):
56
+ for def_name, def_schema in defs.items():
57
+ _ensure_strict_json_schema(
58
+ def_schema, path=(*path, "$defs", def_name), root=root
59
+ )
60
+
61
+ definitions = json_schema.get("definitions")
62
+ if is_dict(definitions):
63
+ for definition_name, definition_schema in definitions.items():
64
+ _ensure_strict_json_schema(
65
+ definition_schema,
66
+ path=(*path, "definitions", definition_name),
67
+ root=root,
68
+ )
69
+
70
+ typ = json_schema.get("type")
71
+ if typ == "object" and "additionalProperties" not in json_schema:
72
+ json_schema["additionalProperties"] = False
73
+
74
+ # object types
75
+ # { 'type': 'object', 'properties': { 'a': {...} } }
76
+ properties = json_schema.get("properties")
77
+ if is_dict(properties):
78
+ json_schema["required"] = [prop for prop in properties.keys()]
79
+ json_schema["properties"] = {
80
+ key: _ensure_strict_json_schema(
81
+ prop_schema, path=(*path, "properties", key), root=root
82
+ )
83
+ for key, prop_schema in properties.items()
84
+ }
85
+
86
+ # arrays
87
+ # { 'type': 'array', 'items': {...} }
88
+ items = json_schema.get("items")
89
+ if is_dict(items):
90
+ json_schema["items"] = _ensure_strict_json_schema(
91
+ items, path=(*path, "items"), root=root
92
+ )
93
+
94
+ # unions
95
+ any_of = json_schema.get("anyOf")
96
+ if is_list(any_of):
97
+ json_schema["anyOf"] = [
98
+ _ensure_strict_json_schema(
99
+ variant, path=(*path, "anyOf", str(i)), root=root
100
+ )
101
+ for i, variant in enumerate(any_of)
102
+ ]
103
+
104
+ # intersections
105
+ all_of = json_schema.get("allOf")
106
+ if is_list(all_of):
107
+ if len(all_of) == 1:
108
+ json_schema.update(
109
+ _ensure_strict_json_schema(
110
+ all_of[0], path=(*path, "allOf", "0"), root=root
111
+ )
112
+ )
113
+ json_schema.pop("allOf")
114
+ else:
115
+ json_schema["allOf"] = [
116
+ _ensure_strict_json_schema(
117
+ entry, path=(*path, "allOf", str(i)), root=root
118
+ )
119
+ for i, entry in enumerate(all_of)
120
+ ]
121
+
122
+ # strip `None` defaults as there's no meaningful distinction here
123
+ # the schema will still be `nullable` and the model will default
124
+ # to using `None` anyway
125
+ if json_schema.get("default", NOT_GIVEN) is None:
126
+ json_schema.pop("default")
127
+
128
+ # we can't use `$ref`s if there are also other properties defined, e.g.
129
+ # `{"$ref": "...", "description": "my description"}`
130
+ #
131
+ # so we unravel the ref
132
+ # `{"type": "string", "description": "my description"}`
133
+ ref = json_schema.get("$ref")
134
+ if ref and has_more_than_n_keys(json_schema, 1):
135
+ assert isinstance(ref, str), f"Received non-string $ref - {ref}"
136
+
137
+ resolved = resolve_ref(root=root, ref=ref)
138
+ if not is_dict(resolved):
139
+ raise ValueError(
140
+ f"Expected `$ref: {ref}` to resolved to a dictionary but got {resolved}"
141
+ )
142
+
143
+ # properties from the json schema take priority over the ones on the `$ref`
144
+ json_schema.update({**resolved, **json_schema})
145
+ json_schema.pop("$ref")
146
+ # Since the schema expanded from `$ref` might not have `additionalProperties: false` applied,
147
+ # we call `_ensure_strict_json_schema` again to fix the inlined schema and ensure it's valid.
148
+ return _ensure_strict_json_schema(json_schema, path=path, root=root)
149
+
150
+ return json_schema
151
+
152
+
153
+ def resolve_ref(*, root: dict[str, object], ref: str) -> object:
154
+ if not ref.startswith("#/"):
155
+ raise ValueError(f"Unexpected $ref format {ref!r}; Does not start with #/")
156
+
157
+ path = ref[2:].split("/")
158
+ resolved = root
159
+ for key in path:
160
+ value = resolved[key]
161
+ assert is_dict(
162
+ value
163
+ ), f"encountered non-dictionary entry while resolving {ref} - {resolved}"
164
+ resolved = value
165
+
166
+ return resolved
167
+
168
+
169
+ def is_basemodel_type(typ: type) -> TypeGuard[type[pydantic.BaseModel]]:
170
+ if not inspect.isclass(typ):
171
+ return False
172
+ return issubclass(typ, pydantic.BaseModel)
173
+
174
+
175
+ def is_dataclass_like_type(typ: type) -> bool:
176
+ """Returns True if the given type likely used `@pydantic.dataclass`"""
177
+ return hasattr(typ, "__pydantic_config__")
178
+
179
+
180
+ def is_dict(obj: object) -> TypeGuard[dict[str, object]]:
181
+ # just pretend that we know there are only `str` keys
182
+ # as that check is not worth the performance cost
183
+ return _is_dict(obj)
184
+
185
+
186
+ def has_more_than_n_keys(obj: dict[str, object], n: int) -> bool:
187
+ i = 0
188
+ for _ in obj.keys():
189
+ i += 1
190
+ if i > n:
191
+ return True
192
+ return False