mistralai 0.4.2__py3-none-any.whl → 0.5.5a50__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. mistralai/__init__.py +5 -0
  2. mistralai/_hooks/__init__.py +5 -0
  3. mistralai/_hooks/custom_user_agent.py +16 -0
  4. mistralai/_hooks/deprecation_warning.py +26 -0
  5. mistralai/_hooks/registration.py +17 -0
  6. mistralai/_hooks/sdkhooks.py +57 -0
  7. mistralai/_hooks/types.py +76 -0
  8. mistralai/async_client.py +5 -413
  9. mistralai/basesdk.py +216 -0
  10. mistralai/chat.py +475 -0
  11. mistralai/client.py +5 -414
  12. mistralai/embeddings.py +182 -0
  13. mistralai/files.py +600 -84
  14. mistralai/fim.py +439 -0
  15. mistralai/fine_tuning.py +855 -0
  16. mistralai/httpclient.py +78 -0
  17. mistralai/models/__init__.py +80 -0
  18. mistralai/models/archiveftmodelout.py +19 -0
  19. mistralai/models/assistantmessage.py +58 -0
  20. mistralai/models/chatcompletionchoice.py +33 -0
  21. mistralai/models/chatcompletionrequest.py +114 -0
  22. mistralai/models/chatcompletionresponse.py +27 -0
  23. mistralai/models/chatcompletionstreamrequest.py +112 -0
  24. mistralai/models/checkpointout.py +25 -0
  25. mistralai/models/completionchunk.py +27 -0
  26. mistralai/models/completionevent.py +15 -0
  27. mistralai/models/completionresponsestreamchoice.py +53 -0
  28. mistralai/models/contentchunk.py +17 -0
  29. mistralai/models/delete_model_v1_models_model_id_deleteop.py +16 -0
  30. mistralai/models/deletefileout.py +24 -0
  31. mistralai/models/deletemodelout.py +25 -0
  32. mistralai/models/deltamessage.py +52 -0
  33. mistralai/models/detailedjobout.py +96 -0
  34. mistralai/models/embeddingrequest.py +66 -0
  35. mistralai/models/embeddingresponse.py +24 -0
  36. mistralai/models/embeddingresponsedata.py +19 -0
  37. mistralai/models/eventout.py +55 -0
  38. mistralai/models/files_api_routes_delete_fileop.py +16 -0
  39. mistralai/models/files_api_routes_retrieve_fileop.py +16 -0
  40. mistralai/models/files_api_routes_upload_fileop.py +51 -0
  41. mistralai/models/fileschema.py +76 -0
  42. mistralai/models/fimcompletionrequest.py +99 -0
  43. mistralai/models/fimcompletionresponse.py +27 -0
  44. mistralai/models/fimcompletionstreamrequest.py +97 -0
  45. mistralai/models/finetuneablemodel.py +8 -0
  46. mistralai/models/ftmodelcapabilitiesout.py +21 -0
  47. mistralai/models/ftmodelout.py +70 -0
  48. mistralai/models/function.py +19 -0
  49. mistralai/models/functioncall.py +16 -0
  50. mistralai/models/githubrepositoryin.py +57 -0
  51. mistralai/models/githubrepositoryout.py +57 -0
  52. mistralai/models/httpvalidationerror.py +23 -0
  53. mistralai/models/jobin.py +78 -0
  54. mistralai/models/jobmetadataout.py +59 -0
  55. mistralai/models/jobout.py +112 -0
  56. mistralai/models/jobs_api_routes_fine_tuning_archive_fine_tuned_modelop.py +16 -0
  57. mistralai/models/jobs_api_routes_fine_tuning_cancel_fine_tuning_jobop.py +18 -0
  58. mistralai/models/jobs_api_routes_fine_tuning_create_fine_tuning_jobop.py +73 -0
  59. mistralai/models/jobs_api_routes_fine_tuning_get_fine_tuning_jobop.py +18 -0
  60. mistralai/models/jobs_api_routes_fine_tuning_get_fine_tuning_jobsop.py +86 -0
  61. mistralai/models/jobs_api_routes_fine_tuning_start_fine_tuning_jobop.py +16 -0
  62. mistralai/models/jobs_api_routes_fine_tuning_unarchive_fine_tuned_modelop.py +16 -0
  63. mistralai/models/jobs_api_routes_fine_tuning_update_fine_tuned_modelop.py +19 -0
  64. mistralai/models/jobsout.py +20 -0
  65. mistralai/models/legacyjobmetadataout.py +85 -0
  66. mistralai/models/listfilesout.py +17 -0
  67. mistralai/models/metricout.py +55 -0
  68. mistralai/models/modelcapabilities.py +21 -0
  69. mistralai/models/modelcard.py +71 -0
  70. mistralai/models/modellist.py +18 -0
  71. mistralai/models/responseformat.py +18 -0
  72. mistralai/models/retrieve_model_v1_models_model_id_getop.py +16 -0
  73. mistralai/models/retrievefileout.py +76 -0
  74. mistralai/models/sampletype.py +7 -0
  75. mistralai/models/sdkerror.py +22 -0
  76. mistralai/models/security.py +16 -0
  77. mistralai/models/source.py +7 -0
  78. mistralai/models/systemmessage.py +26 -0
  79. mistralai/models/textchunk.py +17 -0
  80. mistralai/models/tool.py +18 -0
  81. mistralai/models/toolcall.py +20 -0
  82. mistralai/models/toolmessage.py +55 -0
  83. mistralai/models/trainingfile.py +17 -0
  84. mistralai/models/trainingparameters.py +53 -0
  85. mistralai/models/trainingparametersin.py +61 -0
  86. mistralai/models/unarchiveftmodelout.py +19 -0
  87. mistralai/models/updateftmodelin.py +49 -0
  88. mistralai/models/uploadfileout.py +76 -0
  89. mistralai/models/usageinfo.py +18 -0
  90. mistralai/models/usermessage.py +26 -0
  91. mistralai/models/validationerror.py +24 -0
  92. mistralai/models/wandbintegration.py +61 -0
  93. mistralai/models/wandbintegrationout.py +57 -0
  94. mistralai/models_.py +928 -0
  95. mistralai/py.typed +1 -0
  96. mistralai/sdk.py +111 -0
  97. mistralai/sdkconfiguration.py +53 -0
  98. mistralai/types/__init__.py +21 -0
  99. mistralai/types/basemodel.py +35 -0
  100. mistralai/utils/__init__.py +82 -0
  101. mistralai/utils/annotations.py +19 -0
  102. mistralai/utils/enums.py +34 -0
  103. mistralai/utils/eventstreaming.py +179 -0
  104. mistralai/utils/forms.py +207 -0
  105. mistralai/utils/headers.py +136 -0
  106. mistralai/utils/metadata.py +118 -0
  107. mistralai/utils/queryparams.py +203 -0
  108. mistralai/utils/requestbodies.py +66 -0
  109. mistralai/utils/retries.py +216 -0
  110. mistralai/utils/security.py +182 -0
  111. mistralai/utils/serializers.py +181 -0
  112. mistralai/utils/url.py +150 -0
  113. mistralai/utils/values.py +128 -0
  114. {mistralai-0.4.2.dist-info → mistralai-0.5.5a50.dist-info}/LICENSE +1 -1
  115. mistralai-0.5.5a50.dist-info/METADATA +626 -0
  116. mistralai-0.5.5a50.dist-info/RECORD +228 -0
  117. mistralai_azure/__init__.py +5 -0
  118. mistralai_azure/_hooks/__init__.py +5 -0
  119. mistralai_azure/_hooks/custom_user_agent.py +16 -0
  120. mistralai_azure/_hooks/registration.py +15 -0
  121. mistralai_azure/_hooks/sdkhooks.py +57 -0
  122. mistralai_azure/_hooks/types.py +76 -0
  123. mistralai_azure/basesdk.py +215 -0
  124. mistralai_azure/chat.py +475 -0
  125. mistralai_azure/httpclient.py +78 -0
  126. mistralai_azure/models/__init__.py +28 -0
  127. mistralai_azure/models/assistantmessage.py +58 -0
  128. mistralai_azure/models/chatcompletionchoice.py +33 -0
  129. mistralai_azure/models/chatcompletionrequest.py +114 -0
  130. mistralai_azure/models/chatcompletionresponse.py +27 -0
  131. mistralai_azure/models/chatcompletionstreamrequest.py +112 -0
  132. mistralai_azure/models/completionchunk.py +27 -0
  133. mistralai_azure/models/completionevent.py +15 -0
  134. mistralai_azure/models/completionresponsestreamchoice.py +53 -0
  135. mistralai_azure/models/contentchunk.py +17 -0
  136. mistralai_azure/models/deltamessage.py +52 -0
  137. mistralai_azure/models/function.py +19 -0
  138. mistralai_azure/models/functioncall.py +16 -0
  139. mistralai_azure/models/httpvalidationerror.py +23 -0
  140. mistralai_azure/models/responseformat.py +18 -0
  141. mistralai_azure/models/sdkerror.py +22 -0
  142. mistralai_azure/models/security.py +16 -0
  143. mistralai_azure/models/systemmessage.py +26 -0
  144. mistralai_azure/models/textchunk.py +17 -0
  145. mistralai_azure/models/tool.py +18 -0
  146. mistralai_azure/models/toolcall.py +20 -0
  147. mistralai_azure/models/toolmessage.py +55 -0
  148. mistralai_azure/models/usageinfo.py +18 -0
  149. mistralai_azure/models/usermessage.py +26 -0
  150. mistralai_azure/models/validationerror.py +24 -0
  151. mistralai_azure/py.typed +1 -0
  152. mistralai_azure/sdk.py +102 -0
  153. mistralai_azure/sdkconfiguration.py +53 -0
  154. mistralai_azure/types/__init__.py +21 -0
  155. mistralai_azure/types/basemodel.py +35 -0
  156. mistralai_azure/utils/__init__.py +80 -0
  157. mistralai_azure/utils/annotations.py +19 -0
  158. mistralai_azure/utils/enums.py +34 -0
  159. mistralai_azure/utils/eventstreaming.py +179 -0
  160. mistralai_azure/utils/forms.py +207 -0
  161. mistralai_azure/utils/headers.py +136 -0
  162. mistralai_azure/utils/metadata.py +118 -0
  163. mistralai_azure/utils/queryparams.py +203 -0
  164. mistralai_azure/utils/requestbodies.py +66 -0
  165. mistralai_azure/utils/retries.py +216 -0
  166. mistralai_azure/utils/security.py +168 -0
  167. mistralai_azure/utils/serializers.py +181 -0
  168. mistralai_azure/utils/url.py +150 -0
  169. mistralai_azure/utils/values.py +128 -0
  170. mistralai_gcp/__init__.py +5 -0
  171. mistralai_gcp/_hooks/__init__.py +5 -0
  172. mistralai_gcp/_hooks/custom_user_agent.py +16 -0
  173. mistralai_gcp/_hooks/registration.py +15 -0
  174. mistralai_gcp/_hooks/sdkhooks.py +57 -0
  175. mistralai_gcp/_hooks/types.py +76 -0
  176. mistralai_gcp/basesdk.py +215 -0
  177. mistralai_gcp/chat.py +463 -0
  178. mistralai_gcp/fim.py +439 -0
  179. mistralai_gcp/httpclient.py +78 -0
  180. mistralai_gcp/models/__init__.py +31 -0
  181. mistralai_gcp/models/assistantmessage.py +58 -0
  182. mistralai_gcp/models/chatcompletionchoice.py +33 -0
  183. mistralai_gcp/models/chatcompletionrequest.py +110 -0
  184. mistralai_gcp/models/chatcompletionresponse.py +27 -0
  185. mistralai_gcp/models/chatcompletionstreamrequest.py +108 -0
  186. mistralai_gcp/models/completionchunk.py +27 -0
  187. mistralai_gcp/models/completionevent.py +15 -0
  188. mistralai_gcp/models/completionresponsestreamchoice.py +53 -0
  189. mistralai_gcp/models/contentchunk.py +17 -0
  190. mistralai_gcp/models/deltamessage.py +52 -0
  191. mistralai_gcp/models/fimcompletionrequest.py +99 -0
  192. mistralai_gcp/models/fimcompletionresponse.py +27 -0
  193. mistralai_gcp/models/fimcompletionstreamrequest.py +97 -0
  194. mistralai_gcp/models/function.py +19 -0
  195. mistralai_gcp/models/functioncall.py +16 -0
  196. mistralai_gcp/models/httpvalidationerror.py +23 -0
  197. mistralai_gcp/models/responseformat.py +18 -0
  198. mistralai_gcp/models/sdkerror.py +22 -0
  199. mistralai_gcp/models/security.py +16 -0
  200. mistralai_gcp/models/systemmessage.py +26 -0
  201. mistralai_gcp/models/textchunk.py +17 -0
  202. mistralai_gcp/models/tool.py +18 -0
  203. mistralai_gcp/models/toolcall.py +20 -0
  204. mistralai_gcp/models/toolmessage.py +55 -0
  205. mistralai_gcp/models/usageinfo.py +18 -0
  206. mistralai_gcp/models/usermessage.py +26 -0
  207. mistralai_gcp/models/validationerror.py +24 -0
  208. mistralai_gcp/py.typed +1 -0
  209. mistralai_gcp/sdk.py +165 -0
  210. mistralai_gcp/sdkconfiguration.py +53 -0
  211. mistralai_gcp/types/__init__.py +21 -0
  212. mistralai_gcp/types/basemodel.py +35 -0
  213. mistralai_gcp/utils/__init__.py +80 -0
  214. mistralai_gcp/utils/annotations.py +19 -0
  215. mistralai_gcp/utils/enums.py +34 -0
  216. mistralai_gcp/utils/eventstreaming.py +179 -0
  217. mistralai_gcp/utils/forms.py +207 -0
  218. mistralai_gcp/utils/headers.py +136 -0
  219. mistralai_gcp/utils/metadata.py +118 -0
  220. mistralai_gcp/utils/queryparams.py +203 -0
  221. mistralai_gcp/utils/requestbodies.py +66 -0
  222. mistralai_gcp/utils/retries.py +216 -0
  223. mistralai_gcp/utils/security.py +168 -0
  224. mistralai_gcp/utils/serializers.py +181 -0
  225. mistralai_gcp/utils/url.py +150 -0
  226. mistralai_gcp/utils/values.py +128 -0
  227. py.typed +1 -0
  228. mistralai/client_base.py +0 -211
  229. mistralai/constants.py +0 -5
  230. mistralai/exceptions.py +0 -54
  231. mistralai/jobs.py +0 -172
  232. mistralai/models/chat_completion.py +0 -93
  233. mistralai/models/common.py +0 -9
  234. mistralai/models/embeddings.py +0 -19
  235. mistralai/models/files.py +0 -23
  236. mistralai/models/jobs.py +0 -100
  237. mistralai/models/models.py +0 -39
  238. mistralai-0.4.2.dist-info/METADATA +0 -82
  239. mistralai-0.4.2.dist-info/RECORD +0 -20
  240. {mistralai-0.4.2.dist-info → mistralai-0.5.5a50.dist-info}/WHEEL +0 -0
@@ -0,0 +1,150 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from decimal import Decimal
4
+ from typing import (
5
+ Any,
6
+ Dict,
7
+ get_type_hints,
8
+ List,
9
+ Optional,
10
+ Union,
11
+ get_args,
12
+ get_origin,
13
+ )
14
+ from pydantic import BaseModel
15
+ from pydantic.fields import FieldInfo
16
+
17
+ from .metadata import (
18
+ PathParamMetadata,
19
+ find_field_metadata,
20
+ )
21
+ from .values import _get_serialized_params, _populate_from_globals, _val_to_string
22
+
23
+
24
+ def generate_url(
25
+ server_url: str,
26
+ path: str,
27
+ path_params: Any,
28
+ gbls: Optional[Any] = None,
29
+ ) -> str:
30
+ path_param_values: Dict[str, str] = {}
31
+
32
+ globals_already_populated = _populate_path_params(
33
+ path_params, gbls, path_param_values, []
34
+ )
35
+ if gbls is not None:
36
+ _populate_path_params(gbls, None, path_param_values, globals_already_populated)
37
+
38
+ for key, value in path_param_values.items():
39
+ path = path.replace("{" + key + "}", value, 1)
40
+
41
+ return remove_suffix(server_url, "/") + path
42
+
43
+
44
+ def _populate_path_params(
45
+ path_params: Any,
46
+ gbls: Any,
47
+ path_param_values: Dict[str, str],
48
+ skip_fields: List[str],
49
+ ) -> List[str]:
50
+ globals_already_populated: List[str] = []
51
+
52
+ if not isinstance(path_params, BaseModel):
53
+ return globals_already_populated
54
+
55
+ path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields
56
+ path_param_field_types = get_type_hints(path_params.__class__)
57
+ for name in path_param_fields:
58
+ if name in skip_fields:
59
+ continue
60
+
61
+ field = path_param_fields[name]
62
+
63
+ param_metadata = find_field_metadata(field, PathParamMetadata)
64
+ if param_metadata is None:
65
+ continue
66
+
67
+ param = getattr(path_params, name) if path_params is not None else None
68
+ param, global_found = _populate_from_globals(
69
+ name, param, PathParamMetadata, gbls
70
+ )
71
+ if global_found:
72
+ globals_already_populated.append(name)
73
+
74
+ if param is None:
75
+ continue
76
+
77
+ f_name = field.alias if field.alias is not None else name
78
+ serialization = param_metadata.serialization
79
+ if serialization is not None:
80
+ serialized_params = _get_serialized_params(
81
+ param_metadata, f_name, param, path_param_field_types[name]
82
+ )
83
+ for key, value in serialized_params.items():
84
+ path_param_values[key] = value
85
+ else:
86
+ pp_vals: List[str] = []
87
+ if param_metadata.style == "simple":
88
+ if isinstance(param, List):
89
+ for pp_val in param:
90
+ if pp_val is None:
91
+ continue
92
+ pp_vals.append(_val_to_string(pp_val))
93
+ path_param_values[f_name] = ",".join(pp_vals)
94
+ elif isinstance(param, Dict):
95
+ for pp_key in param:
96
+ if param[pp_key] is None:
97
+ continue
98
+ if param_metadata.explode:
99
+ pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}")
100
+ else:
101
+ pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}")
102
+ path_param_values[f_name] = ",".join(pp_vals)
103
+ elif not isinstance(param, (str, int, float, complex, bool, Decimal)):
104
+ param_fields: Dict[str, FieldInfo] = param.__class__.model_fields
105
+ for name in param_fields:
106
+ param_field = param_fields[name]
107
+
108
+ param_value_metadata = find_field_metadata(
109
+ param_field, PathParamMetadata
110
+ )
111
+ if param_value_metadata is None:
112
+ continue
113
+
114
+ param_name = (
115
+ param_field.alias if param_field.alias is not None else name
116
+ )
117
+
118
+ param_field_val = getattr(param, name)
119
+ if param_field_val is None:
120
+ continue
121
+ if param_metadata.explode:
122
+ pp_vals.append(
123
+ f"{param_name}={_val_to_string(param_field_val)}"
124
+ )
125
+ else:
126
+ pp_vals.append(
127
+ f"{param_name},{_val_to_string(param_field_val)}"
128
+ )
129
+ path_param_values[f_name] = ",".join(pp_vals)
130
+ else:
131
+ path_param_values[f_name] = _val_to_string(param)
132
+
133
+ return globals_already_populated
134
+
135
+
136
+ def is_optional(field):
137
+ return get_origin(field) is Union and type(None) in get_args(field)
138
+
139
+
140
+ def template_url(url_with_params: str, params: Dict[str, str]) -> str:
141
+ for key, value in params.items():
142
+ url_with_params = url_with_params.replace("{" + key + "}", value)
143
+
144
+ return url_with_params
145
+
146
+
147
+ def remove_suffix(input_string, suffix):
148
+ if suffix and input_string.endswith(suffix):
149
+ return input_string[: -len(suffix)]
150
+ return input_string
@@ -0,0 +1,128 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from datetime import datetime
4
+ from enum import Enum
5
+ from email.message import Message
6
+ import os
7
+ from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union
8
+
9
+ from httpx import Response
10
+ from pydantic import BaseModel
11
+ from pydantic.fields import FieldInfo
12
+
13
+ from .serializers import marshal_json
14
+
15
+ from .metadata import ParamMetadata, find_field_metadata
16
+
17
+
18
+ def match_content_type(content_type: str, pattern: str) -> bool:
19
+ if pattern in (content_type, "*", "*/*"):
20
+ return True
21
+
22
+ msg = Message()
23
+ msg["content-type"] = content_type
24
+ media_type = msg.get_content_type()
25
+
26
+ if media_type == pattern:
27
+ return True
28
+
29
+ parts = media_type.split("/")
30
+ if len(parts) == 2:
31
+ if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"):
32
+ return True
33
+
34
+ return False
35
+
36
+
37
+ def match_status_codes(status_codes: List[str], status_code: int) -> bool:
38
+ if "default" in status_codes:
39
+ return True
40
+
41
+ for code in status_codes:
42
+ if code == str(status_code):
43
+ return True
44
+
45
+ if code.endswith("XX") and code.startswith(str(status_code)[:1]):
46
+ return True
47
+ return False
48
+
49
+
50
+ T = TypeVar("T")
51
+
52
+
53
+ def get_global_from_env(
54
+ value: Optional[T], env_key: str, type_cast: Callable[[str], T]
55
+ ) -> Optional[T]:
56
+ if value is not None:
57
+ return value
58
+ env_value = os.getenv(env_key)
59
+ if env_value is not None:
60
+ try:
61
+ return type_cast(env_value)
62
+ except ValueError:
63
+ pass
64
+ return None
65
+
66
+
67
+ def match_response(
68
+ response: Response, code: Union[str, List[str]], content_type: str
69
+ ) -> bool:
70
+ codes = code if isinstance(code, list) else [code]
71
+ return match_status_codes(codes, response.status_code) and match_content_type(
72
+ response.headers.get("content-type", "application/octet-stream"), content_type
73
+ )
74
+
75
+
76
+ def _populate_from_globals(
77
+ param_name: str, value: Any, param_metadata_type: type, gbls: Any
78
+ ) -> Tuple[Any, bool]:
79
+ if gbls is None:
80
+ return value, False
81
+
82
+ if not isinstance(gbls, BaseModel):
83
+ raise TypeError("globals must be a pydantic model")
84
+
85
+ global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields
86
+ found = False
87
+ for name in global_fields:
88
+ field = global_fields[name]
89
+ if name is not param_name:
90
+ continue
91
+
92
+ found = True
93
+
94
+ if value is not None:
95
+ return value, True
96
+
97
+ global_value = getattr(gbls, name)
98
+
99
+ param_metadata = find_field_metadata(field, param_metadata_type)
100
+ if param_metadata is None:
101
+ return value, True
102
+
103
+ return global_value, True
104
+
105
+ return value, found
106
+
107
+
108
+ def _val_to_string(val) -> str:
109
+ if isinstance(val, bool):
110
+ return str(val).lower()
111
+ if isinstance(val, datetime):
112
+ return str(val.isoformat().replace("+00:00", "Z"))
113
+ if isinstance(val, Enum):
114
+ return str(val.value)
115
+
116
+ return str(val)
117
+
118
+
119
+ def _get_serialized_params(
120
+ metadata: ParamMetadata, field_name: str, obj: Any, typ: type
121
+ ) -> Dict[str, str]:
122
+ params: Dict[str, str] = {}
123
+
124
+ serialization = metadata.serialization
125
+ if serialization == "json":
126
+ params[field_name] = marshal_json(obj, typ)
127
+
128
+ return params
@@ -0,0 +1,5 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from .sdk import *
4
+ from .sdkconfiguration import *
5
+ from .models import *
@@ -0,0 +1,5 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from .sdkhooks import *
4
+ from .types import *
5
+ from .registration import *
@@ -0,0 +1,16 @@
1
+ # THIS FILE IS THE EXACT COPY OF THE ORIGINAL FILE FROM src/mistralai/_hooks/custom_user_agent.py
2
+ from typing import Union
3
+
4
+ import httpx
5
+
6
+ from .types import BeforeRequestContext, BeforeRequestHook
7
+
8
+
9
+ class CustomUserAgentHook(BeforeRequestHook):
10
+ def before_request(
11
+ self, hook_ctx: BeforeRequestContext, request: httpx.Request
12
+ ) -> Union[httpx.Request, Exception]:
13
+ request.headers["user-agent"] = (
14
+ "mistral-client-python/" + request.headers["user-agent"].split(" ")[1]
15
+ )
16
+ return request
@@ -0,0 +1,15 @@
1
+ from .custom_user_agent import CustomUserAgentHook
2
+ from .types import Hooks
3
+
4
+ # This file is only ever generated once on the first generation and then is free to be modified.
5
+ # Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them
6
+ # in this file or in separate files in the hooks folder.
7
+
8
+
9
+ def init_hooks(hooks: Hooks):
10
+ # pylint: disable=unused-argument
11
+ """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook
12
+ with an instance of a hook that implements that specific Hook interface
13
+ Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance
14
+ """
15
+ hooks.register_before_request_hook(CustomUserAgentHook())
@@ -0,0 +1,57 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ import httpx
4
+ from .types import SDKInitHook, BeforeRequestContext, BeforeRequestHook, AfterSuccessContext, AfterSuccessHook, AfterErrorContext, AfterErrorHook, Hooks
5
+ from .registration import init_hooks
6
+ from typing import List, Optional, Tuple
7
+ from mistralai_gcp.httpclient import HttpClient
8
+
9
+ class SDKHooks(Hooks):
10
+ def __init__(self) -> None:
11
+ self.sdk_init_hooks: List[SDKInitHook] = []
12
+ self.before_request_hooks: List[BeforeRequestHook] = []
13
+ self.after_success_hooks: List[AfterSuccessHook] = []
14
+ self.after_error_hooks: List[AfterErrorHook] = []
15
+ init_hooks(self)
16
+
17
+ def register_sdk_init_hook(self, hook: SDKInitHook) -> None:
18
+ self.sdk_init_hooks.append(hook)
19
+
20
+ def register_before_request_hook(self, hook: BeforeRequestHook) -> None:
21
+ self.before_request_hooks.append(hook)
22
+
23
+ def register_after_success_hook(self, hook: AfterSuccessHook) -> None:
24
+ self.after_success_hooks.append(hook)
25
+
26
+ def register_after_error_hook(self, hook: AfterErrorHook) -> None:
27
+ self.after_error_hooks.append(hook)
28
+
29
+ def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]:
30
+ for hook in self.sdk_init_hooks:
31
+ base_url, client = hook.sdk_init(base_url, client)
32
+ return base_url, client
33
+
34
+ def before_request(self, hook_ctx: BeforeRequestContext, request: httpx.Request) -> httpx.Request:
35
+ for hook in self.before_request_hooks:
36
+ out = hook.before_request(hook_ctx, request)
37
+ if isinstance(out, Exception):
38
+ raise out
39
+ request = out
40
+
41
+ return request
42
+
43
+ def after_success(self, hook_ctx: AfterSuccessContext, response: httpx.Response) -> httpx.Response:
44
+ for hook in self.after_success_hooks:
45
+ out = hook.after_success(hook_ctx, response)
46
+ if isinstance(out, Exception):
47
+ raise out
48
+ response = out
49
+ return response
50
+
51
+ def after_error(self, hook_ctx: AfterErrorContext, response: Optional[httpx.Response], error: Optional[Exception]) -> Tuple[Optional[httpx.Response], Optional[Exception]]:
52
+ for hook in self.after_error_hooks:
53
+ result = hook.after_error(hook_ctx, response, error)
54
+ if isinstance(result, Exception):
55
+ raise result
56
+ response, error = result
57
+ return response, error
@@ -0,0 +1,76 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+
4
+ from abc import ABC, abstractmethod
5
+ import httpx
6
+ from mistralai_gcp.httpclient import HttpClient
7
+ from typing import Any, Callable, List, Optional, Tuple, Union
8
+
9
+
10
+ class HookContext:
11
+ operation_id: str
12
+ oauth2_scopes: Optional[List[str]] = None
13
+ security_source: Optional[Union[Any, Callable[[], Any]]] = None
14
+
15
+ def __init__(self, operation_id: str, oauth2_scopes: Optional[List[str]], security_source: Optional[Union[Any, Callable[[], Any]]]):
16
+ self.operation_id = operation_id
17
+ self.oauth2_scopes = oauth2_scopes
18
+ self.security_source = security_source
19
+
20
+
21
+ class BeforeRequestContext(HookContext):
22
+ def __init__(self, hook_ctx: HookContext):
23
+ super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source)
24
+
25
+
26
+ class AfterSuccessContext(HookContext):
27
+ def __init__(self, hook_ctx: HookContext):
28
+ super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source)
29
+
30
+
31
+
32
+ class AfterErrorContext(HookContext):
33
+ def __init__(self, hook_ctx: HookContext):
34
+ super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source)
35
+
36
+
37
+ class SDKInitHook(ABC):
38
+ @abstractmethod
39
+ def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]:
40
+ pass
41
+
42
+
43
+ class BeforeRequestHook(ABC):
44
+ @abstractmethod
45
+ def before_request(self, hook_ctx: BeforeRequestContext, request: httpx.Request) -> Union[httpx.Request, Exception]:
46
+ pass
47
+
48
+
49
+ class AfterSuccessHook(ABC):
50
+ @abstractmethod
51
+ def after_success(self, hook_ctx: AfterSuccessContext, response: httpx.Response) -> Union[httpx.Response, Exception]:
52
+ pass
53
+
54
+
55
+ class AfterErrorHook(ABC):
56
+ @abstractmethod
57
+ def after_error(self, hook_ctx: AfterErrorContext, response: Optional[httpx.Response], error: Optional[Exception]) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]:
58
+ pass
59
+
60
+
61
+ class Hooks(ABC):
62
+ @abstractmethod
63
+ def register_sdk_init_hook(self, hook: SDKInitHook):
64
+ pass
65
+
66
+ @abstractmethod
67
+ def register_before_request_hook(self, hook: BeforeRequestHook):
68
+ pass
69
+
70
+ @abstractmethod
71
+ def register_after_success_hook(self, hook: AfterSuccessHook):
72
+ pass
73
+
74
+ @abstractmethod
75
+ def register_after_error_hook(self, hook: AfterErrorHook):
76
+ pass
@@ -0,0 +1,215 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from .sdkconfiguration import SDKConfiguration
4
+ import httpx
5
+ from mistralai_gcp import models
6
+ from mistralai_gcp._hooks import AfterErrorContext, AfterSuccessContext, BeforeRequestContext
7
+ import mistralai_gcp.utils as utils
8
+ from mistralai_gcp.utils import RetryConfig, SerializedRequestBody
9
+ from typing import Callable, List, Optional, Tuple
10
+
11
+ class BaseSDK:
12
+ sdk_configuration: SDKConfiguration
13
+
14
+ def __init__(self, sdk_config: SDKConfiguration) -> None:
15
+ self.sdk_configuration = sdk_config
16
+
17
+ def get_url(self, base_url, url_variables):
18
+ sdk_url, sdk_variables = self.sdk_configuration.get_server_details()
19
+
20
+ if base_url is None:
21
+ base_url = sdk_url
22
+
23
+ if url_variables is None:
24
+ url_variables = sdk_variables
25
+
26
+ return utils.template_url(base_url, url_variables)
27
+
28
+ def build_request(
29
+ self,
30
+ method,
31
+ path,
32
+ base_url,
33
+ url_variables,
34
+ request,
35
+ request_body_required,
36
+ request_has_path_params,
37
+ request_has_query_params,
38
+ user_agent_header,
39
+ accept_header_value,
40
+ _globals=None,
41
+ security=None,
42
+ timeout_ms: Optional[int] = None,
43
+ get_serialized_body: Optional[
44
+ Callable[[], Optional[SerializedRequestBody]]
45
+ ] = None,
46
+ url_override: Optional[str] = None,
47
+ ) -> httpx.Request:
48
+ client = self.sdk_configuration.client
49
+
50
+ query_params = {}
51
+
52
+ url = url_override
53
+ if url is None:
54
+ url = utils.generate_url(
55
+ self.get_url(base_url, url_variables),
56
+ path,
57
+ request if request_has_path_params else None,
58
+ _globals if request_has_path_params else None,
59
+ )
60
+
61
+ query_params = utils.get_query_params(
62
+ request if request_has_query_params else None,
63
+ _globals if request_has_query_params else None,
64
+ )
65
+
66
+ headers = utils.get_headers(request, _globals)
67
+ headers["Accept"] = accept_header_value
68
+ headers[user_agent_header] = self.sdk_configuration.user_agent
69
+
70
+ if security is not None:
71
+ if callable(security):
72
+ security = security()
73
+
74
+ if security is not None:
75
+ security_headers, security_query_params = utils.get_security(security)
76
+ headers = {**headers, **security_headers}
77
+ query_params = {**query_params, **security_query_params}
78
+
79
+ serialized_request_body = SerializedRequestBody("application/octet-stream")
80
+ if get_serialized_body is not None:
81
+ rb = get_serialized_body()
82
+ if request_body_required and rb is None:
83
+ raise ValueError("request body is required")
84
+
85
+ if rb is not None:
86
+ serialized_request_body = rb
87
+
88
+ if (
89
+ serialized_request_body.media_type is not None
90
+ and serialized_request_body.media_type
91
+ not in (
92
+ "multipart/form-data",
93
+ "multipart/mixed",
94
+ )
95
+ ):
96
+ headers["content-type"] = serialized_request_body.media_type
97
+
98
+ timeout = timeout_ms / 1000 if timeout_ms is not None else None
99
+
100
+ return client.build_request(
101
+ method,
102
+ url,
103
+ params=query_params,
104
+ content=serialized_request_body.content,
105
+ data=serialized_request_body.data,
106
+ files=serialized_request_body.files,
107
+ headers=headers,
108
+ timeout=timeout,
109
+ )
110
+
111
+ def do_request(
112
+ self,
113
+ hook_ctx,
114
+ request,
115
+ error_status_codes,
116
+ stream=False,
117
+ retry_config: Optional[Tuple[RetryConfig, List[str]]] = None,
118
+ ) -> httpx.Response:
119
+ client = self.sdk_configuration.client
120
+
121
+ def do():
122
+ http_res = None
123
+ try:
124
+ req = self.sdk_configuration.get_hooks().before_request(
125
+ BeforeRequestContext(hook_ctx), request
126
+ )
127
+ http_res = client.send(req, stream=stream)
128
+ except Exception as e:
129
+ _, e = self.sdk_configuration.get_hooks().after_error(
130
+ AfterErrorContext(hook_ctx), None, e
131
+ )
132
+ if e is not None:
133
+ raise e
134
+
135
+ if http_res is None:
136
+ raise models.SDKError("No response received")
137
+
138
+ if utils.match_status_codes(error_status_codes, http_res.status_code):
139
+ result, err = self.sdk_configuration.get_hooks().after_error(
140
+ AfterErrorContext(hook_ctx), http_res, None
141
+ )
142
+ if err is not None:
143
+ raise err
144
+ if result is not None:
145
+ http_res = result
146
+ else:
147
+ raise models.SDKError("Unexpected error occurred")
148
+
149
+ return http_res
150
+
151
+ if retry_config is not None:
152
+ http_res = utils.retry(do, utils.Retries(retry_config[0], retry_config[1]))
153
+ else:
154
+ http_res = do()
155
+
156
+ if not utils.match_status_codes(error_status_codes, http_res.status_code):
157
+ http_res = self.sdk_configuration.get_hooks().after_success(
158
+ AfterSuccessContext(hook_ctx), http_res
159
+ )
160
+
161
+ return http_res
162
+
163
+ async def do_request_async(
164
+ self,
165
+ hook_ctx,
166
+ request,
167
+ error_status_codes,
168
+ stream=False,
169
+ retry_config: Optional[Tuple[RetryConfig, List[str]]] = None,
170
+ ) -> httpx.Response:
171
+ client = self.sdk_configuration.async_client
172
+
173
+ async def do():
174
+ http_res = None
175
+ try:
176
+ req = self.sdk_configuration.get_hooks().before_request(
177
+ BeforeRequestContext(hook_ctx), request
178
+ )
179
+ http_res = await client.send(req, stream=stream)
180
+ except Exception as e:
181
+ _, e = self.sdk_configuration.get_hooks().after_error(
182
+ AfterErrorContext(hook_ctx), None, e
183
+ )
184
+ if e is not None:
185
+ raise e
186
+
187
+ if http_res is None:
188
+ raise models.SDKError("No response received")
189
+
190
+ if utils.match_status_codes(error_status_codes, http_res.status_code):
191
+ result, err = self.sdk_configuration.get_hooks().after_error(
192
+ AfterErrorContext(hook_ctx), http_res, None
193
+ )
194
+ if err is not None:
195
+ raise err
196
+ if result is not None:
197
+ http_res = result
198
+ else:
199
+ raise models.SDKError("Unexpected error occurred")
200
+
201
+ return http_res
202
+
203
+ if retry_config is not None:
204
+ http_res = await utils.retry_async(
205
+ do, utils.Retries(retry_config[0], retry_config[1])
206
+ )
207
+ else:
208
+ http_res = await do()
209
+
210
+ if not utils.match_status_codes(error_status_codes, http_res.status_code):
211
+ http_res = self.sdk_configuration.get_hooks().after_success(
212
+ AfterSuccessContext(hook_ctx), http_res
213
+ )
214
+
215
+ return http_res