2023-09-03 11:26:26 +03:00
|
|
|
from __future__ import annotations
|
2023-06-24 04:47:00 +03:00
|
|
|
|
2023-12-07 09:18:05 +03:00
|
|
|
import os
|
2023-09-27 21:07:12 +03:00
|
|
|
|
2023-12-11 02:56:06 +03:00
|
|
|
from .errors import *
|
2024-01-26 14:49:52 +03:00
|
|
|
from .models import Model, ModelUtils
|
2024-01-01 19:48:57 +03:00
|
|
|
from .Provider import AsyncGeneratorProvider, ProviderUtils
|
|
|
|
from .typing import Messages, CreateResult, AsyncResult, Union
|
2024-02-09 16:24:15 +03:00
|
|
|
from .cookies import get_cookies, set_cookies
|
2024-01-01 19:48:57 +03:00
|
|
|
from . import debug, version
|
2024-02-22 02:16:58 +03:00
|
|
|
from .providers.types import BaseRetryProvider, ProviderType
|
|
|
|
from .providers.base_provider import ProviderModelMixin
|
2024-02-27 13:55:40 +03:00
|
|
|
from .providers.retry_provider import IterProvider
|
2023-10-07 11:17:43 +03:00
|
|
|
|
2023-10-08 15:31:46 +03:00
|
|
|
def get_model_and_provider(model : Union[Model, str],
|
2024-01-01 19:48:57 +03:00
|
|
|
provider : Union[ProviderType, str, None],
|
2023-10-13 08:45:29 +03:00
|
|
|
stream : bool,
|
2024-01-01 19:48:57 +03:00
|
|
|
ignored : list[str] = None,
|
2023-12-06 11:35:36 +03:00
|
|
|
ignore_working: bool = False,
|
2024-02-12 13:41:27 +03:00
|
|
|
ignore_stream: bool = False,
|
|
|
|
**kwargs) -> tuple[str, ProviderType]:
|
2024-01-14 09:45:41 +03:00
|
|
|
"""
|
|
|
|
Retrieves the model and provider based on input parameters.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (Union[Model, str]): The model to use, either as an object or a string identifier.
|
|
|
|
provider (Union[ProviderType, str, None]): The provider to use, either as an object, a string identifier, or None.
|
|
|
|
stream (bool): Indicates if the operation should be performed as a stream.
|
|
|
|
ignored (list[str], optional): List of provider names to be ignored.
|
|
|
|
ignore_working (bool, optional): If True, ignores the working status of the provider.
|
|
|
|
ignore_stream (bool, optional): If True, ignores the streaming capability of the provider.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
tuple[str, ProviderType]: A tuple containing the model name and the provider type.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
ProviderNotFoundError: If the provider is not found.
|
|
|
|
ModelNotFoundError: If the model is not found.
|
|
|
|
ProviderNotWorkingError: If the provider is not working.
|
|
|
|
StreamNotSupportedError: If streaming is not supported by the provider.
|
|
|
|
"""
|
2023-12-07 09:18:05 +03:00
|
|
|
if debug.version_check:
|
|
|
|
debug.version_check = False
|
2024-01-13 17:37:36 +03:00
|
|
|
version.utils.check_version()
|
2024-02-24 03:31:17 +03:00
|
|
|
|
2023-12-11 02:56:06 +03:00
|
|
|
if isinstance(provider, str):
|
2024-02-23 21:30:53 +03:00
|
|
|
if " " in provider:
|
|
|
|
provider_list = [ProviderUtils.convert[p] for p in provider.split() if p in ProviderUtils.convert]
|
|
|
|
if not provider_list:
|
|
|
|
raise ProviderNotFoundError(f'Providers not found: {provider}')
|
2024-02-27 13:55:40 +03:00
|
|
|
provider = IterProvider(provider_list)
|
2024-02-23 21:30:53 +03:00
|
|
|
elif provider in ProviderUtils.convert:
|
2023-12-11 02:56:06 +03:00
|
|
|
provider = ProviderUtils.convert[provider]
|
|
|
|
else:
|
|
|
|
raise ProviderNotFoundError(f'Provider not found: {provider}')
|
|
|
|
|
2024-01-23 14:17:16 +03:00
|
|
|
if isinstance(model, str):
|
|
|
|
if model in ModelUtils.convert:
|
|
|
|
model = ModelUtils.convert[model]
|
|
|
|
|
2023-09-20 15:52:50 +03:00
|
|
|
if not provider:
|
2024-01-01 19:48:57 +03:00
|
|
|
if isinstance(model, str):
|
2024-01-23 14:17:16 +03:00
|
|
|
raise ModelNotFoundError(f'Model not found: {model}')
|
2023-09-21 21:10:59 +03:00
|
|
|
provider = model.best_provider
|
2023-09-20 15:52:50 +03:00
|
|
|
|
|
|
|
if not provider:
|
2023-12-11 02:56:06 +03:00
|
|
|
raise ProviderNotFoundError(f'No provider found for model: {model}')
|
|
|
|
|
2024-01-01 19:48:57 +03:00
|
|
|
if isinstance(model, Model):
|
|
|
|
model = model.name
|
|
|
|
|
|
|
|
if not ignore_working and not provider.working:
|
2023-12-11 02:56:06 +03:00
|
|
|
raise ProviderNotWorkingError(f'{provider.__name__} is not working')
|
2024-03-14 17:22:09 +03:00
|
|
|
|
|
|
|
if not ignore_working and isinstance(provider, BaseRetryProvider):
|
|
|
|
provider.providers = [p for p in provider.providers if p.working]
|
|
|
|
|
|
|
|
if ignored and isinstance(provider, BaseRetryProvider):
|
|
|
|
provider.providers = [p for p in provider.providers if p.__name__ not in ignored]
|
2023-12-11 02:56:06 +03:00
|
|
|
|
2023-12-06 11:35:36 +03:00
|
|
|
if not ignore_stream and not provider.supports_stream and stream:
|
2023-12-11 02:56:06 +03:00
|
|
|
raise StreamNotSupportedError(f'{provider.__name__} does not support "stream" argument')
|
|
|
|
|
2023-10-23 00:53:18 +03:00
|
|
|
if debug.logging:
|
2024-01-01 19:48:57 +03:00
|
|
|
if model:
|
|
|
|
print(f'Using {provider.__name__} provider and {model} model')
|
|
|
|
else:
|
|
|
|
print(f'Using {provider.__name__} provider')
|
|
|
|
|
|
|
|
debug.last_provider = provider
|
2024-01-26 14:49:52 +03:00
|
|
|
debug.last_model = model
|
2023-09-20 15:52:50 +03:00
|
|
|
|
|
|
|
return model, provider
|
|
|
|
|
2023-06-24 04:47:00 +03:00
|
|
|
class ChatCompletion:
|
|
|
|
@staticmethod
|
2023-10-19 17:14:48 +03:00
|
|
|
def create(model : Union[Model, str],
|
2023-10-12 16:51:11 +03:00
|
|
|
messages : Messages,
|
2024-01-01 19:48:57 +03:00
|
|
|
provider : Union[ProviderType, str, None] = None,
|
2023-10-12 16:51:11 +03:00
|
|
|
stream : bool = False,
|
2023-10-13 08:45:29 +03:00
|
|
|
auth : Union[str, None] = None,
|
2024-01-01 19:48:57 +03:00
|
|
|
ignored : list[str] = None,
|
2023-12-06 11:35:36 +03:00
|
|
|
ignore_working: bool = False,
|
2024-02-09 00:02:52 +03:00
|
|
|
ignore_stream: bool = False,
|
2024-01-10 12:34:56 +03:00
|
|
|
patch_provider: callable = None,
|
2023-12-06 11:35:36 +03:00
|
|
|
**kwargs) -> Union[CreateResult, str]:
|
2024-01-14 09:45:41 +03:00
|
|
|
"""
|
|
|
|
Creates a chat completion using the specified model, provider, and messages.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (Union[Model, str]): The model to use, either as an object or a string identifier.
|
|
|
|
messages (Messages): The messages for which the completion is to be created.
|
|
|
|
provider (Union[ProviderType, str, None], optional): The provider to use, either as an object, a string identifier, or None.
|
|
|
|
stream (bool, optional): Indicates if the operation should be performed as a stream.
|
|
|
|
auth (Union[str, None], optional): Authentication token or credentials, if required.
|
|
|
|
ignored (list[str], optional): List of provider names to be ignored.
|
|
|
|
ignore_working (bool, optional): If True, ignores the working status of the provider.
|
2024-02-09 00:02:52 +03:00
|
|
|
ignore_stream (bool, optional): If True, ignores the stream and authentication requirement checks.
|
2024-01-14 09:45:41 +03:00
|
|
|
patch_provider (callable, optional): Function to modify the provider.
|
|
|
|
**kwargs: Additional keyword arguments.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Union[CreateResult, str]: The result of the chat completion operation.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
AuthenticationRequiredError: If authentication is required but not provided.
|
|
|
|
ProviderNotFoundError, ModelNotFoundError: If the specified provider or model is not found.
|
|
|
|
ProviderNotWorkingError: If the provider is not operational.
|
|
|
|
StreamNotSupportedError: If streaming is requested but not supported by the provider.
|
|
|
|
"""
|
2024-02-09 00:02:52 +03:00
|
|
|
model, provider = get_model_and_provider(
|
|
|
|
model, provider, stream,
|
|
|
|
ignored, ignore_working,
|
|
|
|
ignore_stream or kwargs.get("ignore_stream_and_auth")
|
|
|
|
)
|
2023-10-07 11:17:43 +03:00
|
|
|
|
2023-12-06 11:35:36 +03:00
|
|
|
if auth:
|
2023-08-27 18:37:44 +03:00
|
|
|
kwargs['auth'] = auth
|
2023-12-11 02:56:06 +03:00
|
|
|
|
|
|
|
if "proxy" not in kwargs:
|
|
|
|
proxy = os.environ.get("G4F_PROXY")
|
|
|
|
if proxy:
|
|
|
|
kwargs['proxy'] = proxy
|
2023-07-28 13:07:17 +03:00
|
|
|
|
2024-01-10 12:34:56 +03:00
|
|
|
if patch_provider:
|
|
|
|
provider = patch_provider(provider)
|
|
|
|
|
2024-01-01 19:48:57 +03:00
|
|
|
result = provider.create_completion(model, messages, stream, **kwargs)
|
2024-02-09 06:24:21 +03:00
|
|
|
return result if stream else ''.join([str(chunk) for chunk in result])
|
2023-09-20 15:52:50 +03:00
|
|
|
|
|
|
|
@staticmethod
|
2024-01-01 19:48:57 +03:00
|
|
|
def create_async(model : Union[Model, str],
|
|
|
|
messages : Messages,
|
|
|
|
provider : Union[ProviderType, str, None] = None,
|
|
|
|
stream : bool = False,
|
|
|
|
ignored : list[str] = None,
|
2024-01-10 12:34:56 +03:00
|
|
|
patch_provider: callable = None,
|
2024-01-01 19:48:57 +03:00
|
|
|
**kwargs) -> Union[AsyncResult, str]:
|
2024-01-14 09:45:41 +03:00
|
|
|
"""
|
|
|
|
Asynchronously creates a completion using the specified model and provider.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (Union[Model, str]): The model to use, either as an object or a string identifier.
|
|
|
|
messages (Messages): Messages to be processed.
|
|
|
|
provider (Union[ProviderType, str, None]): The provider to use, either as an object, a string identifier, or None.
|
|
|
|
stream (bool): Indicates if the operation should be performed as a stream.
|
|
|
|
ignored (list[str], optional): List of provider names to be ignored.
|
|
|
|
patch_provider (callable, optional): Function to modify the provider.
|
|
|
|
**kwargs: Additional keyword arguments.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Union[AsyncResult, str]: The result of the asynchronous chat completion operation.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
StreamNotSupportedError: If streaming is requested but not supported by the provider.
|
|
|
|
"""
|
2023-10-13 08:45:29 +03:00
|
|
|
model, provider = get_model_and_provider(model, provider, False, ignored)
|
2023-09-20 15:52:50 +03:00
|
|
|
|
2023-11-20 16:02:51 +03:00
|
|
|
if stream:
|
|
|
|
if isinstance(provider, type) and issubclass(provider, AsyncGeneratorProvider):
|
2024-01-01 19:48:57 +03:00
|
|
|
return provider.create_async_generator(model, messages, **kwargs)
|
2023-12-11 02:56:06 +03:00
|
|
|
raise StreamNotSupportedError(f'{provider.__name__} does not support "stream" argument in "create_async"')
|
2023-11-20 16:02:51 +03:00
|
|
|
|
2024-01-10 12:34:56 +03:00
|
|
|
if patch_provider:
|
|
|
|
provider = patch_provider(provider)
|
|
|
|
|
2024-01-01 19:48:57 +03:00
|
|
|
return provider.create_async(model, messages, **kwargs)
|
2023-09-23 13:16:19 +03:00
|
|
|
|
|
|
|
class Completion:
|
|
|
|
@staticmethod
|
2023-10-19 17:14:48 +03:00
|
|
|
def create(model : Union[Model, str],
|
|
|
|
prompt : str,
|
2024-01-01 19:48:57 +03:00
|
|
|
provider : Union[ProviderType, None] = None,
|
2023-10-19 17:14:48 +03:00
|
|
|
stream : bool = False,
|
2024-01-01 19:48:57 +03:00
|
|
|
ignored : list[str] = None, **kwargs) -> Union[CreateResult, str]:
|
2024-01-14 09:45:41 +03:00
|
|
|
"""
|
|
|
|
Creates a completion based on the provided model, prompt, and provider.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (Union[Model, str]): The model to use, either as an object or a string identifier.
|
|
|
|
prompt (str): The prompt text for which the completion is to be created.
|
|
|
|
provider (Union[ProviderType, None], optional): The provider to use, either as an object or None.
|
|
|
|
stream (bool, optional): Indicates if the operation should be performed as a stream.
|
|
|
|
ignored (list[str], optional): List of provider names to be ignored.
|
|
|
|
**kwargs: Additional keyword arguments.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Union[CreateResult, str]: The result of the completion operation.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
ModelNotAllowedError: If the specified model is not allowed for use with this method.
|
|
|
|
"""
|
2023-09-23 13:16:19 +03:00
|
|
|
allowed_models = [
|
|
|
|
'code-davinci-002',
|
|
|
|
'text-ada-001',
|
|
|
|
'text-babbage-001',
|
|
|
|
'text-curie-001',
|
|
|
|
'text-davinci-002',
|
|
|
|
'text-davinci-003'
|
|
|
|
]
|
|
|
|
if model not in allowed_models:
|
2024-01-01 19:48:57 +03:00
|
|
|
raise ModelNotAllowedError(f'Can\'t use {model} with Completion.create()')
|
2023-10-07 11:17:43 +03:00
|
|
|
|
2023-10-13 08:45:29 +03:00
|
|
|
model, provider = get_model_and_provider(model, provider, stream, ignored)
|
2023-09-23 13:16:19 +03:00
|
|
|
|
2024-01-01 19:48:57 +03:00
|
|
|
result = provider.create_completion(model, [{"role": "user", "content": prompt}], stream, **kwargs)
|
2023-09-23 13:16:19 +03:00
|
|
|
|
2024-01-01 19:48:57 +03:00
|
|
|
return result if stream else ''.join(result)
|
|
|
|
|
2024-01-02 01:20:48 +03:00
|
|
|
def get_last_provider(as_dict: bool = False) -> Union[ProviderType, dict[str, str]]:
|
2024-01-14 09:45:41 +03:00
|
|
|
"""
|
|
|
|
Retrieves the last used provider.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
as_dict (bool, optional): If True, returns the provider information as a dictionary.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Union[ProviderType, dict[str, str]]: The last used provider, either as an object or a dictionary.
|
|
|
|
"""
|
2024-01-01 19:48:57 +03:00
|
|
|
last = debug.last_provider
|
|
|
|
if isinstance(last, BaseRetryProvider):
|
|
|
|
last = last.last_provider
|
|
|
|
if last and as_dict:
|
2024-01-26 14:49:52 +03:00
|
|
|
return {
|
|
|
|
"name": last.__name__,
|
|
|
|
"url": last.url,
|
|
|
|
"model": debug.last_model,
|
|
|
|
"models": last.models if isinstance(last, ProviderModelMixin) else []
|
|
|
|
}
|
2024-01-01 19:48:57 +03:00
|
|
|
return last
|