11import asyncio
22import logging
33import warnings
4- from collections .abc import Iterable
4+ from collections .abc import Callable , Iterable
55
66import httpx
77from httpx import Response
1616 SecretStr ,
1717 model_validator ,
1818)
19+ from tenacity import retry , retry_if_exception_type , stop_after_attempt , wait_fixed
1920from tokenizers import Tokenizer # type: ignore[import]
2021from typing_extensions import Self
2122
@@ -133,7 +134,9 @@ class MistralAIEmbeddings(BaseModel, Embeddings):
133134 default_factory = secret_from_env ("MISTRAL_API_KEY" , default = "" ),
134135 )
135136 endpoint : str = "https://api.mistral.ai/v1/"
137+ max_retries : int | None = 5
136138 timeout : int = 120
139+ wait_time : int | None = 30
137140 max_concurrent_requests : int = 64
138141 tokenizer : Tokenizer = Field (default = None )
139142
@@ -210,6 +213,18 @@ def _get_batches(self, texts: list[str]) -> Iterable[list[str]]:
210213 if batch :
211214 yield batch
212215
216+ def _retry (self , func : Callable ) -> Callable :
217+ if self .max_retries is None or self .wait_time is None :
218+ return func
219+
220+ return retry (
221+ retry = retry_if_exception_type (
222+ (httpx .TimeoutException , httpx .HTTPStatusError )
223+ ),
224+ wait = wait_fixed (self .wait_time ),
225+ stop = stop_after_attempt (self .max_retries ),
226+ )(func )
227+
213228 def embed_documents (self , texts : list [str ]) -> list [list [float ]]:
214229 """Embed a list of document texts.
215230
@@ -223,6 +238,7 @@ def embed_documents(self, texts: list[str]) -> list[list[float]]:
223238 try :
224239 batch_responses = []
225240
241+ @self ._retry
226242 def _embed_batch (batch : list [str ]) -> Response :
227243 response = self .client .post (
228244 url = "/embeddings" ,
@@ -257,6 +273,7 @@ async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
257273 """
258274 try :
259275
276+ @self ._retry
260277 async def _aembed_batch (batch : list [str ]) -> Response :
261278 response = await self .async_client .post (
262279 url = "/embeddings" ,
0 commit comments