base_provider.py 9.7 KB

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