__init__.py 10 KB

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