base_provider.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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 .helper import get_event_loop, get_cookies, format_prompt
  9. from ..typing import CreateResult, AsyncResult, Messages
  10. from ..base_provider import BaseProvider
  11. if sys.version_info < (3, 10):
  12. NoneType = type(None)
  13. else:
  14. from types import NoneType
  15. # Set Windows event loop policy for better compatibility with asyncio and curl_cffi
  16. if sys.platform == 'win32':
  17. if isinstance(asyncio.get_event_loop_policy(), asyncio.WindowsProactorEventLoopPolicy):
  18. asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  19. class AbstractProvider(BaseProvider):
  20. """
  21. Abstract class for providing asynchronous functionality to derived classes.
  22. """
  23. @classmethod
  24. async def create_async(
  25. cls,
  26. model: str,
  27. messages: Messages,
  28. *,
  29. loop: AbstractEventLoop = None,
  30. executor: ThreadPoolExecutor = None,
  31. **kwargs
  32. ) -> str:
  33. """
  34. Asynchronously creates a result based on the given model and messages.
  35. Args:
  36. cls (type): The class on which this method is called.
  37. model (str): The model to use for creation.
  38. messages (Messages): The messages to process.
  39. loop (AbstractEventLoop, optional): The event loop to use. Defaults to None.
  40. executor (ThreadPoolExecutor, optional): The executor for running async tasks. Defaults to None.
  41. **kwargs: Additional keyword arguments.
  42. Returns:
  43. str: The created result as a string.
  44. """
  45. loop = loop or get_event_loop()
  46. def create_func() -> str:
  47. return "".join(cls.create_completion(model, messages, False, **kwargs))
  48. return await asyncio.wait_for(
  49. loop.run_in_executor(executor, create_func),
  50. timeout=kwargs.get("timeout", 0)
  51. )
  52. @classmethod
  53. @property
  54. def params(cls) -> str:
  55. """
  56. Returns the parameters supported by the provider.
  57. Args:
  58. cls (type): The class on which this property is called.
  59. Returns:
  60. str: A string listing the supported parameters.
  61. """
  62. sig = signature(
  63. cls.create_async_generator if issubclass(cls, AsyncGeneratorProvider) else
  64. cls.create_async if issubclass(cls, AsyncProvider) else
  65. cls.create_completion
  66. )
  67. def get_type_name(annotation: type) -> str:
  68. return annotation.__name__ if hasattr(annotation, "__name__") else str(annotation)
  69. args = ""
  70. for name, param in sig.parameters.items():
  71. if name in ("self", "kwargs") or (name == "stream" and not cls.supports_stream):
  72. continue
  73. args += f"\n {name}"
  74. args += f": {get_type_name(param.annotation)}" if param.annotation is not Parameter.empty else ""
  75. args += f' = "{param.default}"' if param.default == "" else f" = {param.default}" if param.default is not Parameter.empty else ""
  76. return f"g4f.Provider.{cls.__name__} supports: ({args}\n)"
  77. class AsyncProvider(AbstractProvider):
  78. """
  79. Provides asynchronous functionality for creating completions.
  80. """
  81. @classmethod
  82. def create_completion(
  83. cls,
  84. model: str,
  85. messages: Messages,
  86. stream: bool = False,
  87. *,
  88. loop: AbstractEventLoop = None,
  89. **kwargs
  90. ) -> CreateResult:
  91. """
  92. Creates a completion result synchronously.
  93. Args:
  94. cls (type): The class on which this method is called.
  95. model (str): The model to use for creation.
  96. messages (Messages): The messages to process.
  97. stream (bool): Indicates whether to stream the results. Defaults to False.
  98. loop (AbstractEventLoop, optional): The event loop to use. Defaults to None.
  99. **kwargs: Additional keyword arguments.
  100. Returns:
  101. CreateResult: The result of the completion creation.
  102. """
  103. loop = loop or get_event_loop()
  104. coro = cls.create_async(model, messages, **kwargs)
  105. yield loop.run_until_complete(coro)
  106. @staticmethod
  107. @abstractmethod
  108. async def create_async(
  109. model: str,
  110. messages: Messages,
  111. **kwargs
  112. ) -> str:
  113. """
  114. Abstract method for creating asynchronous results.
  115. Args:
  116. model (str): The model to use for creation.
  117. messages (Messages): The messages to process.
  118. **kwargs: Additional keyword arguments.
  119. Raises:
  120. NotImplementedError: If this method is not overridden in derived classes.
  121. Returns:
  122. str: The created result as a string.
  123. """
  124. raise NotImplementedError()
  125. class AsyncGeneratorProvider(AsyncProvider):
  126. """
  127. Provides asynchronous generator functionality for streaming results.
  128. """
  129. supports_stream = True
  130. @classmethod
  131. def create_completion(
  132. cls,
  133. model: str,
  134. messages: Messages,
  135. stream: bool = True,
  136. *,
  137. loop: AbstractEventLoop = None,
  138. **kwargs
  139. ) -> CreateResult:
  140. """
  141. Creates a streaming completion result synchronously.
  142. Args:
  143. cls (type): The class on which this method is called.
  144. model (str): The model to use for creation.
  145. messages (Messages): The messages to process.
  146. stream (bool): Indicates whether to stream the results. Defaults to True.
  147. loop (AbstractEventLoop, optional): The event loop to use. Defaults to None.
  148. **kwargs: Additional keyword arguments.
  149. Returns:
  150. CreateResult: The result of the streaming completion creation.
  151. """
  152. loop = loop or get_event_loop()
  153. generator = cls.create_async_generator(model, messages, stream=stream, **kwargs)
  154. gen = generator.__aiter__()
  155. while True:
  156. try:
  157. yield loop.run_until_complete(gen.__anext__())
  158. except StopAsyncIteration:
  159. break
  160. @classmethod
  161. async def create_async(
  162. cls,
  163. model: str,
  164. messages: Messages,
  165. **kwargs
  166. ) -> str:
  167. """
  168. Asynchronously creates a result from a generator.
  169. Args:
  170. cls (type): The class on which this method is called.
  171. model (str): The model to use for creation.
  172. messages (Messages): The messages to process.
  173. **kwargs: Additional keyword arguments.
  174. Returns:
  175. str: The created result as a string.
  176. """
  177. return "".join([
  178. chunk async for chunk in cls.create_async_generator(model, messages, stream=False, **kwargs)
  179. if not isinstance(chunk, Exception)
  180. ])
  181. @staticmethod
  182. @abstractmethod
  183. async def create_async_generator(
  184. model: str,
  185. messages: Messages,
  186. stream: bool = True,
  187. **kwargs
  188. ) -> AsyncResult:
  189. """
  190. Abstract method for creating an asynchronous generator.
  191. Args:
  192. model (str): The model to use for creation.
  193. messages (Messages): The messages to process.
  194. stream (bool): Indicates whether to stream the results. Defaults to True.
  195. **kwargs: Additional keyword arguments.
  196. Raises:
  197. NotImplementedError: If this method is not overridden in derived classes.
  198. Returns:
  199. AsyncResult: An asynchronous generator yielding results.
  200. """
  201. raise NotImplementedError()