base_provider.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. from __future__ import annotations
  2. import sys
  3. import asyncio
  4. from asyncio import AbstractEventLoop
  5. from concurrent.futures import ThreadPoolExecutor
  6. from abc import abstractmethod
  7. from inspect import signature, Parameter
  8. from typing import Callable, Union
  9. from ..typing import CreateResult, AsyncResult, Messages
  10. from .types import BaseProvider
  11. from .response import FinishReason, BaseConversation, SynthesizeData
  12. from ..errors import NestAsyncioError, ModelNotSupportedError
  13. from .. import debug
  14. if sys.version_info < (3, 10):
  15. NoneType = type(None)
  16. else:
  17. from types import NoneType
  18. try:
  19. import nest_asyncio
  20. has_nest_asyncio = True
  21. except ImportError:
  22. has_nest_asyncio = False
  23. try:
  24. import uvloop
  25. has_uvloop = True
  26. except ImportError:
  27. has_uvloop = False
  28. # Set Windows event loop policy for better compatibility with asyncio and curl_cffi
  29. if sys.platform == 'win32':
  30. try:
  31. from curl_cffi import aio
  32. if not hasattr(aio, "_get_selector"):
  33. if isinstance(asyncio.get_event_loop_policy(), asyncio.WindowsProactorEventLoopPolicy):
  34. asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  35. except ImportError:
  36. pass
  37. def get_running_loop(check_nested: bool) -> Union[AbstractEventLoop, None]:
  38. try:
  39. loop = asyncio.get_running_loop()
  40. # Do not patch uvloop loop because its incompatible.
  41. if has_uvloop:
  42. if isinstance(loop, uvloop.Loop):
  43. return loop
  44. if not hasattr(loop.__class__, "_nest_patched"):
  45. if has_nest_asyncio:
  46. nest_asyncio.apply(loop)
  47. elif check_nested:
  48. raise NestAsyncioError('Install "nest_asyncio" package | pip install -U nest_asyncio')
  49. return loop
  50. except RuntimeError:
  51. pass
  52. # Fix for RuntimeError: async generator ignored GeneratorExit
  53. async def await_callback(callback: Callable):
  54. return await callback()
  55. class AbstractProvider(BaseProvider):
  56. """
  57. Abstract class for providing asynchronous functionality to derived classes.
  58. """
  59. @classmethod
  60. async def create_async(
  61. cls,
  62. model: str,
  63. messages: Messages,
  64. *,
  65. loop: AbstractEventLoop = None,
  66. executor: ThreadPoolExecutor = None,
  67. **kwargs
  68. ) -> str:
  69. """
  70. Asynchronously creates a result based on the given model and messages.
  71. Args:
  72. cls (type): The class on which this method is called.
  73. model (str): The model to use for creation.
  74. messages (Messages): The messages to process.
  75. loop (AbstractEventLoop, optional): The event loop to use. Defaults to None.
  76. executor (ThreadPoolExecutor, optional): The executor for running async tasks. Defaults to None.
  77. **kwargs: Additional keyword arguments.
  78. Returns:
  79. str: The created result as a string.
  80. """
  81. loop = loop or asyncio.get_running_loop()
  82. def create_func() -> str:
  83. return "".join(cls.create_completion(model, messages, False, **kwargs))
  84. return await asyncio.wait_for(
  85. loop.run_in_executor(executor, create_func),
  86. timeout=kwargs.get("timeout")
  87. )
  88. @classmethod
  89. def get_parameters(cls) -> dict[str, Parameter]:
  90. return signature(
  91. cls.create_async_generator if issubclass(cls, AsyncGeneratorProvider) else
  92. cls.create_async if issubclass(cls, AsyncProvider) else
  93. cls.create_completion
  94. ).parameters
  95. @classmethod
  96. @property
  97. def params(cls) -> str:
  98. """
  99. Returns the parameters supported by the provider.
  100. Args:
  101. cls (type): The class on which this property is called.
  102. Returns:
  103. str: A string listing the supported parameters.
  104. """
  105. def get_type_name(annotation: type) -> str:
  106. return annotation.__name__ if hasattr(annotation, "__name__") else str(annotation)
  107. args = ""
  108. for name, param in cls.get_parameters().items():
  109. if name in ("self", "kwargs") or (name == "stream" and not cls.supports_stream):
  110. continue
  111. args += f"\n {name}"
  112. args += f": {get_type_name(param.annotation)}" if param.annotation is not Parameter.empty else ""
  113. default_value = f'"{param.default}"' if isinstance(param.default, str) else param.default
  114. args += f" = {default_value}" if param.default is not Parameter.empty else ""
  115. args += ","
  116. return f"g4f.Provider.{cls.__name__} supports: ({args}\n)"
  117. class AsyncProvider(AbstractProvider):
  118. """
  119. Provides asynchronous functionality for creating completions.
  120. """
  121. @classmethod
  122. def create_completion(
  123. cls,
  124. model: str,
  125. messages: Messages,
  126. stream: bool = False,
  127. **kwargs
  128. ) -> CreateResult:
  129. """
  130. Creates a completion result synchronously.
  131. Args:
  132. cls (type): The class on which this method is called.
  133. model (str): The model to use for creation.
  134. messages (Messages): The messages to process.
  135. stream (bool): Indicates whether to stream the results. Defaults to False.
  136. loop (AbstractEventLoop, optional): The event loop to use. Defaults to None.
  137. **kwargs: Additional keyword arguments.
  138. Returns:
  139. CreateResult: The result of the completion creation.
  140. """
  141. get_running_loop(check_nested=False)
  142. yield asyncio.run(cls.create_async(model, messages, **kwargs))
  143. @staticmethod
  144. @abstractmethod
  145. async def create_async(
  146. model: str,
  147. messages: Messages,
  148. **kwargs
  149. ) -> str:
  150. """
  151. Abstract method for creating asynchronous results.
  152. Args:
  153. model (str): The model to use for creation.
  154. messages (Messages): The messages to process.
  155. **kwargs: Additional keyword arguments.
  156. Raises:
  157. NotImplementedError: If this method is not overridden in derived classes.
  158. Returns:
  159. str: The created result as a string.
  160. """
  161. raise NotImplementedError()
  162. class AsyncGeneratorProvider(AsyncProvider):
  163. """
  164. Provides asynchronous generator functionality for streaming results.
  165. """
  166. supports_stream = True
  167. @classmethod
  168. def create_completion(
  169. cls,
  170. model: str,
  171. messages: Messages,
  172. stream: bool = True,
  173. **kwargs
  174. ) -> CreateResult:
  175. """
  176. Creates a streaming completion result synchronously.
  177. Args:
  178. cls (type): The class on which this method is called.
  179. model (str): The model to use for creation.
  180. messages (Messages): The messages to process.
  181. stream (bool): Indicates whether to stream the results. Defaults to True.
  182. loop (AbstractEventLoop, optional): The event loop to use. Defaults to None.
  183. **kwargs: Additional keyword arguments.
  184. Returns:
  185. CreateResult: The result of the streaming completion creation.
  186. """
  187. loop = get_running_loop(check_nested=False)
  188. new_loop = False
  189. if loop is None:
  190. loop = asyncio.new_event_loop()
  191. asyncio.set_event_loop(loop)
  192. new_loop = True
  193. generator = cls.create_async_generator(model, messages, stream=stream, **kwargs)
  194. gen = generator.__aiter__()
  195. try:
  196. while True:
  197. yield loop.run_until_complete(await_callback(gen.__anext__))
  198. except StopAsyncIteration:
  199. pass
  200. finally:
  201. if new_loop:
  202. loop.close()
  203. asyncio.set_event_loop(None)
  204. @classmethod
  205. async def create_async(
  206. cls,
  207. model: str,
  208. messages: Messages,
  209. **kwargs
  210. ) -> str:
  211. """
  212. Asynchronously creates a result from a generator.
  213. Args:
  214. cls (type): The class on which this method is called.
  215. model (str): The model to use for creation.
  216. messages (Messages): The messages to process.
  217. **kwargs: Additional keyword arguments.
  218. Returns:
  219. str: The created result as a string.
  220. """
  221. return "".join([
  222. str(chunk) async for chunk in cls.create_async_generator(model, messages, stream=False, **kwargs)
  223. if not isinstance(chunk, (Exception, FinishReason, BaseConversation, SynthesizeData))
  224. ])
  225. @staticmethod
  226. @abstractmethod
  227. async def create_async_generator(
  228. model: str,
  229. messages: Messages,
  230. stream: bool = True,
  231. **kwargs
  232. ) -> AsyncResult:
  233. """
  234. Abstract method for creating an asynchronous generator.
  235. Args:
  236. model (str): The model to use for creation.
  237. messages (Messages): The messages to process.
  238. stream (bool): Indicates whether to stream the results. Defaults to True.
  239. **kwargs: Additional keyword arguments.
  240. Raises:
  241. NotImplementedError: If this method is not overridden in derived classes.
  242. Returns:
  243. AsyncResult: An asynchronous generator yielding results.
  244. """
  245. raise NotImplementedError()
  246. class ProviderModelMixin:
  247. default_model: str = None
  248. models: list[str] = []
  249. model_aliases: dict[str, str] = {}
  250. image_models: list = None
  251. @classmethod
  252. def get_models(cls) -> list[str]:
  253. if not cls.models and cls.default_model is not None:
  254. return [cls.default_model]
  255. return cls.models
  256. @classmethod
  257. def get_model(cls, model: str) -> str:
  258. if not model and cls.default_model is not None:
  259. model = cls.default_model
  260. elif model in cls.model_aliases:
  261. model = cls.model_aliases[model]
  262. elif model not in cls.get_models() and cls.models:
  263. raise ModelNotSupportedError(f"Model is not supported: {model} in: {cls.__name__}")
  264. debug.last_model = model
  265. return model