mistralai 0.4.2__py3-none-any.whl → 1.0.0__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 (246) 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/agents.py +434 -0
  9. mistralai/async_client.py +5 -413
  10. mistralai/basesdk.py +253 -0
  11. mistralai/chat.py +470 -0
  12. mistralai/client.py +5 -414
  13. mistralai/embeddings.py +182 -0
  14. mistralai/files.py +600 -84
  15. mistralai/fim.py +438 -0
  16. mistralai/fine_tuning.py +16 -0
  17. mistralai/httpclient.py +78 -0
  18. mistralai/jobs.py +822 -150
  19. mistralai/models/__init__.py +82 -0
  20. mistralai/models/agentscompletionrequest.py +96 -0
  21. mistralai/models/agentscompletionstreamrequest.py +92 -0
  22. mistralai/models/archiveftmodelout.py +19 -0
  23. mistralai/models/assistantmessage.py +53 -0
  24. mistralai/models/chatcompletionchoice.py +22 -0
  25. mistralai/models/chatcompletionrequest.py +109 -0
  26. mistralai/models/chatcompletionresponse.py +27 -0
  27. mistralai/models/chatcompletionstreamrequest.py +107 -0
  28. mistralai/models/checkpointout.py +25 -0
  29. mistralai/models/completionchunk.py +27 -0
  30. mistralai/models/completionevent.py +15 -0
  31. mistralai/models/completionresponsestreamchoice.py +48 -0
  32. mistralai/models/contentchunk.py +17 -0
  33. mistralai/models/delete_model_v1_models_model_id_deleteop.py +18 -0
  34. mistralai/models/deletefileout.py +24 -0
  35. mistralai/models/deletemodelout.py +25 -0
  36. mistralai/models/deltamessage.py +47 -0
  37. mistralai/models/detailedjobout.py +91 -0
  38. mistralai/models/embeddingrequest.py +61 -0
  39. mistralai/models/embeddingresponse.py +24 -0
  40. mistralai/models/embeddingresponsedata.py +19 -0
  41. mistralai/models/eventout.py +50 -0
  42. mistralai/models/files_api_routes_delete_fileop.py +16 -0
  43. mistralai/models/files_api_routes_retrieve_fileop.py +16 -0
  44. mistralai/models/files_api_routes_upload_fileop.py +51 -0
  45. mistralai/models/fileschema.py +71 -0
  46. mistralai/models/fimcompletionrequest.py +94 -0
  47. mistralai/models/fimcompletionresponse.py +27 -0
  48. mistralai/models/fimcompletionstreamrequest.py +92 -0
  49. mistralai/models/finetuneablemodel.py +8 -0
  50. mistralai/models/ftmodelcapabilitiesout.py +21 -0
  51. mistralai/models/ftmodelout.py +65 -0
  52. mistralai/models/function.py +19 -0
  53. mistralai/models/functioncall.py +22 -0
  54. mistralai/models/githubrepositoryin.py +52 -0
  55. mistralai/models/githubrepositoryout.py +52 -0
  56. mistralai/models/httpvalidationerror.py +23 -0
  57. mistralai/models/jobin.py +73 -0
  58. mistralai/models/jobmetadataout.py +54 -0
  59. mistralai/models/jobout.py +107 -0
  60. mistralai/models/jobs_api_routes_fine_tuning_archive_fine_tuned_modelop.py +18 -0
  61. mistralai/models/jobs_api_routes_fine_tuning_cancel_fine_tuning_jobop.py +18 -0
  62. mistralai/models/jobs_api_routes_fine_tuning_create_fine_tuning_jobop.py +15 -0
  63. mistralai/models/jobs_api_routes_fine_tuning_get_fine_tuning_jobop.py +18 -0
  64. mistralai/models/jobs_api_routes_fine_tuning_get_fine_tuning_jobsop.py +81 -0
  65. mistralai/models/jobs_api_routes_fine_tuning_start_fine_tuning_jobop.py +16 -0
  66. mistralai/models/jobs_api_routes_fine_tuning_unarchive_fine_tuned_modelop.py +18 -0
  67. mistralai/models/jobs_api_routes_fine_tuning_update_fine_tuned_modelop.py +21 -0
  68. mistralai/models/jobsout.py +20 -0
  69. mistralai/models/legacyjobmetadataout.py +80 -0
  70. mistralai/models/listfilesout.py +17 -0
  71. mistralai/models/metricout.py +50 -0
  72. mistralai/models/modelcapabilities.py +21 -0
  73. mistralai/models/modelcard.py +66 -0
  74. mistralai/models/modellist.py +18 -0
  75. mistralai/models/responseformat.py +18 -0
  76. mistralai/models/retrieve_model_v1_models_model_id_getop.py +18 -0
  77. mistralai/models/retrievefileout.py +71 -0
  78. mistralai/models/sampletype.py +7 -0
  79. mistralai/models/sdkerror.py +22 -0
  80. mistralai/models/security.py +16 -0
  81. mistralai/models/source.py +7 -0
  82. mistralai/models/systemmessage.py +26 -0
  83. mistralai/models/textchunk.py +17 -0
  84. mistralai/models/tool.py +18 -0
  85. mistralai/models/toolcall.py +20 -0
  86. mistralai/models/toolmessage.py +50 -0
  87. mistralai/models/trainingfile.py +17 -0
  88. mistralai/models/trainingparameters.py +48 -0
  89. mistralai/models/trainingparametersin.py +56 -0
  90. mistralai/models/unarchiveftmodelout.py +19 -0
  91. mistralai/models/updateftmodelin.py +44 -0
  92. mistralai/models/uploadfileout.py +71 -0
  93. mistralai/models/usageinfo.py +18 -0
  94. mistralai/models/usermessage.py +26 -0
  95. mistralai/models/validationerror.py +24 -0
  96. mistralai/models/wandbintegration.py +56 -0
  97. mistralai/models/wandbintegrationout.py +52 -0
  98. mistralai/models_.py +928 -0
  99. mistralai/py.typed +1 -0
  100. mistralai/sdk.py +119 -0
  101. mistralai/sdkconfiguration.py +54 -0
  102. mistralai/types/__init__.py +21 -0
  103. mistralai/types/basemodel.py +39 -0
  104. mistralai/utils/__init__.py +86 -0
  105. mistralai/utils/annotations.py +19 -0
  106. mistralai/utils/enums.py +34 -0
  107. mistralai/utils/eventstreaming.py +178 -0
  108. mistralai/utils/forms.py +207 -0
  109. mistralai/utils/headers.py +136 -0
  110. mistralai/utils/logger.py +16 -0
  111. mistralai/utils/metadata.py +118 -0
  112. mistralai/utils/queryparams.py +203 -0
  113. mistralai/utils/requestbodies.py +66 -0
  114. mistralai/utils/retries.py +216 -0
  115. mistralai/utils/security.py +185 -0
  116. mistralai/utils/serializers.py +181 -0
  117. mistralai/utils/url.py +150 -0
  118. mistralai/utils/values.py +128 -0
  119. {mistralai-0.4.2.dist-info → mistralai-1.0.0.dist-info}/LICENSE +1 -1
  120. mistralai-1.0.0.dist-info/METADATA +695 -0
  121. mistralai-1.0.0.dist-info/RECORD +235 -0
  122. mistralai_azure/__init__.py +5 -0
  123. mistralai_azure/_hooks/__init__.py +5 -0
  124. mistralai_azure/_hooks/custom_user_agent.py +16 -0
  125. mistralai_azure/_hooks/registration.py +15 -0
  126. mistralai_azure/_hooks/sdkhooks.py +57 -0
  127. mistralai_azure/_hooks/types.py +76 -0
  128. mistralai_azure/basesdk.py +253 -0
  129. mistralai_azure/chat.py +470 -0
  130. mistralai_azure/httpclient.py +78 -0
  131. mistralai_azure/models/__init__.py +28 -0
  132. mistralai_azure/models/assistantmessage.py +53 -0
  133. mistralai_azure/models/chatcompletionchoice.py +22 -0
  134. mistralai_azure/models/chatcompletionrequest.py +109 -0
  135. mistralai_azure/models/chatcompletionresponse.py +27 -0
  136. mistralai_azure/models/chatcompletionstreamrequest.py +107 -0
  137. mistralai_azure/models/completionchunk.py +27 -0
  138. mistralai_azure/models/completionevent.py +15 -0
  139. mistralai_azure/models/completionresponsestreamchoice.py +48 -0
  140. mistralai_azure/models/contentchunk.py +17 -0
  141. mistralai_azure/models/deltamessage.py +47 -0
  142. mistralai_azure/models/function.py +19 -0
  143. mistralai_azure/models/functioncall.py +22 -0
  144. mistralai_azure/models/httpvalidationerror.py +23 -0
  145. mistralai_azure/models/responseformat.py +18 -0
  146. mistralai_azure/models/sdkerror.py +22 -0
  147. mistralai_azure/models/security.py +16 -0
  148. mistralai_azure/models/systemmessage.py +26 -0
  149. mistralai_azure/models/textchunk.py +17 -0
  150. mistralai_azure/models/tool.py +18 -0
  151. mistralai_azure/models/toolcall.py +20 -0
  152. mistralai_azure/models/toolmessage.py +50 -0
  153. mistralai_azure/models/usageinfo.py +18 -0
  154. mistralai_azure/models/usermessage.py +26 -0
  155. mistralai_azure/models/validationerror.py +24 -0
  156. mistralai_azure/py.typed +1 -0
  157. mistralai_azure/sdk.py +107 -0
  158. mistralai_azure/sdkconfiguration.py +54 -0
  159. mistralai_azure/types/__init__.py +21 -0
  160. mistralai_azure/types/basemodel.py +39 -0
  161. mistralai_azure/utils/__init__.py +84 -0
  162. mistralai_azure/utils/annotations.py +19 -0
  163. mistralai_azure/utils/enums.py +34 -0
  164. mistralai_azure/utils/eventstreaming.py +178 -0
  165. mistralai_azure/utils/forms.py +207 -0
  166. mistralai_azure/utils/headers.py +136 -0
  167. mistralai_azure/utils/logger.py +16 -0
  168. mistralai_azure/utils/metadata.py +118 -0
  169. mistralai_azure/utils/queryparams.py +203 -0
  170. mistralai_azure/utils/requestbodies.py +66 -0
  171. mistralai_azure/utils/retries.py +216 -0
  172. mistralai_azure/utils/security.py +168 -0
  173. mistralai_azure/utils/serializers.py +181 -0
  174. mistralai_azure/utils/url.py +150 -0
  175. mistralai_azure/utils/values.py +128 -0
  176. mistralai_gcp/__init__.py +5 -0
  177. mistralai_gcp/_hooks/__init__.py +5 -0
  178. mistralai_gcp/_hooks/custom_user_agent.py +16 -0
  179. mistralai_gcp/_hooks/registration.py +15 -0
  180. mistralai_gcp/_hooks/sdkhooks.py +57 -0
  181. mistralai_gcp/_hooks/types.py +76 -0
  182. mistralai_gcp/basesdk.py +253 -0
  183. mistralai_gcp/chat.py +458 -0
  184. mistralai_gcp/fim.py +438 -0
  185. mistralai_gcp/httpclient.py +78 -0
  186. mistralai_gcp/models/__init__.py +31 -0
  187. mistralai_gcp/models/assistantmessage.py +53 -0
  188. mistralai_gcp/models/chatcompletionchoice.py +22 -0
  189. mistralai_gcp/models/chatcompletionrequest.py +105 -0
  190. mistralai_gcp/models/chatcompletionresponse.py +27 -0
  191. mistralai_gcp/models/chatcompletionstreamrequest.py +103 -0
  192. mistralai_gcp/models/completionchunk.py +27 -0
  193. mistralai_gcp/models/completionevent.py +15 -0
  194. mistralai_gcp/models/completionresponsestreamchoice.py +48 -0
  195. mistralai_gcp/models/contentchunk.py +17 -0
  196. mistralai_gcp/models/deltamessage.py +47 -0
  197. mistralai_gcp/models/fimcompletionrequest.py +94 -0
  198. mistralai_gcp/models/fimcompletionresponse.py +27 -0
  199. mistralai_gcp/models/fimcompletionstreamrequest.py +92 -0
  200. mistralai_gcp/models/function.py +19 -0
  201. mistralai_gcp/models/functioncall.py +22 -0
  202. mistralai_gcp/models/httpvalidationerror.py +23 -0
  203. mistralai_gcp/models/responseformat.py +18 -0
  204. mistralai_gcp/models/sdkerror.py +22 -0
  205. mistralai_gcp/models/security.py +16 -0
  206. mistralai_gcp/models/systemmessage.py +26 -0
  207. mistralai_gcp/models/textchunk.py +17 -0
  208. mistralai_gcp/models/tool.py +18 -0
  209. mistralai_gcp/models/toolcall.py +20 -0
  210. mistralai_gcp/models/toolmessage.py +50 -0
  211. mistralai_gcp/models/usageinfo.py +18 -0
  212. mistralai_gcp/models/usermessage.py +26 -0
  213. mistralai_gcp/models/validationerror.py +24 -0
  214. mistralai_gcp/py.typed +1 -0
  215. mistralai_gcp/sdk.py +174 -0
  216. mistralai_gcp/sdkconfiguration.py +54 -0
  217. mistralai_gcp/types/__init__.py +21 -0
  218. mistralai_gcp/types/basemodel.py +39 -0
  219. mistralai_gcp/utils/__init__.py +84 -0
  220. mistralai_gcp/utils/annotations.py +19 -0
  221. mistralai_gcp/utils/enums.py +34 -0
  222. mistralai_gcp/utils/eventstreaming.py +178 -0
  223. mistralai_gcp/utils/forms.py +207 -0
  224. mistralai_gcp/utils/headers.py +136 -0
  225. mistralai_gcp/utils/logger.py +16 -0
  226. mistralai_gcp/utils/metadata.py +118 -0
  227. mistralai_gcp/utils/queryparams.py +203 -0
  228. mistralai_gcp/utils/requestbodies.py +66 -0
  229. mistralai_gcp/utils/retries.py +216 -0
  230. mistralai_gcp/utils/security.py +168 -0
  231. mistralai_gcp/utils/serializers.py +181 -0
  232. mistralai_gcp/utils/url.py +150 -0
  233. mistralai_gcp/utils/values.py +128 -0
  234. py.typed +1 -0
  235. mistralai/client_base.py +0 -211
  236. mistralai/constants.py +0 -5
  237. mistralai/exceptions.py +0 -54
  238. mistralai/models/chat_completion.py +0 -93
  239. mistralai/models/common.py +0 -9
  240. mistralai/models/embeddings.py +0 -19
  241. mistralai/models/files.py +0 -23
  242. mistralai/models/jobs.py +0 -100
  243. mistralai/models/models.py +0 -39
  244. mistralai-0.4.2.dist-info/METADATA +0 -82
  245. mistralai-0.4.2.dist-info/RECORD +0 -20
  246. {mistralai-0.4.2.dist-info → mistralai-1.0.0.dist-info}/WHEEL +0 -0
mistralai/py.typed CHANGED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561. The package enables type hints.
mistralai/sdk.py ADDED
@@ -0,0 +1,119 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from .basesdk import BaseSDK
4
+ from .httpclient import AsyncHttpClient, HttpClient
5
+ from .sdkconfiguration import SDKConfiguration
6
+ from .utils.logger import Logger, NoOpLogger
7
+ from .utils.retries import RetryConfig
8
+ import httpx
9
+ from mistralai import models, utils
10
+ from mistralai._hooks import SDKHooks
11
+ from mistralai.agents import Agents
12
+ from mistralai.chat import Chat
13
+ from mistralai.embeddings import Embeddings
14
+ from mistralai.files import Files
15
+ from mistralai.fim import Fim
16
+ from mistralai.fine_tuning import FineTuning
17
+ from mistralai.models_ import Models
18
+ from mistralai.types import OptionalNullable, UNSET
19
+ from typing import Any, Callable, Dict, Optional, Union
20
+
21
+ class Mistral(BaseSDK):
22
+ r"""Mistral AI API: Our Chat Completion and Embeddings APIs specification. Create your account on [La Plateforme](https://console.mistral.ai) to get access and read the [docs](https://docs.mistral.ai) to learn how to use it."""
23
+ models: Models
24
+ r"""Model Management API"""
25
+ files: Files
26
+ r"""Files API"""
27
+ fine_tuning: FineTuning
28
+ chat: Chat
29
+ r"""Chat Completion API."""
30
+ fim: Fim
31
+ r"""Fill-in-the-middle API."""
32
+ agents: Agents
33
+ r"""Agents API."""
34
+ embeddings: Embeddings
35
+ r"""Embeddings API."""
36
+ def __init__(
37
+ self,
38
+ api_key: Optional[Union[Optional[str], Callable[[], Optional[str]]]] = None,
39
+ server: Optional[str] = None,
40
+ server_url: Optional[str] = None,
41
+ url_params: Optional[Dict[str, str]] = None,
42
+ client: Optional[HttpClient] = None,
43
+ async_client: Optional[AsyncHttpClient] = None,
44
+ retry_config: OptionalNullable[RetryConfig] = UNSET,
45
+ timeout_ms: Optional[int] = None,
46
+ debug_logger: Optional[Logger] = None
47
+ ) -> None:
48
+ r"""Instantiates the SDK configuring it with the provided parameters.
49
+
50
+ :param api_key: The api_key required for authentication
51
+ :param server: The server by name to use for all methods
52
+ :param server_url: The server URL to use for all methods
53
+ :param url_params: Parameters to optionally template the server URL with
54
+ :param client: The HTTP client to use for all synchronous methods
55
+ :param async_client: The Async HTTP client to use for all asynchronous methods
56
+ :param retry_config: The retry configuration to use for all supported methods
57
+ :param timeout_ms: Optional request timeout applied to each operation in milliseconds
58
+ """
59
+ if client is None:
60
+ client = httpx.Client()
61
+
62
+ assert issubclass(
63
+ type(client), HttpClient
64
+ ), "The provided client must implement the HttpClient protocol."
65
+
66
+ if async_client is None:
67
+ async_client = httpx.AsyncClient()
68
+
69
+ if debug_logger is None:
70
+ debug_logger = NoOpLogger()
71
+
72
+ assert issubclass(
73
+ type(async_client), AsyncHttpClient
74
+ ), "The provided async_client must implement the AsyncHttpClient protocol."
75
+
76
+ security: Any = None
77
+ if callable(api_key):
78
+ security = lambda: models.Security(api_key = api_key()) # pylint: disable=unnecessary-lambda-assignment
79
+ else:
80
+ security = models.Security(api_key = api_key)
81
+
82
+ if server_url is not None:
83
+ if url_params is not None:
84
+ server_url = utils.template_url(server_url, url_params)
85
+
86
+
87
+ BaseSDK.__init__(self, SDKConfiguration(
88
+ client=client,
89
+ async_client=async_client,
90
+ security=security,
91
+ server_url=server_url,
92
+ server=server,
93
+ retry_config=retry_config,
94
+ timeout_ms=timeout_ms,
95
+ debug_logger=debug_logger
96
+ ))
97
+
98
+ hooks = SDKHooks()
99
+
100
+ current_server_url, *_ = self.sdk_configuration.get_server_details()
101
+ server_url, self.sdk_configuration.client = hooks.sdk_init(current_server_url, self.sdk_configuration.client)
102
+ if current_server_url != server_url:
103
+ self.sdk_configuration.server_url = server_url
104
+
105
+ # pylint: disable=protected-access
106
+ self.sdk_configuration.__dict__["_hooks"] = hooks
107
+
108
+ self._init_sdks()
109
+
110
+
111
+ def _init_sdks(self):
112
+ self.models = Models(self.sdk_configuration)
113
+ self.files = Files(self.sdk_configuration)
114
+ self.fine_tuning = FineTuning(self.sdk_configuration)
115
+ self.chat = Chat(self.sdk_configuration)
116
+ self.fim = Fim(self.sdk_configuration)
117
+ self.agents = Agents(self.sdk_configuration)
118
+ self.embeddings = Embeddings(self.sdk_configuration)
119
+
@@ -0,0 +1,54 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+
4
+ from ._hooks import SDKHooks
5
+ from .httpclient import AsyncHttpClient, HttpClient
6
+ from .utils import Logger, RetryConfig, remove_suffix
7
+ from dataclasses import dataclass
8
+ from mistralai import models
9
+ from mistralai.types import OptionalNullable, UNSET
10
+ from pydantic import Field
11
+ from typing import Callable, Dict, Optional, Tuple, Union
12
+
13
+
14
+ SERVER_PROD = "prod"
15
+ r"""Production server"""
16
+ SERVERS = {
17
+ SERVER_PROD: "https://api.mistral.ai",
18
+ }
19
+ """Contains the list of servers available to the SDK"""
20
+
21
+
22
+ @dataclass
23
+ class SDKConfiguration:
24
+ client: HttpClient
25
+ async_client: AsyncHttpClient
26
+ debug_logger: Logger
27
+ security: Optional[Union[models.Security,Callable[[], models.Security]]] = None
28
+ server_url: Optional[str] = ""
29
+ server: Optional[str] = ""
30
+ language: str = "python"
31
+ openapi_doc_version: str = "0.0.2"
32
+ sdk_version: str = "1.0.0"
33
+ gen_version: str = "2.388.1"
34
+ user_agent: str = "speakeasy-sdk/python 1.0.0 2.388.1 0.0.2 mistralai"
35
+ retry_config: OptionalNullable[RetryConfig] = Field(default_factory=lambda: UNSET)
36
+ timeout_ms: Optional[int] = None
37
+
38
+ def __post_init__(self):
39
+ self._hooks = SDKHooks()
40
+
41
+ def get_server_details(self) -> Tuple[str, Dict[str, str]]:
42
+ if self.server_url is not None and self.server_url:
43
+ return remove_suffix(self.server_url, "/"), {}
44
+ if not self.server:
45
+ self.server = SERVER_PROD
46
+
47
+ if self.server not in SERVERS:
48
+ raise ValueError(f"Invalid server \"{self.server}\"")
49
+
50
+ return SERVERS[self.server], {}
51
+
52
+
53
+ def get_hooks(self) -> SDKHooks:
54
+ return self._hooks
@@ -0,0 +1,21 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from .basemodel import (
4
+ BaseModel,
5
+ Nullable,
6
+ OptionalNullable,
7
+ UnrecognizedInt,
8
+ UnrecognizedStr,
9
+ UNSET,
10
+ UNSET_SENTINEL,
11
+ )
12
+
13
+ __all__ = [
14
+ "BaseModel",
15
+ "Nullable",
16
+ "OptionalNullable",
17
+ "UnrecognizedInt",
18
+ "UnrecognizedStr",
19
+ "UNSET",
20
+ "UNSET_SENTINEL",
21
+ ]
@@ -0,0 +1,39 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from pydantic import ConfigDict, model_serializer
4
+ from pydantic import BaseModel as PydanticBaseModel
5
+ from typing import TYPE_CHECKING, Literal, Optional, TypeVar, Union, NewType
6
+ from typing_extensions import TypeAliasType, TypeAlias
7
+
8
+
9
+ class BaseModel(PydanticBaseModel):
10
+ model_config = ConfigDict(
11
+ populate_by_name=True, arbitrary_types_allowed=True, protected_namespaces=()
12
+ )
13
+
14
+
15
+ class Unset(BaseModel):
16
+ @model_serializer(mode="plain")
17
+ def serialize_model(self):
18
+ return UNSET_SENTINEL
19
+
20
+ def __bool__(self) -> Literal[False]:
21
+ return False
22
+
23
+
24
+ UNSET = Unset()
25
+ UNSET_SENTINEL = "~?~unset~?~sentinel~?~"
26
+
27
+
28
+ T = TypeVar("T")
29
+ if TYPE_CHECKING:
30
+ Nullable: TypeAlias = Union[T, None]
31
+ OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], Unset]
32
+ else:
33
+ Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,))
34
+ OptionalNullable = TypeAliasType(
35
+ "OptionalNullable", Union[Optional[Nullable[T]], Unset], type_params=(T,)
36
+ )
37
+
38
+ UnrecognizedInt = NewType("UnrecognizedInt", int)
39
+ UnrecognizedStr = NewType("UnrecognizedStr", str)
@@ -0,0 +1,86 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from .annotations import get_discriminator
4
+ from .enums import OpenEnumMeta
5
+ from .headers import get_headers, get_response_headers
6
+ from .metadata import (
7
+ FieldMetadata,
8
+ find_metadata,
9
+ FormMetadata,
10
+ HeaderMetadata,
11
+ MultipartFormMetadata,
12
+ PathParamMetadata,
13
+ QueryParamMetadata,
14
+ RequestMetadata,
15
+ SecurityMetadata,
16
+ )
17
+ from .queryparams import get_query_params
18
+ from .retries import BackoffStrategy, Retries, retry, retry_async, RetryConfig
19
+ from .requestbodies import serialize_request_body, SerializedRequestBody
20
+ from .security import get_security, get_security_from_env
21
+
22
+ from .serializers import (
23
+ get_pydantic_model,
24
+ marshal_json,
25
+ unmarshal,
26
+ unmarshal_json,
27
+ serialize_decimal,
28
+ serialize_float,
29
+ serialize_int,
30
+ stream_to_text,
31
+ validate_decimal,
32
+ validate_float,
33
+ validate_int,
34
+ validate_open_enum,
35
+ )
36
+ from .url import generate_url, template_url, remove_suffix
37
+ from .values import get_global_from_env, match_content_type, match_status_codes, match_response
38
+ from .logger import Logger, get_body_content, NoOpLogger
39
+
40
+ __all__ = [
41
+ "BackoffStrategy",
42
+ "FieldMetadata",
43
+ "find_metadata",
44
+ "FormMetadata",
45
+ "generate_url",
46
+ "get_body_content",
47
+ "get_discriminator",
48
+ "get_global_from_env",
49
+ "get_headers",
50
+ "get_pydantic_model",
51
+ "get_query_params",
52
+ "get_response_headers",
53
+ "get_security",
54
+ "get_security_from_env",
55
+ "HeaderMetadata",
56
+ "Logger",
57
+ "marshal_json",
58
+ "match_content_type",
59
+ "match_status_codes",
60
+ "match_response",
61
+ "MultipartFormMetadata",
62
+ "NoOpLogger",
63
+ "OpenEnumMeta",
64
+ "PathParamMetadata",
65
+ "QueryParamMetadata",
66
+ "remove_suffix",
67
+ "Retries",
68
+ "retry",
69
+ "retry_async",
70
+ "RetryConfig",
71
+ "RequestMetadata",
72
+ "SecurityMetadata",
73
+ "serialize_decimal",
74
+ "serialize_float",
75
+ "serialize_int",
76
+ "serialize_request_body",
77
+ "SerializedRequestBody",
78
+ "stream_to_text",
79
+ "template_url",
80
+ "unmarshal",
81
+ "unmarshal_json",
82
+ "validate_decimal",
83
+ "validate_float",
84
+ "validate_int",
85
+ "validate_open_enum",
86
+ ]
@@ -0,0 +1,19 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from typing import Any
4
+
5
+ def get_discriminator(model: Any, fieldname: str, key: str) -> str:
6
+ if isinstance(model, dict):
7
+ try:
8
+ return f'{model.get(key)}'
9
+ except AttributeError as e:
10
+ raise ValueError(f'Could not find discriminator key {key} in {model}') from e
11
+
12
+ if hasattr(model, fieldname):
13
+ return f'{getattr(model, fieldname)}'
14
+
15
+ fieldname = fieldname.upper()
16
+ if hasattr(model, fieldname):
17
+ return f'{getattr(model, fieldname)}'
18
+
19
+ raise ValueError(f'Could not find discriminator field {fieldname} in {model}')
@@ -0,0 +1,34 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ import enum
4
+
5
+
6
+ class OpenEnumMeta(enum.EnumMeta):
7
+ def __call__(
8
+ cls, value, names=None, *, module=None, qualname=None, type=None, start=1
9
+ ):
10
+ # The `type` kwarg also happens to be a built-in that pylint flags as
11
+ # redeclared. Safe to ignore this lint rule with this scope.
12
+ # pylint: disable=redefined-builtin
13
+
14
+ if names is not None:
15
+ return super().__call__(
16
+ value,
17
+ names=names,
18
+ module=module,
19
+ qualname=qualname,
20
+ type=type,
21
+ start=start,
22
+ )
23
+
24
+ try:
25
+ return super().__call__(
26
+ value,
27
+ names=names, # pyright: ignore[reportArgumentType]
28
+ module=module,
29
+ qualname=qualname,
30
+ type=type,
31
+ start=start,
32
+ )
33
+ except ValueError:
34
+ return value
@@ -0,0 +1,178 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ import re
4
+ import json
5
+ from typing import Callable, TypeVar, Optional, Generator, AsyncGenerator, Tuple
6
+ import httpx
7
+
8
+ T = TypeVar("T")
9
+
10
+
11
+ class ServerEvent:
12
+ id: Optional[str] = None
13
+ event: Optional[str] = None
14
+ data: Optional[str] = None
15
+ retry: Optional[int] = None
16
+
17
+
18
+ MESSAGE_BOUNDARIES = [
19
+ b"\r\n\r\n",
20
+ b"\n\n",
21
+ b"\r\r",
22
+ ]
23
+
24
+
25
+ async def stream_events_async(
26
+ response: httpx.Response,
27
+ decoder: Callable[[str], T],
28
+ sentinel: Optional[str] = None,
29
+ ) -> AsyncGenerator[T, None]:
30
+ buffer = bytearray()
31
+ position = 0
32
+ discard = False
33
+ async for chunk in response.aiter_bytes():
34
+ # We've encountered the sentinel value and should no longer process
35
+ # incoming data. Instead we throw new data away until the server closes
36
+ # the connection.
37
+ if discard:
38
+ continue
39
+
40
+ buffer += chunk
41
+ for i in range(position, len(buffer)):
42
+ char = buffer[i : i + 1]
43
+ seq: Optional[bytes] = None
44
+ if char in [b"\r", b"\n"]:
45
+ for boundary in MESSAGE_BOUNDARIES:
46
+ seq = _peek_sequence(i, buffer, boundary)
47
+ if seq is not None:
48
+ break
49
+ if seq is None:
50
+ continue
51
+
52
+ block = buffer[position:i]
53
+ position = i + len(seq)
54
+ event, discard = _parse_event(block, decoder, sentinel)
55
+ if event is not None:
56
+ yield event
57
+
58
+ if position > 0:
59
+ buffer = buffer[position:]
60
+ position = 0
61
+
62
+ event, discard = _parse_event(buffer, decoder, sentinel)
63
+ if event is not None:
64
+ yield event
65
+
66
+
67
+ def stream_events(
68
+ response: httpx.Response,
69
+ decoder: Callable[[str], T],
70
+ sentinel: Optional[str] = None,
71
+ ) -> Generator[T, None, None]:
72
+ buffer = bytearray()
73
+ position = 0
74
+ discard = False
75
+ for chunk in response.iter_bytes():
76
+ # We've encountered the sentinel value and should no longer process
77
+ # incoming data. Instead we throw new data away until the server closes
78
+ # the connection.
79
+ if discard:
80
+ continue
81
+
82
+ buffer += chunk
83
+ for i in range(position, len(buffer)):
84
+ char = buffer[i : i + 1]
85
+ seq: Optional[bytes] = None
86
+ if char in [b"\r", b"\n"]:
87
+ for boundary in MESSAGE_BOUNDARIES:
88
+ seq = _peek_sequence(i, buffer, boundary)
89
+ if seq is not None:
90
+ break
91
+ if seq is None:
92
+ continue
93
+
94
+ block = buffer[position:i]
95
+ position = i + len(seq)
96
+ event, discard = _parse_event(block, decoder, sentinel)
97
+ if event is not None:
98
+ yield event
99
+
100
+ if position > 0:
101
+ buffer = buffer[position:]
102
+ position = 0
103
+
104
+ event, discard = _parse_event(buffer, decoder, sentinel)
105
+ if event is not None:
106
+ yield event
107
+
108
+
109
+ def _parse_event(
110
+ raw: bytearray, decoder: Callable[[str], T], sentinel: Optional[str] = None
111
+ ) -> Tuple[Optional[T], bool]:
112
+ block = raw.decode()
113
+ lines = re.split(r"\r?\n|\r", block)
114
+ publish = False
115
+ event = ServerEvent()
116
+ data = ""
117
+ for line in lines:
118
+ if not line:
119
+ continue
120
+
121
+ delim = line.find(":")
122
+ if delim <= 0:
123
+ continue
124
+
125
+ field = line[0:delim]
126
+ value = line[delim + 1 :] if delim < len(line) - 1 else ""
127
+ if len(value) and value[0] == " ":
128
+ value = value[1:]
129
+
130
+ if field == "event":
131
+ event.event = value
132
+ publish = True
133
+ elif field == "data":
134
+ data += value + "\n"
135
+ publish = True
136
+ elif field == "id":
137
+ event.id = value
138
+ publish = True
139
+ elif field == "retry":
140
+ event.retry = int(value) if value.isdigit() else None
141
+ publish = True
142
+
143
+ if sentinel and data == f"{sentinel}\n":
144
+ return None, True
145
+
146
+ if data:
147
+ data = data[:-1]
148
+ event.data = data
149
+
150
+ data_is_primitive = (
151
+ data.isnumeric() or data == "true" or data == "false" or data == "null"
152
+ )
153
+ data_is_json = (
154
+ data.startswith("{") or data.startswith("[") or data.startswith('"')
155
+ )
156
+
157
+ if data_is_primitive or data_is_json:
158
+ try:
159
+ event.data = json.loads(data)
160
+ except Exception:
161
+ pass
162
+
163
+ out = None
164
+ if publish:
165
+ out = decoder(json.dumps(event.__dict__))
166
+
167
+ return out, False
168
+
169
+
170
+ def _peek_sequence(position: int, buffer: bytearray, sequence: bytes):
171
+ if len(sequence) > (len(buffer) - position):
172
+ return None
173
+
174
+ for i, seq in enumerate(sequence):
175
+ if buffer[position + i] != seq:
176
+ return None
177
+
178
+ return sequence