__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. from __future__ import annotations
  2. import os
  3. from .errors import *
  4. from .models import Model, ModelUtils
  5. from .Provider import AsyncGeneratorProvider, ProviderUtils
  6. from .typing import Messages, CreateResult, AsyncResult, Union
  7. from .cookies import get_cookies, set_cookies
  8. from . import debug, version
  9. from .base_provider import BaseRetryProvider, ProviderType
  10. from .Provider.base_provider import ProviderModelMixin
  11. def get_model_and_provider(model : Union[Model, str],
  12. provider : Union[ProviderType, str, None],
  13. stream : bool,
  14. ignored : list[str] = None,
  15. ignore_working: bool = False,
  16. ignore_stream: bool = False,
  17. **kwargs) -> tuple[str, ProviderType]:
  18. """
  19. Retrieves the model and provider based on input parameters.
  20. Args:
  21. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  22. provider (Union[ProviderType, str, None]): The provider to use, either as an object, a string identifier, or None.
  23. stream (bool): Indicates if the operation should be performed as a stream.
  24. ignored (list[str], optional): List of provider names to be ignored.
  25. ignore_working (bool, optional): If True, ignores the working status of the provider.
  26. ignore_stream (bool, optional): If True, ignores the streaming capability of the provider.
  27. Returns:
  28. tuple[str, ProviderType]: A tuple containing the model name and the provider type.
  29. Raises:
  30. ProviderNotFoundError: If the provider is not found.
  31. ModelNotFoundError: If the model is not found.
  32. ProviderNotWorkingError: If the provider is not working.
  33. StreamNotSupportedError: If streaming is not supported by the provider.
  34. """
  35. if debug.version_check:
  36. debug.version_check = False
  37. version.utils.check_version()
  38. if isinstance(provider, str):
  39. if provider in ProviderUtils.convert:
  40. provider = ProviderUtils.convert[provider]
  41. else:
  42. raise ProviderNotFoundError(f'Provider not found: {provider}')
  43. if isinstance(model, str):
  44. if model in ModelUtils.convert:
  45. model = ModelUtils.convert[model]
  46. if not provider:
  47. if isinstance(model, str):
  48. raise ModelNotFoundError(f'Model not found: {model}')
  49. provider = model.best_provider
  50. if not provider:
  51. raise ProviderNotFoundError(f'No provider found for model: {model}')
  52. if isinstance(model, Model):
  53. model = model.name
  54. if ignored and isinstance(provider, BaseRetryProvider):
  55. provider.providers = [p for p in provider.providers if p.__name__ not in ignored]
  56. if not ignore_working and not provider.working:
  57. raise ProviderNotWorkingError(f'{provider.__name__} is not working')
  58. if not ignore_stream and not provider.supports_stream and stream:
  59. raise StreamNotSupportedError(f'{provider.__name__} does not support "stream" argument')
  60. if debug.logging:
  61. if model:
  62. print(f'Using {provider.__name__} provider and {model} model')
  63. else:
  64. print(f'Using {provider.__name__} provider')
  65. debug.last_provider = provider
  66. debug.last_model = model
  67. return model, provider
  68. class ChatCompletion:
  69. @staticmethod
  70. def create(model : Union[Model, str],
  71. messages : Messages,
  72. provider : Union[ProviderType, str, None] = None,
  73. stream : bool = False,
  74. auth : Union[str, None] = None,
  75. ignored : list[str] = None,
  76. ignore_working: bool = False,
  77. ignore_stream: bool = False,
  78. patch_provider: callable = None,
  79. **kwargs) -> Union[CreateResult, str]:
  80. """
  81. Creates a chat completion using the specified model, provider, and messages.
  82. Args:
  83. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  84. messages (Messages): The messages for which the completion is to be created.
  85. provider (Union[ProviderType, str, None], optional): The provider to use, either as an object, a string identifier, or None.
  86. stream (bool, optional): Indicates if the operation should be performed as a stream.
  87. auth (Union[str, None], optional): Authentication token or credentials, if required.
  88. ignored (list[str], optional): List of provider names to be ignored.
  89. ignore_working (bool, optional): If True, ignores the working status of the provider.
  90. ignore_stream (bool, optional): If True, ignores the stream and authentication requirement checks.
  91. patch_provider (callable, optional): Function to modify the provider.
  92. **kwargs: Additional keyword arguments.
  93. Returns:
  94. Union[CreateResult, str]: The result of the chat completion operation.
  95. Raises:
  96. AuthenticationRequiredError: If authentication is required but not provided.
  97. ProviderNotFoundError, ModelNotFoundError: If the specified provider or model is not found.
  98. ProviderNotWorkingError: If the provider is not operational.
  99. StreamNotSupportedError: If streaming is requested but not supported by the provider.
  100. """
  101. model, provider = get_model_and_provider(
  102. model, provider, stream,
  103. ignored, ignore_working,
  104. ignore_stream or kwargs.get("ignore_stream_and_auth")
  105. )
  106. if auth:
  107. kwargs['auth'] = auth
  108. if "proxy" not in kwargs:
  109. proxy = os.environ.get("G4F_PROXY")
  110. if proxy:
  111. kwargs['proxy'] = proxy
  112. if patch_provider:
  113. provider = patch_provider(provider)
  114. result = provider.create_completion(model, messages, stream, **kwargs)
  115. return result if stream else ''.join([str(chunk) for chunk in result])
  116. @staticmethod
  117. def create_async(model : Union[Model, str],
  118. messages : Messages,
  119. provider : Union[ProviderType, str, None] = None,
  120. stream : bool = False,
  121. ignored : list[str] = None,
  122. patch_provider: callable = None,
  123. **kwargs) -> Union[AsyncResult, str]:
  124. """
  125. Asynchronously creates a completion using the specified model and provider.
  126. Args:
  127. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  128. messages (Messages): Messages to be processed.
  129. provider (Union[ProviderType, str, None]): The provider to use, either as an object, a string identifier, or None.
  130. stream (bool): Indicates if the operation should be performed as a stream.
  131. ignored (list[str], optional): List of provider names to be ignored.
  132. patch_provider (callable, optional): Function to modify the provider.
  133. **kwargs: Additional keyword arguments.
  134. Returns:
  135. Union[AsyncResult, str]: The result of the asynchronous chat completion operation.
  136. Raises:
  137. StreamNotSupportedError: If streaming is requested but not supported by the provider.
  138. """
  139. model, provider = get_model_and_provider(model, provider, False, ignored)
  140. if stream:
  141. if isinstance(provider, type) and issubclass(provider, AsyncGeneratorProvider):
  142. return provider.create_async_generator(model, messages, **kwargs)
  143. raise StreamNotSupportedError(f'{provider.__name__} does not support "stream" argument in "create_async"')
  144. if patch_provider:
  145. provider = patch_provider(provider)
  146. return provider.create_async(model, messages, **kwargs)
  147. class Completion:
  148. @staticmethod
  149. def create(model : Union[Model, str],
  150. prompt : str,
  151. provider : Union[ProviderType, None] = None,
  152. stream : bool = False,
  153. ignored : list[str] = None, **kwargs) -> Union[CreateResult, str]:
  154. """
  155. Creates a completion based on the provided model, prompt, and provider.
  156. Args:
  157. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  158. prompt (str): The prompt text for which the completion is to be created.
  159. provider (Union[ProviderType, None], optional): The provider to use, either as an object or None.
  160. stream (bool, optional): Indicates if the operation should be performed as a stream.
  161. ignored (list[str], optional): List of provider names to be ignored.
  162. **kwargs: Additional keyword arguments.
  163. Returns:
  164. Union[CreateResult, str]: The result of the completion operation.
  165. Raises:
  166. ModelNotAllowedError: If the specified model is not allowed for use with this method.
  167. """
  168. allowed_models = [
  169. 'code-davinci-002',
  170. 'text-ada-001',
  171. 'text-babbage-001',
  172. 'text-curie-001',
  173. 'text-davinci-002',
  174. 'text-davinci-003'
  175. ]
  176. if model not in allowed_models:
  177. raise ModelNotAllowedError(f'Can\'t use {model} with Completion.create()')
  178. model, provider = get_model_and_provider(model, provider, stream, ignored)
  179. result = provider.create_completion(model, [{"role": "user", "content": prompt}], stream, **kwargs)
  180. return result if stream else ''.join(result)
  181. def get_last_provider(as_dict: bool = False) -> Union[ProviderType, dict[str, str]]:
  182. """
  183. Retrieves the last used provider.
  184. Args:
  185. as_dict (bool, optional): If True, returns the provider information as a dictionary.
  186. Returns:
  187. Union[ProviderType, dict[str, str]]: The last used provider, either as an object or a dictionary.
  188. """
  189. last = debug.last_provider
  190. if isinstance(last, BaseRetryProvider):
  191. last = last.last_provider
  192. if last and as_dict:
  193. return {
  194. "name": last.__name__,
  195. "url": last.url,
  196. "model": debug.last_model,
  197. "models": last.models if isinstance(last, ProviderModelMixin) else []
  198. }
  199. return last