__init__.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. if debug.version_check:
  16. debug.version_check = False
  17. version.utils.check_pypi_version()
  18. if isinstance(provider, str):
  19. if provider in ProviderUtils.convert:
  20. provider = ProviderUtils.convert[provider]
  21. else:
  22. raise ProviderNotFoundError(f'Provider not found: {provider}')
  23. if not provider:
  24. if isinstance(model, str):
  25. if model in ModelUtils.convert:
  26. model = ModelUtils.convert[model]
  27. else:
  28. raise ModelNotFoundError(f'Model not found: {model}')
  29. provider = model.best_provider
  30. if not provider:
  31. raise ProviderNotFoundError(f'No provider found for model: {model}')
  32. if isinstance(model, Model):
  33. model = model.name
  34. if ignored and isinstance(provider, BaseRetryProvider):
  35. provider.providers = [p for p in provider.providers if p.__name__ not in ignored]
  36. if not ignore_working and not provider.working:
  37. raise ProviderNotWorkingError(f'{provider.__name__} is not working')
  38. if not ignore_stream and not provider.supports_stream and stream:
  39. raise StreamNotSupportedError(f'{provider.__name__} does not support "stream" argument')
  40. if debug.logging:
  41. if model:
  42. print(f'Using {provider.__name__} provider and {model} model')
  43. else:
  44. print(f'Using {provider.__name__} provider')
  45. debug.last_provider = provider
  46. return model, provider
  47. class ChatCompletion:
  48. @staticmethod
  49. def create(model : Union[Model, str],
  50. messages : Messages,
  51. provider : Union[ProviderType, str, None] = None,
  52. stream : bool = False,
  53. auth : Union[str, None] = None,
  54. ignored : list[str] = None,
  55. ignore_working: bool = False,
  56. ignore_stream_and_auth: bool = False,
  57. patch_provider: callable = None,
  58. **kwargs) -> Union[CreateResult, str]:
  59. model, provider = get_model_and_provider(model, provider, stream, ignored, ignore_working, ignore_stream_and_auth)
  60. if not ignore_stream_and_auth and provider.needs_auth and not auth:
  61. raise AuthenticationRequiredError(f'{provider.__name__} requires authentication (use auth=\'cookie or token or jwt ...\' param)')
  62. if auth:
  63. kwargs['auth'] = auth
  64. if "proxy" not in kwargs:
  65. proxy = os.environ.get("G4F_PROXY")
  66. if proxy:
  67. kwargs['proxy'] = proxy
  68. if patch_provider:
  69. provider = patch_provider(provider)
  70. result = provider.create_completion(model, messages, stream, **kwargs)
  71. return result if stream else ''.join(result)
  72. @staticmethod
  73. def create_async(model : Union[Model, str],
  74. messages : Messages,
  75. provider : Union[ProviderType, str, None] = None,
  76. stream : bool = False,
  77. ignored : list[str] = None,
  78. patch_provider: callable = None,
  79. **kwargs) -> Union[AsyncResult, str]:
  80. model, provider = get_model_and_provider(model, provider, False, ignored)
  81. if stream:
  82. if isinstance(provider, type) and issubclass(provider, AsyncGeneratorProvider):
  83. return provider.create_async_generator(model, messages, **kwargs)
  84. raise StreamNotSupportedError(f'{provider.__name__} does not support "stream" argument in "create_async"')
  85. if patch_provider:
  86. provider = patch_provider(provider)
  87. return provider.create_async(model, messages, **kwargs)
  88. class Completion:
  89. @staticmethod
  90. def create(model : Union[Model, str],
  91. prompt : str,
  92. provider : Union[ProviderType, None] = None,
  93. stream : bool = False,
  94. ignored : list[str] = None, **kwargs) -> Union[CreateResult, str]:
  95. allowed_models = [
  96. 'code-davinci-002',
  97. 'text-ada-001',
  98. 'text-babbage-001',
  99. 'text-curie-001',
  100. 'text-davinci-002',
  101. 'text-davinci-003'
  102. ]
  103. if model not in allowed_models:
  104. raise ModelNotAllowedError(f'Can\'t use {model} with Completion.create()')
  105. model, provider = get_model_and_provider(model, provider, stream, ignored)
  106. result = provider.create_completion(model, [{"role": "user", "content": prompt}], stream, **kwargs)
  107. return result if stream else ''.join(result)
  108. def get_last_provider(as_dict: bool = False) -> Union[ProviderType, dict[str, str]]:
  109. last = debug.last_provider
  110. if isinstance(last, BaseRetryProvider):
  111. last = last.last_provider
  112. if last and as_dict:
  113. return {"name": last.__name__, "url": last.url}
  114. return last