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
mistralai/__init__.py CHANGED
@@ -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
+ # MAKE SURE YOU UPDATE THE COPIES OF THIS FILES IN THE PROVIDERS'S PACKAGES WHEN YOU MAKE CHANGES HERE
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,26 @@
1
+ import logging
2
+ from typing import Union
3
+
4
+ import httpx
5
+
6
+ from .types import AfterSuccessContext, AfterSuccessHook
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ HEADER_MODEL_DEPRECATION_TIMESTAMP = "x-model-deprecation-timestamp"
11
+
12
+
13
+ class DeprecationWarningHook(AfterSuccessHook):
14
+
15
+ def after_success(
16
+ self, hook_ctx: AfterSuccessContext, response: httpx.Response
17
+ ) -> Union[httpx.Response, Exception]:
18
+ if HEADER_MODEL_DEPRECATION_TIMESTAMP in response.headers:
19
+ model = response.json()["model"]
20
+ # pylint: disable=logging-fstring-interpolation
21
+ logger.warning(
22
+ "WARNING: The model %s is deprecated and will be removed on %s. Please refer to https://docs.mistral.ai/getting-started/models/#api-versioning for more information.",
23
+ model,
24
+ response.headers[HEADER_MODEL_DEPRECATION_TIMESTAMP],
25
+ )
26
+ return response
@@ -0,0 +1,17 @@
1
+ from .custom_user_agent import CustomUserAgentHook
2
+ from .deprecation_warning import DeprecationWarningHook
3
+ from .types import Hooks
4
+
5
+ # This file is only ever generated once on the first generation and then is free to be modified.
6
+ # Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them
7
+ # in this file or in separate files in the hooks folder.
8
+
9
+
10
+ def init_hooks(hooks: Hooks):
11
+ # pylint: disable=unused-argument
12
+ """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook
13
+ with an instance of a hook that implements that specific Hook interface
14
+ Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance
15
+ """
16
+ hooks.register_before_request_hook(CustomUserAgentHook())
17
+ hooks.register_after_success_hook(DeprecationWarningHook())
@@ -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.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.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
mistralai/async_client.py CHANGED
@@ -1,423 +1,15 @@
1
- import asyncio
2
- import posixpath
3
- from json import JSONDecodeError
4
- from typing import Any, AsyncGenerator, Callable, Dict, List, Optional, Union
1
+ from typing import Optional
5
2
 
6
- from httpx import (
7
- AsyncClient,
8
- AsyncHTTPTransport,
9
- ConnectError,
10
- Limits,
11
- RequestError,
12
- Response,
13
- )
3
+ from .client import MIGRATION_MESSAGE
14
4
 
15
- from mistralai.client_base import ClientBase
16
- from mistralai.constants import ENDPOINT, RETRY_STATUS_CODES
17
- from mistralai.exceptions import (
18
- MistralAPIException,
19
- MistralAPIStatusException,
20
- MistralConnectionException,
21
- MistralException,
22
- )
23
- from mistralai.files import FilesAsyncClient
24
- from mistralai.jobs import JobsAsyncClient
25
- from mistralai.models.chat_completion import (
26
- ChatCompletionResponse,
27
- ChatCompletionStreamResponse,
28
- ResponseFormat,
29
- ToolChoice,
30
- )
31
- from mistralai.models.embeddings import EmbeddingResponse
32
- from mistralai.models.models import ModelDeleted, ModelList
33
5
 
34
-
35
- class MistralAsyncClient(ClientBase):
6
+ class MistralAsyncClient:
36
7
  def __init__(
37
8
  self,
38
9
  api_key: Optional[str] = None,
39
- endpoint: str = ENDPOINT,
10
+ endpoint: str = "",
40
11
  max_retries: int = 5,
41
12
  timeout: int = 120,
42
13
  max_concurrent_requests: int = 64,
43
14
  ):
44
- super().__init__(endpoint, api_key, max_retries, timeout)
45
-
46
- self._client = AsyncClient(
47
- follow_redirects=True,
48
- timeout=timeout,
49
- limits=Limits(max_connections=max_concurrent_requests),
50
- transport=AsyncHTTPTransport(retries=max_retries),
51
- )
52
- self.files = FilesAsyncClient(self)
53
- self.jobs = JobsAsyncClient(self)
54
-
55
- async def close(self) -> None:
56
- await self._client.aclose()
57
-
58
- async def _check_response_status_codes(self, response: Response) -> None:
59
- if response.status_code in RETRY_STATUS_CODES:
60
- raise MistralAPIStatusException.from_response(
61
- response,
62
- message=f"Status: {response.status_code}. Message: {response.text}",
63
- )
64
- elif 400 <= response.status_code < 500:
65
- if response.stream:
66
- await response.aread()
67
- raise MistralAPIException.from_response(
68
- response,
69
- message=f"Status: {response.status_code}. Message: {response.text}",
70
- )
71
- elif response.status_code >= 500:
72
- if response.stream:
73
- await response.aread()
74
- raise MistralException(
75
- message=f"Status: {response.status_code}. Message: {response.text}",
76
- )
77
-
78
- async def _check_streaming_response(self, response: Response) -> None:
79
- await self._check_response_status_codes(response)
80
-
81
- async def _check_response(self, response: Response) -> Dict[str, Any]:
82
- await self._check_response_status_codes(response)
83
-
84
- json_response: Dict[str, Any] = response.json()
85
-
86
- if "object" not in json_response:
87
- raise MistralException(message=f"Unexpected response: {json_response}")
88
- if "error" == json_response["object"]: # has errors
89
- raise MistralAPIException.from_response(
90
- response,
91
- message=json_response["message"],
92
- )
93
-
94
- return json_response
95
-
96
- async def _request(
97
- self,
98
- method: str,
99
- json: Optional[Dict[str, Any]],
100
- path: str,
101
- stream: bool = False,
102
- attempt: int = 1,
103
- data: Optional[Dict[str, Any]] = None,
104
- check_model_deprecation_headers_callback: Optional[Callable] = None,
105
- **kwargs: Any,
106
- ) -> AsyncGenerator[Dict[str, Any], None]:
107
- accept_header = "text/event-stream" if stream else "application/json"
108
- headers = {
109
- "Accept": accept_header,
110
- "User-Agent": f"mistral-client-python/{self._version}",
111
- "Authorization": f"Bearer {self._api_key}",
112
- }
113
-
114
- if json is not None:
115
- headers["Content-Type"] = "application/json"
116
-
117
- url = posixpath.join(self._endpoint, path)
118
-
119
- self._logger.debug(f"Sending request: {method} {url} {json}")
120
-
121
- response: Response
122
-
123
- try:
124
- if stream:
125
- async with self._client.stream(
126
- method,
127
- url,
128
- headers=headers,
129
- json=json,
130
- data=data,
131
- **kwargs,
132
- ) as response:
133
- if check_model_deprecation_headers_callback:
134
- check_model_deprecation_headers_callback(response.headers)
135
- await self._check_streaming_response(response)
136
-
137
- async for line in response.aiter_lines():
138
- json_streamed_response = self._process_line(line)
139
- if json_streamed_response:
140
- yield json_streamed_response
141
-
142
- else:
143
- response = await self._client.request(
144
- method,
145
- url,
146
- headers=headers,
147
- json=json,
148
- data=data,
149
- **kwargs,
150
- )
151
- if check_model_deprecation_headers_callback:
152
- check_model_deprecation_headers_callback(response.headers)
153
- yield await self._check_response(response)
154
-
155
- except ConnectError as e:
156
- raise MistralConnectionException(str(e)) from e
157
- except RequestError as e:
158
- raise MistralException(f"Unexpected exception ({e.__class__.__name__}): {e}") from e
159
- except JSONDecodeError as e:
160
- raise MistralAPIException.from_response(
161
- response,
162
- message=f"Failed to decode json body: {response.text}",
163
- ) from e
164
- except MistralAPIStatusException as e:
165
- attempt += 1
166
- if attempt > self._max_retries:
167
- raise MistralAPIStatusException.from_response(response, message=str(e)) from e
168
- backoff = 2.0**attempt # exponential backoff
169
- await asyncio.sleep(backoff)
170
-
171
- # Retry as a generator
172
- async for r in self._request(method, json, path, stream=stream, attempt=attempt):
173
- yield r
174
-
175
- async def chat(
176
- self,
177
- messages: List[Any],
178
- model: Optional[str] = None,
179
- tools: Optional[List[Dict[str, Any]]] = None,
180
- temperature: Optional[float] = None,
181
- max_tokens: Optional[int] = None,
182
- top_p: Optional[float] = None,
183
- random_seed: Optional[int] = None,
184
- safe_mode: bool = False,
185
- safe_prompt: bool = False,
186
- tool_choice: Optional[Union[str, ToolChoice]] = None,
187
- response_format: Optional[Union[Dict[str, str], ResponseFormat]] = None,
188
- ) -> ChatCompletionResponse:
189
- """A asynchronous chat endpoint that returns a single response.
190
-
191
- Args:
192
- model (str): model the name of the model to chat with, e.g. mistral-tiny
193
- messages (List[Any]): messages an array of messages to chat with, e.g.
194
- [{role: 'user', content: 'What is the best French cheese?'}]
195
- temperature (Optional[float], optional): temperature the temperature to use for sampling, e.g. 0.5.
196
- max_tokens (Optional[int], optional): the maximum number of tokens to generate, e.g. 100. Defaults to None.
197
- top_p (Optional[float], optional): the cumulative probability of tokens to generate, e.g. 0.9.
198
- Defaults to None.
199
- random_seed (Optional[int], optional): the random seed to use for sampling, e.g. 42. Defaults to None.
200
- safe_mode (bool, optional): deprecated, use safe_prompt instead. Defaults to False.
201
- safe_prompt (bool, optional): whether to use safe prompt, e.g. true. Defaults to False.
202
-
203
- Returns:
204
- ChatCompletionResponse: a response object containing the generated text.
205
- """
206
- request = self._make_chat_request(
207
- messages,
208
- model,
209
- tools=tools,
210
- temperature=temperature,
211
- max_tokens=max_tokens,
212
- top_p=top_p,
213
- random_seed=random_seed,
214
- stream=False,
215
- safe_prompt=safe_mode or safe_prompt,
216
- tool_choice=tool_choice,
217
- response_format=response_format,
218
- )
219
-
220
- single_response = self._request(
221
- "post",
222
- request,
223
- "v1/chat/completions",
224
- check_model_deprecation_headers_callback=self._check_model_deprecation_header_callback_factory(model),
225
- )
226
-
227
- async for response in single_response:
228
- return ChatCompletionResponse(**response)
229
-
230
- raise MistralException("No response received")
231
-
232
- async def chat_stream(
233
- self,
234
- messages: List[Any],
235
- model: Optional[str] = None,
236
- tools: Optional[List[Dict[str, Any]]] = None,
237
- temperature: Optional[float] = None,
238
- max_tokens: Optional[int] = None,
239
- top_p: Optional[float] = None,
240
- random_seed: Optional[int] = None,
241
- safe_mode: bool = False,
242
- safe_prompt: bool = False,
243
- tool_choice: Optional[Union[str, ToolChoice]] = None,
244
- response_format: Optional[Union[Dict[str, str], ResponseFormat]] = None,
245
- ) -> AsyncGenerator[ChatCompletionStreamResponse, None]:
246
- """An Asynchronous chat endpoint that streams responses.
247
-
248
- Args:
249
- model (str): model the name of the model to chat with, e.g. mistral-tiny
250
- messages (List[Any]): messages an array of messages to chat with, e.g.
251
- [{role: 'user', content: 'What is the best French cheese?'}]
252
- tools (Optional[List[Function]], optional): a list of tools to use.
253
- temperature (Optional[float], optional): temperature the temperature to use for sampling, e.g. 0.5.
254
- max_tokens (Optional[int], optional): the maximum number of tokens to generate, e.g. 100. Defaults to None.
255
- top_p (Optional[float], optional): the cumulative probability of tokens to generate, e.g. 0.9.
256
- Defaults to None.
257
- random_seed (Optional[int], optional): the random seed to use for sampling, e.g. 42. Defaults to None.
258
- safe_mode (bool, optional): deprecated, use safe_prompt instead. Defaults to False.
259
- safe_prompt (bool, optional): whether to use safe prompt, e.g. true. Defaults to False.
260
-
261
- Returns:
262
- AsyncGenerator[ChatCompletionStreamResponse, None]:
263
- An async generator that yields ChatCompletionStreamResponse objects.
264
- """
265
-
266
- request = self._make_chat_request(
267
- messages,
268
- model,
269
- tools=tools,
270
- temperature=temperature,
271
- max_tokens=max_tokens,
272
- top_p=top_p,
273
- random_seed=random_seed,
274
- stream=True,
275
- safe_prompt=safe_mode or safe_prompt,
276
- tool_choice=tool_choice,
277
- response_format=response_format,
278
- )
279
- async_response = self._request(
280
- "post",
281
- request,
282
- "v1/chat/completions",
283
- stream=True,
284
- check_model_deprecation_headers_callback=self._check_model_deprecation_header_callback_factory(model),
285
- )
286
-
287
- async for json_response in async_response:
288
- yield ChatCompletionStreamResponse(**json_response)
289
-
290
- async def embeddings(self, model: str, input: Union[str, List[str]]) -> EmbeddingResponse:
291
- """An asynchronous embeddings endpoint that returns embeddings for a single, or batch of inputs
292
-
293
- Args:
294
- model (str): The embedding model to use, e.g. mistral-embed
295
- input (Union[str, List[str]]): The input to embed,
296
- e.g. ['What is the best French cheese?']
297
-
298
- Returns:
299
- EmbeddingResponse: A response object containing the embeddings.
300
- """
301
- request = {"model": model, "input": input}
302
- single_response = self._request(
303
- "post",
304
- request,
305
- "v1/embeddings",
306
- check_model_deprecation_headers_callback=self._check_model_deprecation_header_callback_factory(model),
307
- )
308
-
309
- async for response in single_response:
310
- return EmbeddingResponse(**response)
311
-
312
- raise MistralException("No response received")
313
-
314
- async def list_models(self) -> ModelList:
315
- """Returns a list of the available models
316
-
317
- Returns:
318
- ModelList: A response object containing the list of models.
319
- """
320
- single_response = self._request("get", {}, "v1/models")
321
-
322
- async for response in single_response:
323
- return ModelList(**response)
324
-
325
- raise MistralException("No response received")
326
-
327
- async def delete_model(self, model_id: str) -> ModelDeleted:
328
- single_response = self._request("delete", {}, f"v1/models/{model_id}")
329
-
330
- async for response in single_response:
331
- return ModelDeleted(**response)
332
-
333
- raise MistralException("No response received")
334
-
335
- async def completion(
336
- self,
337
- model: str,
338
- prompt: str,
339
- suffix: Optional[str] = None,
340
- temperature: Optional[float] = None,
341
- max_tokens: Optional[int] = None,
342
- top_p: Optional[float] = None,
343
- random_seed: Optional[int] = None,
344
- stop: Optional[List[str]] = None,
345
- ) -> ChatCompletionResponse:
346
- """An asynchronous completion endpoint that returns a single response.
347
-
348
- Args:
349
- model (str): model the name of the model to get completions with, e.g. codestral-latest
350
- prompt (str): the prompt to complete
351
- suffix (Optional[str]): the suffix to append to the prompt for fill-in-the-middle completion
352
- temperature (Optional[float], optional): temperature the temperature to use for sampling, e.g. 0.5.
353
- max_tokens (Optional[int], optional): the maximum number of tokens to generate, e.g. 100. Defaults to None.
354
- top_p (Optional[float], optional): the cumulative probability of tokens to generate, e.g. 0.9.
355
- Defaults to None.
356
- random_seed (Optional[int], optional): the random seed to use for sampling, e.g. 42. Defaults to None.
357
- stop (Optional[List[str]], optional): a list of tokens to stop generation at, e.g. ['/n/n']
358
- Returns:
359
- Dict[str, Any]: a response object containing the generated text.
360
- """
361
- request = self._make_completion_request(
362
- prompt, model, suffix, temperature, max_tokens, top_p, random_seed, stop
363
- )
364
- single_response = self._request(
365
- "post",
366
- request,
367
- "v1/fim/completions",
368
- check_model_deprecation_headers_callback=self._check_model_deprecation_header_callback_factory(model),
369
- )
370
-
371
- async for response in single_response:
372
- return ChatCompletionResponse(**response)
373
-
374
- raise MistralException("No response received")
375
-
376
- async def completion_stream(
377
- self,
378
- model: str,
379
- prompt: str,
380
- suffix: Optional[str] = None,
381
- temperature: Optional[float] = None,
382
- max_tokens: Optional[int] = None,
383
- top_p: Optional[float] = None,
384
- random_seed: Optional[int] = None,
385
- stop: Optional[List[str]] = None,
386
- ) -> AsyncGenerator[ChatCompletionStreamResponse, None]:
387
- """An asynchronous completion endpoint that returns a streaming response.
388
-
389
- Args:
390
- model (str): model the name of the model to get completions with, e.g. codestral-latest
391
- prompt (str): the prompt to complete
392
- suffix (Optional[str]): the suffix to append to the prompt for fill-in-the-middle completion
393
- temperature (Optional[float], optional): temperature the temperature to use for sampling, e.g. 0.5.
394
- max_tokens (Optional[int], optional): the maximum number of tokens to generate, e.g. 100. Defaults to None.
395
- top_p (Optional[float], optional): the cumulative probability of tokens to generate, e.g. 0.9.
396
- Defaults to None.
397
- random_seed (Optional[int], optional): the random seed to use for sampling, e.g. 42. Defaults to None.
398
- stop (Optional[List[str]], optional): a list of tokens to stop generation at, e.g. ['/n/n']
399
-
400
- Returns:
401
- Dict[str, Any]: a response object containing the generated text.
402
- """
403
- request = self._make_completion_request(
404
- prompt,
405
- model,
406
- suffix,
407
- temperature,
408
- max_tokens,
409
- top_p,
410
- random_seed,
411
- stop,
412
- stream=True,
413
- )
414
- async_response = self._request(
415
- "post",
416
- request,
417
- "v1/fim/completions",
418
- stream=True,
419
- check_model_deprecation_headers_callback=self._check_model_deprecation_header_callback_factory(model),
420
- )
421
-
422
- async for json_response in async_response:
423
- yield ChatCompletionStreamResponse(**json_response)
15
+ raise NotImplementedError(MIGRATION_MESSAGE)