retry_provider.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. from __future__ import annotations
  2. import random
  3. from ..typing import Type, List, CreateResult, Messages, AsyncResult
  4. from .types import BaseProvider, BaseRetryProvider, ProviderType
  5. from .response import ImageResponse
  6. from .. import debug
  7. from ..errors import RetryProviderError, RetryNoProviderError
  8. class IterListProvider(BaseRetryProvider):
  9. def __init__(
  10. self,
  11. providers: List[Type[BaseProvider]],
  12. shuffle: bool = True
  13. ) -> None:
  14. """
  15. Initialize the BaseRetryProvider.
  16. Args:
  17. providers (List[Type[BaseProvider]]): List of providers to use.
  18. shuffle (bool): Whether to shuffle the providers list.
  19. single_provider_retry (bool): Whether to retry a single provider if it fails.
  20. max_retries (int): Maximum number of retries for a single provider.
  21. """
  22. self.providers = providers
  23. self.shuffle = shuffle
  24. self.working = True
  25. self.last_provider: Type[BaseProvider] = None
  26. def create_completion(
  27. self,
  28. model: str,
  29. messages: Messages,
  30. stream: bool = False,
  31. ignore_stream: bool = False,
  32. ignored: list[str] = [],
  33. **kwargs,
  34. ) -> CreateResult:
  35. """
  36. Create a completion using available providers, with an option to stream the response.
  37. Args:
  38. model (str): The model to be used for completion.
  39. messages (Messages): The messages to be used for generating completion.
  40. stream (bool, optional): Flag to indicate if the response should be streamed. Defaults to False.
  41. Yields:
  42. CreateResult: Tokens or results from the completion.
  43. Raises:
  44. Exception: Any exception encountered during the completion process.
  45. """
  46. exceptions = {}
  47. started: bool = False
  48. for provider in self.get_providers(stream and not ignore_stream, ignored):
  49. self.last_provider = provider
  50. debug.log(f"Using {provider.__name__} provider")
  51. try:
  52. response = provider.get_create_function()(model, messages, stream=stream, **kwargs)
  53. for chunk in response:
  54. if chunk:
  55. yield chunk
  56. if isinstance(chunk, str) or isinstance(chunk, ImageResponse):
  57. started = True
  58. if started:
  59. return
  60. except Exception as e:
  61. exceptions[provider.__name__] = e
  62. debug.log(f"{provider.__name__}: {e.__class__.__name__}: {e}")
  63. if started:
  64. raise e
  65. raise_exceptions(exceptions)
  66. async def create_async_generator(
  67. self,
  68. model: str,
  69. messages: Messages,
  70. stream: bool = True,
  71. ignore_stream: bool = False,
  72. ignored: list[str] = [],
  73. **kwargs
  74. ) -> AsyncResult:
  75. exceptions = {}
  76. started: bool = False
  77. for provider in self.get_providers(stream and not ignore_stream, ignored):
  78. self.last_provider = provider
  79. debug.log(f"Using {provider.__name__} provider")
  80. try:
  81. response = provider.get_async_create_function()(model, messages, stream=stream, **kwargs)
  82. if hasattr(response, "__aiter__"):
  83. async for chunk in response:
  84. if chunk:
  85. yield chunk
  86. if isinstance(chunk, str) or isinstance(chunk, ImageResponse):
  87. started = True
  88. elif response:
  89. response = await response
  90. if response:
  91. yield response
  92. started = True
  93. if started:
  94. return
  95. except Exception as e:
  96. exceptions[provider.__name__] = e
  97. debug.log(f"{provider.__name__}: {e.__class__.__name__}: {e}")
  98. if started:
  99. raise e
  100. raise_exceptions(exceptions)
  101. def get_create_function(self) -> callable:
  102. return self.create_completion
  103. def get_async_create_function(self) -> callable:
  104. return self.create_async_generator
  105. def get_providers(self, stream: bool, ignored: list[str]) -> list[ProviderType]:
  106. providers = [p for p in self.providers if (p.supports_stream or not stream) and p.__name__ not in ignored]
  107. if self.shuffle:
  108. random.shuffle(providers)
  109. return providers
  110. class RetryProvider(IterListProvider):
  111. def __init__(
  112. self,
  113. providers: List[Type[BaseProvider]],
  114. shuffle: bool = True,
  115. single_provider_retry: bool = False,
  116. max_retries: int = 3,
  117. ) -> None:
  118. """
  119. Initialize the BaseRetryProvider.
  120. Args:
  121. providers (List[Type[BaseProvider]]): List of providers to use.
  122. shuffle (bool): Whether to shuffle the providers list.
  123. single_provider_retry (bool): Whether to retry a single provider if it fails.
  124. max_retries (int): Maximum number of retries for a single provider.
  125. """
  126. super().__init__(providers, shuffle)
  127. self.single_provider_retry = single_provider_retry
  128. self.max_retries = max_retries
  129. def create_completion(
  130. self,
  131. model: str,
  132. messages: Messages,
  133. stream: bool = False,
  134. **kwargs,
  135. ) -> CreateResult:
  136. """
  137. Create a completion using available providers, with an option to stream the response.
  138. Args:
  139. model (str): The model to be used for completion.
  140. messages (Messages): The messages to be used for generating completion.
  141. stream (bool, optional): Flag to indicate if the response should be streamed. Defaults to False.
  142. Yields:
  143. CreateResult: Tokens or results from the completion.
  144. Raises:
  145. Exception: Any exception encountered during the completion process.
  146. """
  147. if self.single_provider_retry:
  148. exceptions = {}
  149. started: bool = False
  150. provider = self.providers[0]
  151. self.last_provider = provider
  152. for attempt in range(self.max_retries):
  153. try:
  154. if debug.logging:
  155. print(f"Using {provider.__name__} provider (attempt {attempt + 1})")
  156. response = provider.get_create_function()(model, messages, stream=stream, **kwargs)
  157. for chunk in response:
  158. if isinstance(chunk, str) or isinstance(chunk, ImageResponse):
  159. yield chunk
  160. started = True
  161. if started:
  162. return
  163. except Exception as e:
  164. exceptions[provider.__name__] = e
  165. if debug.logging:
  166. print(f"{provider.__name__}: {e.__class__.__name__}: {e}")
  167. if started:
  168. raise e
  169. raise_exceptions(exceptions)
  170. else:
  171. yield from super().create_completion(model, messages, stream, **kwargs)
  172. async def create_async_generator(
  173. self,
  174. model: str,
  175. messages: Messages,
  176. stream: bool = True,
  177. **kwargs
  178. ) -> AsyncResult:
  179. exceptions = {}
  180. started = False
  181. if self.single_provider_retry:
  182. provider = self.providers[0]
  183. self.last_provider = provider
  184. for attempt in range(self.max_retries):
  185. try:
  186. debug.log(f"Using {provider.__name__} provider (attempt {attempt + 1})")
  187. response = provider.get_async_create_function()(model, messages, stream=stream, **kwargs)
  188. if hasattr(response, "__aiter__"):
  189. async for chunk in response:
  190. if isinstance(chunk, str) or isinstance(chunk, ImageResponse):
  191. yield chunk
  192. started = True
  193. else:
  194. response = await response
  195. if response:
  196. yield response
  197. started = True
  198. if started:
  199. return
  200. except Exception as e:
  201. exceptions[provider.__name__] = e
  202. if debug.logging:
  203. print(f"{provider.__name__}: {e.__class__.__name__}: {e}")
  204. raise_exceptions(exceptions)
  205. else:
  206. async for chunk in super().create_async_generator(model, messages, stream, **kwargs):
  207. yield chunk
  208. def raise_exceptions(exceptions: dict) -> None:
  209. """
  210. Raise a combined exception if any occurred during retries.
  211. Raises:
  212. RetryProviderError: If any provider encountered an exception.
  213. RetryNoProviderError: If no provider is found.
  214. """
  215. if exceptions:
  216. raise RetryProviderError("RetryProvider failed:\n" + "\n".join([
  217. f"{p}: {type(exception).__name__}: {exception}" for p, exception in exceptions.items()
  218. ]))
  219. raise RetryNoProviderError("No provider found")