c63a5cfe-b235-4fbe-8bbb-82a9e02a482a-python 0.1.0a3__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 (190) hide show
  1. c63a5cfe_b235_4fbe_8bbb_82a9e02a482a_python-0.1.0a3.dist-info/METADATA +396 -0
  2. c63a5cfe_b235_4fbe_8bbb_82a9e02a482a_python-0.1.0a3.dist-info/RECORD +190 -0
  3. c63a5cfe_b235_4fbe_8bbb_82a9e02a482a_python-0.1.0a3.dist-info/WHEEL +4 -0
  4. c63a5cfe_b235_4fbe_8bbb_82a9e02a482a_python-0.1.0a3.dist-info/licenses/LICENSE +201 -0
  5. digitalocean_genai_sdk/__init__.py +99 -0
  6. digitalocean_genai_sdk/_base_client.py +1949 -0
  7. digitalocean_genai_sdk/_client.py +795 -0
  8. digitalocean_genai_sdk/_compat.py +219 -0
  9. digitalocean_genai_sdk/_constants.py +14 -0
  10. digitalocean_genai_sdk/_exceptions.py +108 -0
  11. digitalocean_genai_sdk/_files.py +123 -0
  12. digitalocean_genai_sdk/_models.py +805 -0
  13. digitalocean_genai_sdk/_qs.py +150 -0
  14. digitalocean_genai_sdk/_resource.py +43 -0
  15. digitalocean_genai_sdk/_response.py +832 -0
  16. digitalocean_genai_sdk/_streaming.py +333 -0
  17. digitalocean_genai_sdk/_types.py +219 -0
  18. digitalocean_genai_sdk/_utils/__init__.py +57 -0
  19. digitalocean_genai_sdk/_utils/_logs.py +25 -0
  20. digitalocean_genai_sdk/_utils/_proxy.py +65 -0
  21. digitalocean_genai_sdk/_utils/_reflection.py +42 -0
  22. digitalocean_genai_sdk/_utils/_resources_proxy.py +24 -0
  23. digitalocean_genai_sdk/_utils/_streams.py +12 -0
  24. digitalocean_genai_sdk/_utils/_sync.py +86 -0
  25. digitalocean_genai_sdk/_utils/_transform.py +447 -0
  26. digitalocean_genai_sdk/_utils/_typing.py +151 -0
  27. digitalocean_genai_sdk/_utils/_utils.py +422 -0
  28. digitalocean_genai_sdk/_version.py +4 -0
  29. digitalocean_genai_sdk/lib/.keep +4 -0
  30. digitalocean_genai_sdk/py.typed +0 -0
  31. digitalocean_genai_sdk/resources/__init__.py +145 -0
  32. digitalocean_genai_sdk/resources/agents/__init__.py +89 -0
  33. digitalocean_genai_sdk/resources/agents/agents.py +965 -0
  34. digitalocean_genai_sdk/resources/agents/api_keys.py +581 -0
  35. digitalocean_genai_sdk/resources/agents/child_agents.py +508 -0
  36. digitalocean_genai_sdk/resources/agents/functions.py +421 -0
  37. digitalocean_genai_sdk/resources/agents/knowledge_bases.py +346 -0
  38. digitalocean_genai_sdk/resources/agents/versions.py +298 -0
  39. digitalocean_genai_sdk/resources/api_keys/__init__.py +19 -0
  40. digitalocean_genai_sdk/resources/api_keys/api_keys.py +275 -0
  41. digitalocean_genai_sdk/resources/api_keys/api_keys_.py +529 -0
  42. digitalocean_genai_sdk/resources/auth/__init__.py +33 -0
  43. digitalocean_genai_sdk/resources/auth/agents/__init__.py +33 -0
  44. digitalocean_genai_sdk/resources/auth/agents/agents.py +102 -0
  45. digitalocean_genai_sdk/resources/auth/agents/token.py +173 -0
  46. digitalocean_genai_sdk/resources/auth/auth.py +102 -0
  47. digitalocean_genai_sdk/resources/chat.py +381 -0
  48. digitalocean_genai_sdk/resources/embeddings.py +201 -0
  49. digitalocean_genai_sdk/resources/indexing_jobs.py +543 -0
  50. digitalocean_genai_sdk/resources/knowledge_bases/__init__.py +33 -0
  51. digitalocean_genai_sdk/resources/knowledge_bases/data_sources.py +410 -0
  52. digitalocean_genai_sdk/resources/knowledge_bases/knowledge_bases.py +667 -0
  53. digitalocean_genai_sdk/resources/models.py +222 -0
  54. digitalocean_genai_sdk/resources/providers/__init__.py +47 -0
  55. digitalocean_genai_sdk/resources/providers/anthropic/__init__.py +33 -0
  56. digitalocean_genai_sdk/resources/providers/anthropic/anthropic.py +102 -0
  57. digitalocean_genai_sdk/resources/providers/anthropic/keys.py +662 -0
  58. digitalocean_genai_sdk/resources/providers/openai/__init__.py +33 -0
  59. digitalocean_genai_sdk/resources/providers/openai/keys.py +658 -0
  60. digitalocean_genai_sdk/resources/providers/openai/openai.py +102 -0
  61. digitalocean_genai_sdk/resources/providers/providers.py +134 -0
  62. digitalocean_genai_sdk/resources/regions.py +191 -0
  63. digitalocean_genai_sdk/types/__init__.py +57 -0
  64. digitalocean_genai_sdk/types/agent_create_params.py +39 -0
  65. digitalocean_genai_sdk/types/agent_create_response.py +16 -0
  66. digitalocean_genai_sdk/types/agent_delete_response.py +16 -0
  67. digitalocean_genai_sdk/types/agent_list_params.py +18 -0
  68. digitalocean_genai_sdk/types/agent_list_response.py +198 -0
  69. digitalocean_genai_sdk/types/agent_retrieve_response.py +16 -0
  70. digitalocean_genai_sdk/types/agent_update_params.py +65 -0
  71. digitalocean_genai_sdk/types/agent_update_response.py +16 -0
  72. digitalocean_genai_sdk/types/agent_update_status_params.py +16 -0
  73. digitalocean_genai_sdk/types/agent_update_status_response.py +16 -0
  74. digitalocean_genai_sdk/types/agents/__init__.py +31 -0
  75. digitalocean_genai_sdk/types/agents/api_key_create_params.py +15 -0
  76. digitalocean_genai_sdk/types/agents/api_key_create_response.py +12 -0
  77. digitalocean_genai_sdk/types/agents/api_key_delete_response.py +12 -0
  78. digitalocean_genai_sdk/types/agents/api_key_list_params.py +15 -0
  79. digitalocean_genai_sdk/types/agents/api_key_list_response.py +18 -0
  80. digitalocean_genai_sdk/types/agents/api_key_regenerate_response.py +12 -0
  81. digitalocean_genai_sdk/types/agents/api_key_update_params.py +19 -0
  82. digitalocean_genai_sdk/types/agents/api_key_update_response.py +12 -0
  83. digitalocean_genai_sdk/types/agents/api_link_knowledge_base_output.py +16 -0
  84. digitalocean_genai_sdk/types/agents/api_links.py +21 -0
  85. digitalocean_genai_sdk/types/agents/api_meta.py +15 -0
  86. digitalocean_genai_sdk/types/agents/child_agent_add_params.py +22 -0
  87. digitalocean_genai_sdk/types/agents/child_agent_add_response.py +14 -0
  88. digitalocean_genai_sdk/types/agents/child_agent_delete_response.py +13 -0
  89. digitalocean_genai_sdk/types/agents/child_agent_update_params.py +24 -0
  90. digitalocean_genai_sdk/types/agents/child_agent_update_response.py +18 -0
  91. digitalocean_genai_sdk/types/agents/child_agent_view_response.py +16 -0
  92. digitalocean_genai_sdk/types/agents/function_create_params.py +25 -0
  93. digitalocean_genai_sdk/types/agents/function_create_response.py +16 -0
  94. digitalocean_genai_sdk/types/agents/function_delete_response.py +16 -0
  95. digitalocean_genai_sdk/types/agents/function_update_params.py +29 -0
  96. digitalocean_genai_sdk/types/agents/function_update_response.py +16 -0
  97. digitalocean_genai_sdk/types/agents/knowledge_base_detach_response.py +16 -0
  98. digitalocean_genai_sdk/types/agents/version_list_params.py +15 -0
  99. digitalocean_genai_sdk/types/agents/version_list_response.py +118 -0
  100. digitalocean_genai_sdk/types/agents/version_update_params.py +15 -0
  101. digitalocean_genai_sdk/types/agents/version_update_response.py +30 -0
  102. digitalocean_genai_sdk/types/api_agent.py +263 -0
  103. digitalocean_genai_sdk/types/api_agent_api_key_info.py +22 -0
  104. digitalocean_genai_sdk/types/api_agreement.py +17 -0
  105. digitalocean_genai_sdk/types/api_anthropic_api_key_info.py +22 -0
  106. digitalocean_genai_sdk/types/api_deployment_visibility.py +9 -0
  107. digitalocean_genai_sdk/types/api_indexing_job.py +43 -0
  108. digitalocean_genai_sdk/types/api_key_list_params.py +42 -0
  109. digitalocean_genai_sdk/types/api_key_list_response.py +42 -0
  110. digitalocean_genai_sdk/types/api_keys/__init__.py +13 -0
  111. digitalocean_genai_sdk/types/api_keys/api_key_create_params.py +11 -0
  112. digitalocean_genai_sdk/types/api_keys/api_key_create_response.py +12 -0
  113. digitalocean_genai_sdk/types/api_keys/api_key_delete_response.py +12 -0
  114. digitalocean_genai_sdk/types/api_keys/api_key_list_params.py +15 -0
  115. digitalocean_genai_sdk/types/api_keys/api_key_list_response.py +18 -0
  116. digitalocean_genai_sdk/types/api_keys/api_key_update_params.py +15 -0
  117. digitalocean_genai_sdk/types/api_keys/api_key_update_regenerate_response.py +12 -0
  118. digitalocean_genai_sdk/types/api_keys/api_key_update_response.py +12 -0
  119. digitalocean_genai_sdk/types/api_keys/api_model_api_key_info.py +22 -0
  120. digitalocean_genai_sdk/types/api_knowledge_base.py +37 -0
  121. digitalocean_genai_sdk/types/api_model.py +57 -0
  122. digitalocean_genai_sdk/types/api_model_version.py +15 -0
  123. digitalocean_genai_sdk/types/api_openai_api_key_info.py +25 -0
  124. digitalocean_genai_sdk/types/api_retrieval_method.py +13 -0
  125. digitalocean_genai_sdk/types/auth/__init__.py +3 -0
  126. digitalocean_genai_sdk/types/auth/agents/__init__.py +6 -0
  127. digitalocean_genai_sdk/types/auth/agents/token_create_params.py +13 -0
  128. digitalocean_genai_sdk/types/auth/agents/token_create_response.py +13 -0
  129. digitalocean_genai_sdk/types/chat_completion_request_message_content_part_text_param.py +15 -0
  130. digitalocean_genai_sdk/types/chat_completion_token_logprob.py +57 -0
  131. digitalocean_genai_sdk/types/chat_create_completion_params.py +208 -0
  132. digitalocean_genai_sdk/types/chat_create_completion_response.py +81 -0
  133. digitalocean_genai_sdk/types/embedding_create_params.py +28 -0
  134. digitalocean_genai_sdk/types/embedding_create_response.py +41 -0
  135. digitalocean_genai_sdk/types/indexing_job_create_params.py +14 -0
  136. digitalocean_genai_sdk/types/indexing_job_create_response.py +12 -0
  137. digitalocean_genai_sdk/types/indexing_job_list_params.py +15 -0
  138. digitalocean_genai_sdk/types/indexing_job_list_response.py +18 -0
  139. digitalocean_genai_sdk/types/indexing_job_retrieve_data_sources_response.py +52 -0
  140. digitalocean_genai_sdk/types/indexing_job_retrieve_response.py +12 -0
  141. digitalocean_genai_sdk/types/indexing_job_update_cancel_params.py +14 -0
  142. digitalocean_genai_sdk/types/indexing_job_update_cancel_response.py +12 -0
  143. digitalocean_genai_sdk/types/knowledge_base_create_params.py +64 -0
  144. digitalocean_genai_sdk/types/knowledge_base_create_response.py +12 -0
  145. digitalocean_genai_sdk/types/knowledge_base_delete_response.py +11 -0
  146. digitalocean_genai_sdk/types/knowledge_base_list_params.py +15 -0
  147. digitalocean_genai_sdk/types/knowledge_base_list_response.py +18 -0
  148. digitalocean_genai_sdk/types/knowledge_base_retrieve_response.py +30 -0
  149. digitalocean_genai_sdk/types/knowledge_base_update_params.py +27 -0
  150. digitalocean_genai_sdk/types/knowledge_base_update_response.py +12 -0
  151. digitalocean_genai_sdk/types/knowledge_bases/__init__.py +16 -0
  152. digitalocean_genai_sdk/types/knowledge_bases/api_file_upload_data_source.py +15 -0
  153. digitalocean_genai_sdk/types/knowledge_bases/api_file_upload_data_source_param.py +15 -0
  154. digitalocean_genai_sdk/types/knowledge_bases/api_knowledge_base_data_source.py +35 -0
  155. digitalocean_genai_sdk/types/knowledge_bases/api_spaces_data_source.py +15 -0
  156. digitalocean_genai_sdk/types/knowledge_bases/api_spaces_data_source_param.py +15 -0
  157. digitalocean_genai_sdk/types/knowledge_bases/api_web_crawler_data_source.py +26 -0
  158. digitalocean_genai_sdk/types/knowledge_bases/api_web_crawler_data_source_param.py +25 -0
  159. digitalocean_genai_sdk/types/knowledge_bases/data_source_create_params.py +33 -0
  160. digitalocean_genai_sdk/types/knowledge_bases/data_source_create_response.py +12 -0
  161. digitalocean_genai_sdk/types/knowledge_bases/data_source_delete_response.py +13 -0
  162. digitalocean_genai_sdk/types/knowledge_bases/data_source_list_params.py +15 -0
  163. digitalocean_genai_sdk/types/knowledge_bases/data_source_list_response.py +18 -0
  164. digitalocean_genai_sdk/types/model.py +21 -0
  165. digitalocean_genai_sdk/types/model_list_response.py +15 -0
  166. digitalocean_genai_sdk/types/providers/__init__.py +3 -0
  167. digitalocean_genai_sdk/types/providers/anthropic/__init__.py +14 -0
  168. digitalocean_genai_sdk/types/providers/anthropic/key_create_params.py +13 -0
  169. digitalocean_genai_sdk/types/providers/anthropic/key_create_response.py +12 -0
  170. digitalocean_genai_sdk/types/providers/anthropic/key_delete_response.py +12 -0
  171. digitalocean_genai_sdk/types/providers/anthropic/key_list_agents_params.py +15 -0
  172. digitalocean_genai_sdk/types/providers/anthropic/key_list_agents_response.py +22 -0
  173. digitalocean_genai_sdk/types/providers/anthropic/key_list_params.py +15 -0
  174. digitalocean_genai_sdk/types/providers/anthropic/key_list_response.py +18 -0
  175. digitalocean_genai_sdk/types/providers/anthropic/key_retrieve_response.py +12 -0
  176. digitalocean_genai_sdk/types/providers/anthropic/key_update_params.py +17 -0
  177. digitalocean_genai_sdk/types/providers/anthropic/key_update_response.py +12 -0
  178. digitalocean_genai_sdk/types/providers/openai/__init__.py +14 -0
  179. digitalocean_genai_sdk/types/providers/openai/key_create_params.py +13 -0
  180. digitalocean_genai_sdk/types/providers/openai/key_create_response.py +12 -0
  181. digitalocean_genai_sdk/types/providers/openai/key_delete_response.py +12 -0
  182. digitalocean_genai_sdk/types/providers/openai/key_list_params.py +15 -0
  183. digitalocean_genai_sdk/types/providers/openai/key_list_response.py +18 -0
  184. digitalocean_genai_sdk/types/providers/openai/key_retrieve_agents_params.py +15 -0
  185. digitalocean_genai_sdk/types/providers/openai/key_retrieve_agents_response.py +22 -0
  186. digitalocean_genai_sdk/types/providers/openai/key_retrieve_response.py +12 -0
  187. digitalocean_genai_sdk/types/providers/openai/key_update_params.py +17 -0
  188. digitalocean_genai_sdk/types/providers/openai/key_update_response.py +12 -0
  189. digitalocean_genai_sdk/types/region_list_params.py +15 -0
  190. digitalocean_genai_sdk/types/region_list_response.py +23 -0
@@ -0,0 +1,805 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, cast
6
+ from datetime import date, datetime
7
+ from typing_extensions import (
8
+ Unpack,
9
+ Literal,
10
+ ClassVar,
11
+ Protocol,
12
+ Required,
13
+ ParamSpec,
14
+ TypedDict,
15
+ TypeGuard,
16
+ final,
17
+ override,
18
+ runtime_checkable,
19
+ )
20
+
21
+ import pydantic
22
+ from pydantic.fields import FieldInfo
23
+
24
+ from ._types import (
25
+ Body,
26
+ IncEx,
27
+ Query,
28
+ ModelT,
29
+ Headers,
30
+ Timeout,
31
+ NotGiven,
32
+ AnyMapping,
33
+ HttpxRequestFiles,
34
+ )
35
+ from ._utils import (
36
+ PropertyInfo,
37
+ is_list,
38
+ is_given,
39
+ json_safe,
40
+ lru_cache,
41
+ is_mapping,
42
+ parse_date,
43
+ coerce_boolean,
44
+ parse_datetime,
45
+ strip_not_given,
46
+ extract_type_arg,
47
+ is_annotated_type,
48
+ is_type_alias_type,
49
+ strip_annotated_type,
50
+ )
51
+ from ._compat import (
52
+ PYDANTIC_V2,
53
+ ConfigDict,
54
+ GenericModel as BaseGenericModel,
55
+ get_args,
56
+ is_union,
57
+ parse_obj,
58
+ get_origin,
59
+ is_literal_type,
60
+ get_model_config,
61
+ get_model_fields,
62
+ field_get_default,
63
+ )
64
+ from ._constants import RAW_RESPONSE_HEADER
65
+
66
+ if TYPE_CHECKING:
67
+ from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema
68
+
69
+ __all__ = ["BaseModel", "GenericModel"]
70
+
71
+ _T = TypeVar("_T")
72
+ _BaseModelT = TypeVar("_BaseModelT", bound="BaseModel")
73
+
74
+ P = ParamSpec("P")
75
+
76
+
77
+ @runtime_checkable
78
+ class _ConfigProtocol(Protocol):
79
+ allow_population_by_field_name: bool
80
+
81
+
82
+ class BaseModel(pydantic.BaseModel):
83
+ if PYDANTIC_V2:
84
+ model_config: ClassVar[ConfigDict] = ConfigDict(
85
+ extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
86
+ )
87
+ else:
88
+
89
+ @property
90
+ @override
91
+ def model_fields_set(self) -> set[str]:
92
+ # a forwards-compat shim for pydantic v2
93
+ return self.__fields_set__ # type: ignore
94
+
95
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
96
+ extra: Any = pydantic.Extra.allow # type: ignore
97
+
98
+ def to_dict(
99
+ self,
100
+ *,
101
+ mode: Literal["json", "python"] = "python",
102
+ use_api_names: bool = True,
103
+ exclude_unset: bool = True,
104
+ exclude_defaults: bool = False,
105
+ exclude_none: bool = False,
106
+ warnings: bool = True,
107
+ ) -> dict[str, object]:
108
+ """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
109
+
110
+ By default, fields that were not set by the API will not be included,
111
+ and keys will match the API response, *not* the property names from the model.
112
+
113
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
114
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
115
+
116
+ Args:
117
+ mode:
118
+ 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"`.
119
+ If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
120
+
121
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
122
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
123
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
124
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
125
+ warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
126
+ """
127
+ return self.model_dump(
128
+ mode=mode,
129
+ by_alias=use_api_names,
130
+ exclude_unset=exclude_unset,
131
+ exclude_defaults=exclude_defaults,
132
+ exclude_none=exclude_none,
133
+ warnings=warnings,
134
+ )
135
+
136
+ def to_json(
137
+ self,
138
+ *,
139
+ indent: int | None = 2,
140
+ use_api_names: bool = True,
141
+ exclude_unset: bool = True,
142
+ exclude_defaults: bool = False,
143
+ exclude_none: bool = False,
144
+ warnings: bool = True,
145
+ ) -> str:
146
+ """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
147
+
148
+ By default, fields that were not set by the API will not be included,
149
+ and keys will match the API response, *not* the property names from the model.
150
+
151
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
152
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
153
+
154
+ Args:
155
+ indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
156
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
157
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
158
+ exclude_defaults: Whether to exclude fields that have the default value.
159
+ exclude_none: Whether to exclude fields that have a value of `None`.
160
+ warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
161
+ """
162
+ return self.model_dump_json(
163
+ indent=indent,
164
+ by_alias=use_api_names,
165
+ exclude_unset=exclude_unset,
166
+ exclude_defaults=exclude_defaults,
167
+ exclude_none=exclude_none,
168
+ warnings=warnings,
169
+ )
170
+
171
+ @override
172
+ def __str__(self) -> str:
173
+ # mypy complains about an invalid self arg
174
+ return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc]
175
+
176
+ # Override the 'construct' method in a way that supports recursive parsing without validation.
177
+ # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
178
+ @classmethod
179
+ @override
180
+ def construct( # pyright: ignore[reportIncompatibleMethodOverride]
181
+ __cls: Type[ModelT],
182
+ _fields_set: set[str] | None = None,
183
+ **values: object,
184
+ ) -> ModelT:
185
+ m = __cls.__new__(__cls)
186
+ fields_values: dict[str, object] = {}
187
+
188
+ config = get_model_config(__cls)
189
+ populate_by_name = (
190
+ config.allow_population_by_field_name
191
+ if isinstance(config, _ConfigProtocol)
192
+ else config.get("populate_by_name")
193
+ )
194
+
195
+ if _fields_set is None:
196
+ _fields_set = set()
197
+
198
+ model_fields = get_model_fields(__cls)
199
+ for name, field in model_fields.items():
200
+ key = field.alias
201
+ if key is None or (key not in values and populate_by_name):
202
+ key = name
203
+
204
+ if key in values:
205
+ fields_values[name] = _construct_field(value=values[key], field=field, key=key)
206
+ _fields_set.add(name)
207
+ else:
208
+ fields_values[name] = field_get_default(field)
209
+
210
+ _extra = {}
211
+ for key, value in values.items():
212
+ if key not in model_fields:
213
+ if PYDANTIC_V2:
214
+ _extra[key] = value
215
+ else:
216
+ _fields_set.add(key)
217
+ fields_values[key] = value
218
+
219
+ object.__setattr__(m, "__dict__", fields_values)
220
+
221
+ if PYDANTIC_V2:
222
+ # these properties are copied from Pydantic's `model_construct()` method
223
+ object.__setattr__(m, "__pydantic_private__", None)
224
+ object.__setattr__(m, "__pydantic_extra__", _extra)
225
+ object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
226
+ else:
227
+ # init_private_attributes() does not exist in v2
228
+ m._init_private_attributes() # type: ignore
229
+
230
+ # copied from Pydantic v1's `construct()` method
231
+ object.__setattr__(m, "__fields_set__", _fields_set)
232
+
233
+ return m
234
+
235
+ if not TYPE_CHECKING:
236
+ # type checkers incorrectly complain about this assignment
237
+ # because the type signatures are technically different
238
+ # although not in practice
239
+ model_construct = construct
240
+
241
+ if not PYDANTIC_V2:
242
+ # we define aliases for some of the new pydantic v2 methods so
243
+ # that we can just document these methods without having to specify
244
+ # a specific pydantic version as some users may not know which
245
+ # pydantic version they are currently using
246
+
247
+ @override
248
+ def model_dump(
249
+ self,
250
+ *,
251
+ mode: Literal["json", "python"] | str = "python",
252
+ include: IncEx | None = None,
253
+ exclude: IncEx | None = None,
254
+ by_alias: bool = False,
255
+ exclude_unset: bool = False,
256
+ exclude_defaults: bool = False,
257
+ exclude_none: bool = False,
258
+ round_trip: bool = False,
259
+ warnings: bool | Literal["none", "warn", "error"] = True,
260
+ context: dict[str, Any] | None = None,
261
+ serialize_as_any: bool = False,
262
+ ) -> dict[str, Any]:
263
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
264
+
265
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
266
+
267
+ Args:
268
+ mode: The mode in which `to_python` should run.
269
+ If mode is 'json', the dictionary will only contain JSON serializable types.
270
+ If mode is 'python', the dictionary may contain any Python objects.
271
+ include: A list of fields to include in the output.
272
+ exclude: A list of fields to exclude from the output.
273
+ by_alias: Whether to use the field's alias in the dictionary key if defined.
274
+ exclude_unset: Whether to exclude fields that are unset or None from the output.
275
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
276
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
277
+ round_trip: Whether to enable serialization and deserialization round-trip support.
278
+ warnings: Whether to log warnings when invalid fields are encountered.
279
+
280
+ Returns:
281
+ A dictionary representation of the model.
282
+ """
283
+ if mode not in {"json", "python"}:
284
+ raise ValueError("mode must be either 'json' or 'python'")
285
+ if round_trip != False:
286
+ raise ValueError("round_trip is only supported in Pydantic v2")
287
+ if warnings != True:
288
+ raise ValueError("warnings is only supported in Pydantic v2")
289
+ if context is not None:
290
+ raise ValueError("context is only supported in Pydantic v2")
291
+ if serialize_as_any != False:
292
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
293
+ dumped = super().dict( # pyright: ignore[reportDeprecated]
294
+ include=include,
295
+ exclude=exclude,
296
+ by_alias=by_alias,
297
+ exclude_unset=exclude_unset,
298
+ exclude_defaults=exclude_defaults,
299
+ exclude_none=exclude_none,
300
+ )
301
+
302
+ return cast(dict[str, Any], json_safe(dumped)) if mode == "json" else dumped
303
+
304
+ @override
305
+ def model_dump_json(
306
+ self,
307
+ *,
308
+ indent: int | None = None,
309
+ include: IncEx | None = None,
310
+ exclude: IncEx | None = None,
311
+ by_alias: bool = False,
312
+ exclude_unset: bool = False,
313
+ exclude_defaults: bool = False,
314
+ exclude_none: bool = False,
315
+ round_trip: bool = False,
316
+ warnings: bool | Literal["none", "warn", "error"] = True,
317
+ context: dict[str, Any] | None = None,
318
+ serialize_as_any: bool = False,
319
+ ) -> str:
320
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
321
+
322
+ Generates a JSON representation of the model using Pydantic's `to_json` method.
323
+
324
+ Args:
325
+ indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
326
+ include: Field(s) to include in the JSON output. Can take either a string or set of strings.
327
+ exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings.
328
+ by_alias: Whether to serialize using field aliases.
329
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
330
+ exclude_defaults: Whether to exclude fields that have the default value.
331
+ exclude_none: Whether to exclude fields that have a value of `None`.
332
+ round_trip: Whether to use serialization/deserialization between JSON and class instance.
333
+ warnings: Whether to show any warnings that occurred during serialization.
334
+
335
+ Returns:
336
+ A JSON string representation of the model.
337
+ """
338
+ if round_trip != False:
339
+ raise ValueError("round_trip is only supported in Pydantic v2")
340
+ if warnings != True:
341
+ raise ValueError("warnings is only supported in Pydantic v2")
342
+ if context is not None:
343
+ raise ValueError("context is only supported in Pydantic v2")
344
+ if serialize_as_any != False:
345
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
346
+ return super().json( # type: ignore[reportDeprecated]
347
+ indent=indent,
348
+ include=include,
349
+ exclude=exclude,
350
+ by_alias=by_alias,
351
+ exclude_unset=exclude_unset,
352
+ exclude_defaults=exclude_defaults,
353
+ exclude_none=exclude_none,
354
+ )
355
+
356
+
357
+ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
358
+ if value is None:
359
+ return field_get_default(field)
360
+
361
+ if PYDANTIC_V2:
362
+ type_ = field.annotation
363
+ else:
364
+ type_ = cast(type, field.outer_type_) # type: ignore
365
+
366
+ if type_ is None:
367
+ raise RuntimeError(f"Unexpected field type is None for {key}")
368
+
369
+ return construct_type(value=value, type_=type_)
370
+
371
+
372
+ def is_basemodel(type_: type) -> bool:
373
+ """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
374
+ if is_union(type_):
375
+ for variant in get_args(type_):
376
+ if is_basemodel(variant):
377
+ return True
378
+
379
+ return False
380
+
381
+ return is_basemodel_type(type_)
382
+
383
+
384
+ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
385
+ origin = get_origin(type_) or type_
386
+ if not inspect.isclass(origin):
387
+ return False
388
+ return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
389
+
390
+
391
+ def build(
392
+ base_model_cls: Callable[P, _BaseModelT],
393
+ *args: P.args,
394
+ **kwargs: P.kwargs,
395
+ ) -> _BaseModelT:
396
+ """Construct a BaseModel class without validation.
397
+
398
+ This is useful for cases where you need to instantiate a `BaseModel`
399
+ from an API response as this provides type-safe params which isn't supported
400
+ by helpers like `construct_type()`.
401
+
402
+ ```py
403
+ build(MyModel, my_field_a="foo", my_field_b=123)
404
+ ```
405
+ """
406
+ if args:
407
+ raise TypeError(
408
+ "Received positional arguments which are not supported; Keyword arguments must be used instead",
409
+ )
410
+
411
+ return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs))
412
+
413
+
414
+ def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T:
415
+ """Loose coercion to the expected type with construction of nested values.
416
+
417
+ Note: the returned value from this function is not guaranteed to match the
418
+ given type.
419
+ """
420
+ return cast(_T, construct_type(value=value, type_=type_))
421
+
422
+
423
+ def construct_type(*, value: object, type_: object) -> object:
424
+ """Loose coercion to the expected type with construction of nested values.
425
+
426
+ If the given value does not match the expected type then it is returned as-is.
427
+ """
428
+
429
+ # store a reference to the original type we were given before we extract any inner
430
+ # types so that we can properly resolve forward references in `TypeAliasType` annotations
431
+ original_type = None
432
+
433
+ # we allow `object` as the input type because otherwise, passing things like
434
+ # `Literal['value']` will be reported as a type error by type checkers
435
+ type_ = cast("type[object]", type_)
436
+ if is_type_alias_type(type_):
437
+ original_type = type_ # type: ignore[unreachable]
438
+ type_ = type_.__value__ # type: ignore[unreachable]
439
+
440
+ # unwrap `Annotated[T, ...]` -> `T`
441
+ if is_annotated_type(type_):
442
+ meta: tuple[Any, ...] = get_args(type_)[1:]
443
+ type_ = extract_type_arg(type_, 0)
444
+ else:
445
+ meta = tuple()
446
+
447
+ # we need to use the origin class for any types that are subscripted generics
448
+ # e.g. Dict[str, object]
449
+ origin = get_origin(type_) or type_
450
+ args = get_args(type_)
451
+
452
+ if is_union(origin):
453
+ try:
454
+ return validate_type(type_=cast("type[object]", original_type or type_), value=value)
455
+ except Exception:
456
+ pass
457
+
458
+ # if the type is a discriminated union then we want to construct the right variant
459
+ # in the union, even if the data doesn't match exactly, otherwise we'd break code
460
+ # that relies on the constructed class types, e.g.
461
+ #
462
+ # class FooType:
463
+ # kind: Literal['foo']
464
+ # value: str
465
+ #
466
+ # class BarType:
467
+ # kind: Literal['bar']
468
+ # value: int
469
+ #
470
+ # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then
471
+ # we'd end up constructing `FooType` when it should be `BarType`.
472
+ discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta)
473
+ if discriminator and is_mapping(value):
474
+ variant_value = value.get(discriminator.field_alias_from or discriminator.field_name)
475
+ if variant_value and isinstance(variant_value, str):
476
+ variant_type = discriminator.mapping.get(variant_value)
477
+ if variant_type:
478
+ return construct_type(type_=variant_type, value=value)
479
+
480
+ # if the data is not valid, use the first variant that doesn't fail while deserializing
481
+ for variant in args:
482
+ try:
483
+ return construct_type(value=value, type_=variant)
484
+ except Exception:
485
+ continue
486
+
487
+ raise RuntimeError(f"Could not convert data into a valid instance of {type_}")
488
+
489
+ if origin == dict:
490
+ if not is_mapping(value):
491
+ return value
492
+
493
+ _, items_type = get_args(type_) # Dict[_, items_type]
494
+ return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
495
+
496
+ if (
497
+ not is_literal_type(type_)
498
+ and inspect.isclass(origin)
499
+ and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel))
500
+ ):
501
+ if is_list(value):
502
+ return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value]
503
+
504
+ if is_mapping(value):
505
+ if issubclass(type_, BaseModel):
506
+ return type_.construct(**value) # type: ignore[arg-type]
507
+
508
+ return cast(Any, type_).construct(**value)
509
+
510
+ if origin == list:
511
+ if not is_list(value):
512
+ return value
513
+
514
+ inner_type = args[0] # List[inner_type]
515
+ return [construct_type(value=entry, type_=inner_type) for entry in value]
516
+
517
+ if origin == float:
518
+ if isinstance(value, int):
519
+ coerced = float(value)
520
+ if coerced != value:
521
+ return value
522
+ return coerced
523
+
524
+ return value
525
+
526
+ if type_ == datetime:
527
+ try:
528
+ return parse_datetime(value) # type: ignore
529
+ except Exception:
530
+ return value
531
+
532
+ if type_ == date:
533
+ try:
534
+ return parse_date(value) # type: ignore
535
+ except Exception:
536
+ return value
537
+
538
+ return value
539
+
540
+
541
+ @runtime_checkable
542
+ class CachedDiscriminatorType(Protocol):
543
+ __discriminator__: DiscriminatorDetails
544
+
545
+
546
+ class DiscriminatorDetails:
547
+ field_name: str
548
+ """The name of the discriminator field in the variant class, e.g.
549
+
550
+ ```py
551
+ class Foo(BaseModel):
552
+ type: Literal['foo']
553
+ ```
554
+
555
+ Will result in field_name='type'
556
+ """
557
+
558
+ field_alias_from: str | None
559
+ """The name of the discriminator field in the API response, e.g.
560
+
561
+ ```py
562
+ class Foo(BaseModel):
563
+ type: Literal['foo'] = Field(alias='type_from_api')
564
+ ```
565
+
566
+ Will result in field_alias_from='type_from_api'
567
+ """
568
+
569
+ mapping: dict[str, type]
570
+ """Mapping of discriminator value to variant type, e.g.
571
+
572
+ {'foo': FooVariant, 'bar': BarVariant}
573
+ """
574
+
575
+ def __init__(
576
+ self,
577
+ *,
578
+ mapping: dict[str, type],
579
+ discriminator_field: str,
580
+ discriminator_alias: str | None,
581
+ ) -> None:
582
+ self.mapping = mapping
583
+ self.field_name = discriminator_field
584
+ self.field_alias_from = discriminator_alias
585
+
586
+
587
+ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
588
+ if isinstance(union, CachedDiscriminatorType):
589
+ return union.__discriminator__
590
+
591
+ discriminator_field_name: str | None = None
592
+
593
+ for annotation in meta_annotations:
594
+ if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None:
595
+ discriminator_field_name = annotation.discriminator
596
+ break
597
+
598
+ if not discriminator_field_name:
599
+ return None
600
+
601
+ mapping: dict[str, type] = {}
602
+ discriminator_alias: str | None = None
603
+
604
+ for variant in get_args(union):
605
+ variant = strip_annotated_type(variant)
606
+ if is_basemodel_type(variant):
607
+ if PYDANTIC_V2:
608
+ field = _extract_field_schema_pv2(variant, discriminator_field_name)
609
+ if not field:
610
+ continue
611
+
612
+ # Note: if one variant defines an alias then they all should
613
+ discriminator_alias = field.get("serialization_alias")
614
+
615
+ field_schema = field["schema"]
616
+
617
+ if field_schema["type"] == "literal":
618
+ for entry in cast("LiteralSchema", field_schema)["expected"]:
619
+ if isinstance(entry, str):
620
+ mapping[entry] = variant
621
+ else:
622
+ field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
623
+ if not field_info:
624
+ continue
625
+
626
+ # Note: if one variant defines an alias then they all should
627
+ discriminator_alias = field_info.alias
628
+
629
+ if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation):
630
+ for entry in get_args(annotation):
631
+ if isinstance(entry, str):
632
+ mapping[entry] = variant
633
+
634
+ if not mapping:
635
+ return None
636
+
637
+ details = DiscriminatorDetails(
638
+ mapping=mapping,
639
+ discriminator_field=discriminator_field_name,
640
+ discriminator_alias=discriminator_alias,
641
+ )
642
+ cast(CachedDiscriminatorType, union).__discriminator__ = details
643
+ return details
644
+
645
+
646
+ def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None:
647
+ schema = model.__pydantic_core_schema__
648
+ if schema["type"] == "definitions":
649
+ schema = schema["schema"]
650
+
651
+ if schema["type"] != "model":
652
+ return None
653
+
654
+ schema = cast("ModelSchema", schema)
655
+ fields_schema = schema["schema"]
656
+ if fields_schema["type"] != "model-fields":
657
+ return None
658
+
659
+ fields_schema = cast("ModelFieldsSchema", fields_schema)
660
+ field = fields_schema["fields"].get(field_name)
661
+ if not field:
662
+ return None
663
+
664
+ return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast]
665
+
666
+
667
+ def validate_type(*, type_: type[_T], value: object) -> _T:
668
+ """Strict validation that the given value matches the expected type"""
669
+ if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
670
+ return cast(_T, parse_obj(type_, value))
671
+
672
+ return cast(_T, _validate_non_model_type(type_=type_, value=value))
673
+
674
+
675
+ def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None:
676
+ """Add a pydantic config for the given type.
677
+
678
+ Note: this is a no-op on Pydantic v1.
679
+ """
680
+ setattr(typ, "__pydantic_config__", config) # noqa: B010
681
+
682
+
683
+ # our use of subclassing here causes weirdness for type checkers,
684
+ # so we just pretend that we don't subclass
685
+ if TYPE_CHECKING:
686
+ GenericModel = BaseModel
687
+ else:
688
+
689
+ class GenericModel(BaseGenericModel, BaseModel):
690
+ pass
691
+
692
+
693
+ if PYDANTIC_V2:
694
+ from pydantic import TypeAdapter as _TypeAdapter
695
+
696
+ _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter))
697
+
698
+ if TYPE_CHECKING:
699
+ from pydantic import TypeAdapter
700
+ else:
701
+ TypeAdapter = _CachedTypeAdapter
702
+
703
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
704
+ return TypeAdapter(type_).validate_python(value)
705
+
706
+ elif not TYPE_CHECKING: # TODO: condition is weird
707
+
708
+ class RootModel(GenericModel, Generic[_T]):
709
+ """Used as a placeholder to easily convert runtime types to a Pydantic format
710
+ to provide validation.
711
+
712
+ For example:
713
+ ```py
714
+ validated = RootModel[int](__root__="5").__root__
715
+ # validated: 5
716
+ ```
717
+ """
718
+
719
+ __root__: _T
720
+
721
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
722
+ model = _create_pydantic_model(type_).validate(value)
723
+ return cast(_T, model.__root__)
724
+
725
+ def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]:
726
+ return RootModel[type_] # type: ignore
727
+
728
+
729
+ class FinalRequestOptionsInput(TypedDict, total=False):
730
+ method: Required[str]
731
+ url: Required[str]
732
+ params: Query
733
+ headers: Headers
734
+ max_retries: int
735
+ timeout: float | Timeout | None
736
+ files: HttpxRequestFiles | None
737
+ idempotency_key: str
738
+ json_data: Body
739
+ extra_json: AnyMapping
740
+ follow_redirects: bool
741
+
742
+
743
+ @final
744
+ class FinalRequestOptions(pydantic.BaseModel):
745
+ method: str
746
+ url: str
747
+ params: Query = {}
748
+ headers: Union[Headers, NotGiven] = NotGiven()
749
+ max_retries: Union[int, NotGiven] = NotGiven()
750
+ timeout: Union[float, Timeout, None, NotGiven] = NotGiven()
751
+ files: Union[HttpxRequestFiles, None] = None
752
+ idempotency_key: Union[str, None] = None
753
+ post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
754
+ follow_redirects: Union[bool, None] = None
755
+
756
+ # It should be noted that we cannot use `json` here as that would override
757
+ # a BaseModel method in an incompatible fashion.
758
+ json_data: Union[Body, None] = None
759
+ extra_json: Union[AnyMapping, None] = None
760
+
761
+ if PYDANTIC_V2:
762
+ model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
763
+ else:
764
+
765
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
766
+ arbitrary_types_allowed: bool = True
767
+
768
+ def get_max_retries(self, max_retries: int) -> int:
769
+ if isinstance(self.max_retries, NotGiven):
770
+ return max_retries
771
+ return self.max_retries
772
+
773
+ def _strip_raw_response_header(self) -> None:
774
+ if not is_given(self.headers):
775
+ return
776
+
777
+ if self.headers.get(RAW_RESPONSE_HEADER):
778
+ self.headers = {**self.headers}
779
+ self.headers.pop(RAW_RESPONSE_HEADER)
780
+
781
+ # override the `construct` method so that we can run custom transformations.
782
+ # this is necessary as we don't want to do any actual runtime type checking
783
+ # (which means we can't use validators) but we do want to ensure that `NotGiven`
784
+ # values are not present
785
+ #
786
+ # type ignore required because we're adding explicit types to `**values`
787
+ @classmethod
788
+ def construct( # type: ignore
789
+ cls,
790
+ _fields_set: set[str] | None = None,
791
+ **values: Unpack[FinalRequestOptionsInput],
792
+ ) -> FinalRequestOptions:
793
+ kwargs: dict[str, Any] = {
794
+ # we unconditionally call `strip_not_given` on any value
795
+ # as it will just ignore any non-mapping types
796
+ key: strip_not_given(value)
797
+ for key, value in values.items()
798
+ }
799
+ if PYDANTIC_V2:
800
+ return super().model_construct(_fields_set, **kwargs)
801
+ return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
802
+
803
+ if not TYPE_CHECKING:
804
+ # type checkers incorrectly complain about this assignment
805
+ model_construct = construct