__init__.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. from __future__ import annotations
  2. import os
  3. from . import debug, version
  4. from .models import Model
  5. from .typing import Messages, CreateResult, AsyncResult, Union
  6. from .errors import StreamNotSupportedError, ModelNotAllowedError
  7. from .cookies import get_cookies, set_cookies
  8. from .providers.types import ProviderType
  9. from .providers.base_provider import AsyncGeneratorProvider
  10. from .client.service import get_model_and_provider, get_last_provider
  11. class ChatCompletion:
  12. @staticmethod
  13. def create(model : Union[Model, str],
  14. messages : Messages,
  15. provider : Union[ProviderType, str, None] = None,
  16. stream : bool = False,
  17. auth : Union[str, None] = None,
  18. ignored : list[str] = None,
  19. ignore_working: bool = False,
  20. ignore_stream: bool = False,
  21. patch_provider: callable = None,
  22. **kwargs) -> Union[CreateResult, str]:
  23. """
  24. Creates a chat completion using the specified model, provider, and messages.
  25. Args:
  26. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  27. messages (Messages): The messages for which the completion is to be created.
  28. provider (Union[ProviderType, str, None], optional): The provider to use, either as an object, a string identifier, or None.
  29. stream (bool, optional): Indicates if the operation should be performed as a stream.
  30. auth (Union[str, None], optional): Authentication token or credentials, if required.
  31. ignored (list[str], optional): List of provider names to be ignored.
  32. ignore_working (bool, optional): If True, ignores the working status of the provider.
  33. ignore_stream (bool, optional): If True, ignores the stream and authentication requirement checks.
  34. patch_provider (callable, optional): Function to modify the provider.
  35. **kwargs: Additional keyword arguments.
  36. Returns:
  37. Union[CreateResult, str]: The result of the chat completion operation.
  38. Raises:
  39. AuthenticationRequiredError: If authentication is required but not provided.
  40. ProviderNotFoundError, ModelNotFoundError: If the specified provider or model is not found.
  41. ProviderNotWorkingError: If the provider is not operational.
  42. StreamNotSupportedError: If streaming is requested but not supported by the provider.
  43. """
  44. model, provider = get_model_and_provider(
  45. model, provider, stream,
  46. ignored, ignore_working,
  47. ignore_stream or kwargs.get("ignore_stream_and_auth")
  48. )
  49. if auth is not None:
  50. kwargs['auth'] = auth
  51. if "proxy" not in kwargs:
  52. proxy = os.environ.get("G4F_PROXY")
  53. if proxy:
  54. kwargs['proxy'] = proxy
  55. if patch_provider:
  56. provider = patch_provider(provider)
  57. result = provider.create_completion(model, messages, stream, **kwargs)
  58. return result if stream else ''.join([str(chunk) for chunk in result])
  59. @staticmethod
  60. def create_async(model : Union[Model, str],
  61. messages : Messages,
  62. provider : Union[ProviderType, str, None] = None,
  63. stream : bool = False,
  64. ignored : list[str] = None,
  65. ignore_working: bool = False,
  66. patch_provider: callable = None,
  67. **kwargs) -> Union[AsyncResult, str]:
  68. """
  69. Asynchronously creates a completion using the specified model and provider.
  70. Args:
  71. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  72. messages (Messages): Messages to be processed.
  73. provider (Union[ProviderType, str, None]): The provider to use, either as an object, a string identifier, or None.
  74. stream (bool): Indicates if the operation should be performed as a stream.
  75. ignored (list[str], optional): List of provider names to be ignored.
  76. patch_provider (callable, optional): Function to modify the provider.
  77. **kwargs: Additional keyword arguments.
  78. Returns:
  79. Union[AsyncResult, str]: The result of the asynchronous chat completion operation.
  80. Raises:
  81. StreamNotSupportedError: If streaming is requested but not supported by the provider.
  82. """
  83. model, provider = get_model_and_provider(model, provider, False, ignored, ignore_working)
  84. if stream:
  85. if isinstance(provider, type) and issubclass(provider, AsyncGeneratorProvider):
  86. return provider.create_async_generator(model, messages, **kwargs)
  87. raise StreamNotSupportedError(f'{provider.__name__} does not support "stream" argument in "create_async"')
  88. if patch_provider:
  89. provider = patch_provider(provider)
  90. return provider.create_async(model, messages, **kwargs)
  91. class Completion:
  92. @staticmethod
  93. def create(model : Union[Model, str],
  94. prompt : str,
  95. provider : Union[ProviderType, None] = None,
  96. stream : bool = False,
  97. ignored : list[str] = None, **kwargs) -> Union[CreateResult, str]:
  98. """
  99. Creates a completion based on the provided model, prompt, and provider.
  100. Args:
  101. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  102. prompt (str): The prompt text for which the completion is to be created.
  103. provider (Union[ProviderType, None], optional): The provider to use, either as an object or None.
  104. stream (bool, optional): Indicates if the operation should be performed as a stream.
  105. ignored (list[str], optional): List of provider names to be ignored.
  106. **kwargs: Additional keyword arguments.
  107. Returns:
  108. Union[CreateResult, str]: The result of the completion operation.
  109. Raises:
  110. ModelNotAllowedError: If the specified model is not allowed for use with this method.
  111. """
  112. allowed_models = [
  113. 'code-davinci-002',
  114. 'text-ada-001',
  115. 'text-babbage-001',
  116. 'text-curie-001',
  117. 'text-davinci-002',
  118. 'text-davinci-003'
  119. ]
  120. if model not in allowed_models:
  121. raise ModelNotAllowedError(f'Can\'t use {model} with Completion.create()')
  122. model, provider = get_model_and_provider(model, provider, stream, ignored)
  123. result = provider.create_completion(model, [{"role": "user", "content": prompt}], stream, **kwargs)
  124. return result if stream else ''.join(result)