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,734 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ from typing import (
6
+ TYPE_CHECKING,
7
+ Any,
8
+ Type,
9
+ Generic,
10
+ TypeVar,
11
+ Callable,
12
+ cast,
13
+ )
14
+ from datetime import date, datetime
15
+ from typing_extensions import (
16
+ Literal,
17
+ ClassVar,
18
+ Protocol,
19
+ ParamSpec,
20
+ TypeGuard,
21
+ override,
22
+ runtime_checkable,
23
+ )
24
+
25
+ import pydantic
26
+ from pydantic.fields import FieldInfo
27
+
28
+ from ._utils import (
29
+ PropertyInfo,
30
+ is_list,
31
+ lru_cache,
32
+ is_mapping,
33
+ parse_date,
34
+ coerce_boolean,
35
+ parse_datetime,
36
+ extract_type_arg,
37
+ is_annotated_type,
38
+ strip_annotated_type,
39
+ )
40
+ from ._compat import (
41
+ PYDANTIC_V2,
42
+ ConfigDict,
43
+ GenericModel as BaseGenericModel,
44
+ get_args,
45
+ is_union,
46
+ parse_obj,
47
+ get_origin,
48
+ is_literal_type,
49
+ get_model_config,
50
+ get_model_fields,
51
+ field_get_default,
52
+ )
53
+
54
+ from ._types import ModelT
55
+
56
+
57
+ if TYPE_CHECKING:
58
+ from pydantic_core.core_schema import (
59
+ ModelField,
60
+ )
61
+
62
+ __all__ = ["BaseModel", "GenericModel"]
63
+
64
+ _T = TypeVar("_T")
65
+ _BaseModelT = TypeVar("_BaseModelT", bound="BaseModel")
66
+
67
+ P = ParamSpec("P")
68
+
69
+
70
+ @runtime_checkable
71
+ class _ConfigProtocol(Protocol):
72
+ allow_population_by_field_name: bool
73
+
74
+
75
+ class BaseModel(pydantic.BaseModel):
76
+ if PYDANTIC_V2:
77
+ model_config: ClassVar[ConfigDict] = ConfigDict(
78
+ extra="allow",
79
+ defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")),
80
+ protected_namespaces=(),
81
+ )
82
+ else:
83
+
84
+ @property
85
+ @override
86
+ def model_fields_set(self) -> set[str]:
87
+ # a forwards-compat shim for pydantic v2
88
+ return self.__fields_set__ # type: ignore
89
+
90
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
91
+ extra: Any = pydantic.Extra.allow # type: ignore
92
+
93
+ def to_dict(
94
+ self,
95
+ *,
96
+ mode: Literal["json", "python"] = "python",
97
+ use_api_names: bool = True,
98
+ exclude_unset: bool = True,
99
+ exclude_defaults: bool = False,
100
+ exclude_none: bool = False,
101
+ warnings: bool = True,
102
+ ) -> dict[str, object]:
103
+ """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
104
+
105
+ By default, fields that were not set by the API will not be included,
106
+ and keys will match the API response, *not* the property names from the model.
107
+
108
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
109
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
110
+
111
+ Args:
112
+ mode:
113
+ If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
114
+ If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
115
+
116
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
117
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
118
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
119
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
120
+ warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
121
+ """
122
+ return self.model_dump(
123
+ mode=mode,
124
+ by_alias=use_api_names,
125
+ exclude_unset=exclude_unset,
126
+ exclude_defaults=exclude_defaults,
127
+ exclude_none=exclude_none,
128
+ warnings=warnings,
129
+ )
130
+
131
+ def to_json(
132
+ self,
133
+ *,
134
+ indent: int | None = 2,
135
+ use_api_names: bool = True,
136
+ exclude_unset: bool = True,
137
+ exclude_defaults: bool = False,
138
+ exclude_none: bool = False,
139
+ warnings: bool = True,
140
+ ) -> str:
141
+ """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
142
+
143
+ By default, fields that were not set by the API will not be included,
144
+ and keys will match the API response, *not* the property names from the model.
145
+
146
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
147
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
148
+
149
+ Args:
150
+ indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
151
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
152
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
153
+ exclude_defaults: Whether to exclude fields that have the default value.
154
+ exclude_none: Whether to exclude fields that have a value of `None`.
155
+ warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
156
+ """
157
+ return self.model_dump_json(
158
+ indent=indent,
159
+ by_alias=use_api_names,
160
+ exclude_unset=exclude_unset,
161
+ exclude_defaults=exclude_defaults,
162
+ exclude_none=exclude_none,
163
+ warnings=warnings,
164
+ )
165
+
166
+ @override
167
+ def __str__(self) -> str:
168
+ # mypy complains about an invalid self arg
169
+ return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc]
170
+
171
+ # Override the 'construct' method in a way that supports recursive parsing without validation.
172
+ # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
173
+ @classmethod
174
+ @override
175
+ def construct(
176
+ cls: Type[ModelT],
177
+ _fields_set: set[str] | None = None,
178
+ **values: object,
179
+ ) -> ModelT:
180
+ m = cls.__new__(cls)
181
+ fields_values: dict[str, object] = {}
182
+
183
+ config = get_model_config(cls)
184
+ populate_by_name = (
185
+ config.allow_population_by_field_name
186
+ if isinstance(config, _ConfigProtocol)
187
+ else config.get("populate_by_name")
188
+ )
189
+
190
+ if _fields_set is None:
191
+ _fields_set = set()
192
+
193
+ model_fields = get_model_fields(cls)
194
+ for name, field in model_fields.items():
195
+ key = field.alias
196
+ if key is None or (key not in values and populate_by_name):
197
+ key = name
198
+
199
+ if key in values:
200
+ fields_values[name] = _construct_field(
201
+ value=values[key], field=field, key=key
202
+ )
203
+ _fields_set.add(name)
204
+ else:
205
+ fields_values[name] = field_get_default(field)
206
+
207
+ _extra = {}
208
+ for key, value in values.items():
209
+ if key not in model_fields:
210
+ if PYDANTIC_V2:
211
+ _extra[key] = value
212
+ else:
213
+ _fields_set.add(key)
214
+ fields_values[key] = value
215
+
216
+ object.__setattr__(m, "__dict__", fields_values)
217
+
218
+ if PYDANTIC_V2:
219
+ # these properties are copied from Pydantic's `model_construct()` method
220
+ object.__setattr__(m, "__pydantic_private__", None)
221
+ object.__setattr__(m, "__pydantic_extra__", _extra)
222
+ object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
223
+ else:
224
+ # init_private_attributes() does not exist in v2
225
+ m._init_private_attributes() # type: ignore
226
+
227
+ # copied from Pydantic v1's `construct()` method
228
+ object.__setattr__(m, "__fields_set__", _fields_set)
229
+
230
+ return m
231
+
232
+ if not TYPE_CHECKING:
233
+ # type checkers incorrectly complain about this assignment
234
+ # because the type signatures are technically different
235
+ # although not in practice
236
+ model_construct = construct
237
+
238
+ if not PYDANTIC_V2:
239
+ # we define aliases for some of the new pydantic v2 methods so
240
+ # that we can just document these methods without having to specify
241
+ # a specific pydantic version as some users may not know which
242
+ # pydantic version they are currently using
243
+
244
+ @override
245
+ def model_dump(
246
+ self,
247
+ *,
248
+ mode: Literal["json", "python"] | str = "python",
249
+ include: (
250
+ set[int] | set[str] | dict[int, Any] | dict[str, Any] | None
251
+ ) = None,
252
+ exclude: (
253
+ set[int] | set[str] | dict[int, Any] | dict[str, Any] | None
254
+ ) = None,
255
+ by_alias: bool = False,
256
+ exclude_unset: bool = False,
257
+ exclude_defaults: bool = False,
258
+ exclude_none: bool = False,
259
+ round_trip: bool = False,
260
+ warnings: bool = True,
261
+ ) -> dict[str, Any]:
262
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
263
+
264
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
265
+
266
+ Args:
267
+ mode: The mode in which `to_python` should run.
268
+ If mode is 'json', the dictionary will only contain JSON serializable types.
269
+ If mode is 'python', the dictionary may contain any Python objects.
270
+ include: A list of fields to include in the output.
271
+ exclude: A list of fields to exclude from the output.
272
+ by_alias: Whether to use the field's alias in the dictionary key if defined.
273
+ exclude_unset: Whether to exclude fields that are unset or None from the output.
274
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
275
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
276
+ round_trip: Whether to enable serialization and deserialization round-trip support.
277
+ warnings: Whether to log warnings when invalid fields are encountered.
278
+
279
+ Returns:
280
+ A dictionary representation of the model.
281
+ """
282
+ if mode != "python":
283
+ raise ValueError("mode is only supported in Pydantic v2")
284
+ if round_trip != False:
285
+ raise ValueError("round_trip is only supported in Pydantic v2")
286
+ if warnings != True:
287
+ raise ValueError("warnings is only supported in Pydantic v2")
288
+ return super().dict( # pyright: ignore[reportDeprecated]
289
+ include=include,
290
+ exclude=exclude,
291
+ by_alias=by_alias,
292
+ exclude_unset=exclude_unset,
293
+ exclude_defaults=exclude_defaults,
294
+ exclude_none=exclude_none,
295
+ )
296
+
297
+ @override
298
+ def model_dump_json(
299
+ self,
300
+ *,
301
+ indent: int | None = None,
302
+ include: (
303
+ set[int] | set[str] | dict[int, Any] | dict[str, Any] | None
304
+ ) = None,
305
+ exclude: (
306
+ set[int] | set[str] | dict[int, Any] | dict[str, Any] | None
307
+ ) = None,
308
+ by_alias: bool = False,
309
+ exclude_unset: bool = False,
310
+ exclude_defaults: bool = False,
311
+ exclude_none: bool = False,
312
+ round_trip: bool = False,
313
+ warnings: bool = True,
314
+ ) -> str:
315
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
316
+
317
+ Generates a JSON representation of the model using Pydantic's `to_json` method.
318
+
319
+ Args:
320
+ indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
321
+ include: Field(s) to include in the JSON output. Can take either a string or set of strings.
322
+ exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings.
323
+ by_alias: Whether to serialize using field aliases.
324
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
325
+ exclude_defaults: Whether to exclude fields that have the default value.
326
+ exclude_none: Whether to exclude fields that have a value of `None`.
327
+ round_trip: Whether to use serialization/deserialization between JSON and class instance.
328
+ warnings: Whether to show any warnings that occurred during serialization.
329
+
330
+ Returns:
331
+ A JSON string representation of the model.
332
+ """
333
+ if round_trip != False:
334
+ raise ValueError("round_trip is only supported in Pydantic v2")
335
+ if warnings != True:
336
+ raise ValueError("warnings is only supported in Pydantic v2")
337
+ return super().json( # type: ignore[reportDeprecated]
338
+ indent=indent,
339
+ include=include,
340
+ exclude=exclude,
341
+ by_alias=by_alias,
342
+ exclude_unset=exclude_unset,
343
+ exclude_defaults=exclude_defaults,
344
+ exclude_none=exclude_none,
345
+ )
346
+
347
+
348
+ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
349
+ if value is None:
350
+ return field_get_default(field)
351
+
352
+ if PYDANTIC_V2:
353
+ type_ = field.annotation
354
+ else:
355
+ type_ = cast(type, field.outer_type_) # type: ignore
356
+
357
+ if type_ is None:
358
+ raise RuntimeError(f"Unexpected field type is None for {key}")
359
+
360
+ return construct_type(value=value, type_=type_)
361
+
362
+
363
+ def is_basemodel(type_: type) -> bool:
364
+ """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
365
+ if is_union(type_):
366
+ for variant in get_args(type_):
367
+ if is_basemodel(variant):
368
+ return True
369
+
370
+ return False
371
+
372
+ return is_basemodel_type(type_)
373
+
374
+
375
+ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
376
+ origin = get_origin(type_) or type_
377
+ return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
378
+
379
+
380
+ def build(
381
+ base_model_cls: Callable[P, _BaseModelT],
382
+ *args: P.args,
383
+ **kwargs: P.kwargs,
384
+ ) -> _BaseModelT:
385
+ """Construct a BaseModel class without validation.
386
+
387
+ This is useful for cases where you need to instantiate a `BaseModel`
388
+ from an API response as this provides type-safe params which isn't supported
389
+ by helpers like `construct_type()`.
390
+
391
+ ```py
392
+ build(MyModel, my_field_a="foo", my_field_b=123)
393
+ ```
394
+ """
395
+ if args:
396
+ raise TypeError(
397
+ "Received positional arguments which are not supported; Keyword arguments must be used instead",
398
+ )
399
+
400
+ return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs))
401
+
402
+
403
+ def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T:
404
+ """Loose coercion to the expected type with construction of nested values.
405
+
406
+ Note: the returned value from this function is not guaranteed to match the
407
+ given type.
408
+ """
409
+ return cast(_T, construct_type(value=value, type_=type_))
410
+
411
+
412
+ def construct_type(*, value: object, type_: object) -> object:
413
+ """Loose coercion to the expected type with construction of nested values.
414
+
415
+ If the given value does not match the expected type then it is returned as-is.
416
+ """
417
+ # we allow `object` as the input type because otherwise, passing things like
418
+ # `Literal['value']` will be reported as a type error by type checkers
419
+ type_ = cast("type[object]", type_)
420
+
421
+ # unwrap `Annotated[T, ...]` -> `T`
422
+ if is_annotated_type(type_):
423
+ meta: tuple[Any, ...] = get_args(type_)[1:]
424
+ type_ = extract_type_arg(type_, 0)
425
+ else:
426
+ meta = tuple()
427
+
428
+ # we need to use the origin class for any types that are subscripted generics
429
+ # e.g. Dict[str, object]
430
+ origin = get_origin(type_) or type_
431
+ args = get_args(type_)
432
+
433
+ if is_union(origin):
434
+ try:
435
+ return validate_type(type_=cast("type[object]", type_), value=value)
436
+ except Exception:
437
+ pass
438
+
439
+ # if the type is a discriminated union then we want to construct the right variant
440
+ # in the union, even if the data doesn't match exactly, otherwise we'd break code
441
+ # that relies on the constructed class types, e.g.
442
+ #
443
+ # class FooType:
444
+ # kind: Literal['foo']
445
+ # value: str
446
+ #
447
+ # class BarType:
448
+ # kind: Literal['bar']
449
+ # value: int
450
+ #
451
+ # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then
452
+ # we'd end up constructing `FooType` when it should be `BarType`.
453
+ discriminator = _build_discriminated_union_meta(
454
+ union=type_, meta_annotations=meta
455
+ )
456
+ if discriminator and is_mapping(value):
457
+ variant_value = value.get(
458
+ discriminator.field_alias_from or discriminator.field_name
459
+ )
460
+ if variant_value and isinstance(variant_value, str):
461
+ variant_type = discriminator.mapping.get(variant_value)
462
+ if variant_type:
463
+ return construct_type(type_=variant_type, value=value)
464
+
465
+ # if the data is not valid, use the first variant that doesn't fail while deserializing
466
+ for variant in args:
467
+ try:
468
+ return construct_type(value=value, type_=variant)
469
+ except Exception:
470
+ continue
471
+
472
+ raise RuntimeError(f"Could not convert data into a valid instance of {type_}")
473
+
474
+ if origin == dict:
475
+ if not is_mapping(value):
476
+ return value
477
+
478
+ _, items_type = get_args(type_) # Dict[_, items_type]
479
+ return {
480
+ key: construct_type(value=item, type_=items_type)
481
+ for key, item in value.items()
482
+ }
483
+
484
+ if not is_literal_type(type_) and (
485
+ issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
486
+ ):
487
+ if is_list(value):
488
+ return [
489
+ cast(Any, type_).construct(**entry) if is_mapping(entry) else entry
490
+ for entry in value
491
+ ]
492
+
493
+ if is_mapping(value):
494
+ if issubclass(type_, BaseModel):
495
+ return type_.construct(**value) # type: ignore[arg-type]
496
+
497
+ return cast(Any, type_).construct(**value)
498
+
499
+ if origin == list:
500
+ if not is_list(value):
501
+ return value
502
+
503
+ inner_type = args[0] # List[inner_type]
504
+ return [construct_type(value=entry, type_=inner_type) for entry in value]
505
+
506
+ if origin == float:
507
+ if isinstance(value, int):
508
+ coerced = float(value)
509
+ if coerced != value:
510
+ return value
511
+ return coerced
512
+
513
+ return value
514
+
515
+ if type_ == datetime:
516
+ try:
517
+ return parse_datetime(value) # type: ignore
518
+ except Exception:
519
+ return value
520
+
521
+ if type_ == date:
522
+ try:
523
+ return parse_date(value) # type: ignore
524
+ except Exception:
525
+ return value
526
+
527
+ return value
528
+
529
+
530
+ @runtime_checkable
531
+ class CachedDiscriminatorType(Protocol):
532
+ __discriminator__: DiscriminatorDetails
533
+
534
+
535
+ class DiscriminatorDetails:
536
+ field_name: str
537
+ """The name of the discriminator field in the variant class, e.g.
538
+
539
+ ```py
540
+ class Foo(BaseModel):
541
+ type: Literal['foo']
542
+ ```
543
+
544
+ Will result in field_name='type'
545
+ """
546
+
547
+ field_alias_from: str | None
548
+ """The name of the discriminator field in the API response, e.g.
549
+
550
+ ```py
551
+ class Foo(BaseModel):
552
+ type: Literal['foo'] = Field(alias='type_from_api')
553
+ ```
554
+
555
+ Will result in field_alias_from='type_from_api'
556
+ """
557
+
558
+ mapping: dict[str, type]
559
+ """Mapping of discriminator value to variant type, e.g.
560
+
561
+ {'foo': FooVariant, 'bar': BarVariant}
562
+ """
563
+
564
+ def __init__(
565
+ self,
566
+ *,
567
+ mapping: dict[str, type],
568
+ discriminator_field: str,
569
+ discriminator_alias: str | None,
570
+ ) -> None:
571
+ self.mapping = mapping
572
+ self.field_name = discriminator_field
573
+ self.field_alias_from = discriminator_alias
574
+
575
+
576
+ def _build_discriminated_union_meta(
577
+ *, union: type, meta_annotations: tuple[Any, ...]
578
+ ) -> DiscriminatorDetails | None:
579
+ if isinstance(union, CachedDiscriminatorType):
580
+ return union.__discriminator__
581
+
582
+ discriminator_field_name: str | None = None
583
+
584
+ for annotation in meta_annotations:
585
+ if (
586
+ isinstance(annotation, PropertyInfo)
587
+ and annotation.discriminator is not None
588
+ ):
589
+ discriminator_field_name = annotation.discriminator
590
+ break
591
+
592
+ if not discriminator_field_name:
593
+ return None
594
+
595
+ mapping: dict[str, type] = {}
596
+ discriminator_alias: str | None = None
597
+
598
+ for variant in get_args(union):
599
+ variant = strip_annotated_type(variant)
600
+ if is_basemodel_type(variant):
601
+ if PYDANTIC_V2:
602
+ field = _extract_field_schema_pv2(variant, discriminator_field_name)
603
+ if not field:
604
+ continue
605
+
606
+ # Note: if one variant defines an alias then they all should
607
+ discriminator_alias = field.get("serialization_alias")
608
+
609
+ field_schema = field["schema"]
610
+
611
+ if field_schema["type"] == "literal":
612
+ for entry in field_schema["expected"]:
613
+ if isinstance(entry, str):
614
+ mapping[entry] = variant
615
+ else:
616
+ field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(
617
+ discriminator_field_name
618
+ ) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
619
+ if not field_info:
620
+ continue
621
+
622
+ # Note: if one variant defines an alias then they all should
623
+ discriminator_alias = field_info.alias
624
+
625
+ if field_info.annotation and is_literal_type(field_info.annotation):
626
+ for entry in get_args(field_info.annotation):
627
+ if isinstance(entry, str):
628
+ mapping[entry] = variant
629
+
630
+ if not mapping:
631
+ return None
632
+
633
+ details = DiscriminatorDetails(
634
+ mapping=mapping,
635
+ discriminator_field=discriminator_field_name,
636
+ discriminator_alias=discriminator_alias,
637
+ )
638
+ cast(CachedDiscriminatorType, union).__discriminator__ = details
639
+ return details
640
+
641
+
642
+ def _extract_field_schema_pv2(
643
+ model: type[BaseModel], field_name: str
644
+ ) -> ModelField | None:
645
+ schema = model.__pydantic_core_schema__
646
+ if schema["type"] != "model":
647
+ return None
648
+
649
+ fields_schema = schema["schema"]
650
+ if fields_schema["type"] != "model-fields":
651
+ return None
652
+
653
+ fields_schema = cast("ModelFieldsSchema", fields_schema)
654
+
655
+ field = fields_schema["fields"].get(field_name)
656
+ if not field:
657
+ return None
658
+
659
+ return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast]
660
+
661
+
662
+ def validate_type(*, type_: type[_T], value: object) -> _T:
663
+ """Strict validation that the given value matches the expected type"""
664
+ if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
665
+ return cast(_T, parse_obj(type_, value))
666
+
667
+ return cast(_T, _validate_non_model_type(type_=type_, value=value))
668
+
669
+
670
+ def add_request_id(obj: BaseModel, request_id: str | None) -> None:
671
+ obj._request_id = request_id
672
+
673
+ # in Pydantic v1, using setattr like we do above causes the attribute
674
+ # to be included when serializing the model which we don't want in this
675
+ # case so we need to explicitly exclude it
676
+ if not PYDANTIC_V2:
677
+ try:
678
+ exclude_fields = obj.__exclude_fields__ # type: ignore
679
+ except AttributeError:
680
+ cast(Any, obj).__exclude_fields__ = {"_request_id", "__exclude_fields__"}
681
+ else:
682
+ cast(Any, obj).__exclude_fields__ = {
683
+ *(exclude_fields or {}),
684
+ "_request_id",
685
+ "__exclude_fields__",
686
+ }
687
+
688
+
689
+ # our use of subclasssing here causes weirdness for type checkers,
690
+ # so we just pretend that we don't subclass
691
+ if TYPE_CHECKING:
692
+ GenericModel = BaseModel
693
+ else:
694
+
695
+ class GenericModel(BaseGenericModel, BaseModel):
696
+ pass
697
+
698
+
699
+ if PYDANTIC_V2:
700
+ from pydantic import TypeAdapter as _TypeAdapter
701
+
702
+ _CachedTypeAdapter = cast(
703
+ "TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter)
704
+ )
705
+
706
+ if TYPE_CHECKING:
707
+ from pydantic import TypeAdapter
708
+ else:
709
+ TypeAdapter = _CachedTypeAdapter
710
+
711
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
712
+ return TypeAdapter(type_).validate_python(value)
713
+
714
+ elif not TYPE_CHECKING: # TODO: condition is weird
715
+
716
+ class RootModel(GenericModel, Generic[_T]):
717
+ """Used as a placeholder to easily convert runtime types to a Pydantic format
718
+ to provide validation.
719
+
720
+ For example:
721
+ ```py
722
+ validated = RootModel[int](__root__="5").__root__
723
+ # validated: 5
724
+ ```
725
+ """
726
+
727
+ __root__: _T
728
+
729
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
730
+ model = _create_pydantic_model(type_).validate(value)
731
+ return cast(_T, model.__root__)
732
+
733
+ def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]:
734
+ return RootModel[type_] # type: ignore