2024-03-19 20:48:32 +03:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-03-16 12:48:37 +03:00
|
|
|
import logging
|
2024-05-20 02:28:08 +03:00
|
|
|
import os
|
|
|
|
import os.path
|
|
|
|
import uuid
|
|
|
|
import asyncio
|
|
|
|
import time
|
2024-09-04 20:56:07 +03:00
|
|
|
import base64
|
2024-05-20 02:28:08 +03:00
|
|
|
from aiohttp import ClientSession
|
|
|
|
from typing import Iterator, Optional
|
|
|
|
from flask import send_from_directory
|
2024-03-16 12:48:37 +03:00
|
|
|
|
|
|
|
from g4f import version, models
|
|
|
|
from g4f import get_last_provider, ChatCompletion
|
|
|
|
from g4f.errors import VersionNotFoundError
|
2024-05-20 02:28:08 +03:00
|
|
|
from g4f.typing import Cookies
|
|
|
|
from g4f.image import ImagePreview, ImageResponse, is_accepted_format
|
|
|
|
from g4f.requests.aiohttp import get_connector
|
2024-03-16 12:48:37 +03:00
|
|
|
from g4f.Provider import ProviderType, __providers__, __map__
|
2024-04-10 09:14:50 +03:00
|
|
|
from g4f.providers.base_provider import ProviderModelMixin, FinishReason
|
2024-03-26 08:42:47 +03:00
|
|
|
from g4f.providers.conversation import BaseConversation
|
2024-03-16 20:07:53 +03:00
|
|
|
|
2024-03-28 13:36:25 +03:00
|
|
|
conversations: dict[dict[str, BaseConversation]] = {}
|
2024-05-20 02:28:08 +03:00
|
|
|
images_dir = "./generated_images"
|
2024-03-16 20:07:53 +03:00
|
|
|
|
|
|
|
class Api():
|
2024-03-16 12:48:37 +03:00
|
|
|
|
2024-04-21 16:15:55 +03:00
|
|
|
@staticmethod
|
|
|
|
def get_models() -> list[str]:
|
2024-03-16 12:48:37 +03:00
|
|
|
"""
|
|
|
|
Return a list of all models.
|
|
|
|
|
|
|
|
Fetches and returns a list of all available models in the system.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
List[str]: A list of model names.
|
|
|
|
"""
|
|
|
|
return models._all_models
|
|
|
|
|
2024-04-21 16:15:55 +03:00
|
|
|
@staticmethod
|
|
|
|
def get_provider_models(provider: str) -> list[dict]:
|
2024-03-16 12:48:37 +03:00
|
|
|
if provider in __map__:
|
|
|
|
provider: ProviderType = __map__[provider]
|
|
|
|
if issubclass(provider, ProviderModelMixin):
|
|
|
|
return [{"model": model, "default": model == provider.default_model} for model in provider.get_models()]
|
|
|
|
elif provider.supports_gpt_35_turbo or provider.supports_gpt_4:
|
|
|
|
return [
|
|
|
|
*([{"model": "gpt-4", "default": not provider.supports_gpt_4}] if provider.supports_gpt_4 else []),
|
|
|
|
*([{"model": "gpt-3.5-turbo", "default": not provider.supports_gpt_4}] if provider.supports_gpt_35_turbo else [])
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return [];
|
|
|
|
|
2024-04-21 16:15:55 +03:00
|
|
|
@staticmethod
|
|
|
|
def get_image_models() -> list[dict]:
|
|
|
|
image_models = []
|
2024-04-22 19:08:04 +03:00
|
|
|
index = []
|
2024-04-22 02:27:48 +03:00
|
|
|
for provider in __providers__:
|
2024-04-21 16:15:55 +03:00
|
|
|
if hasattr(provider, "image_models"):
|
|
|
|
if hasattr(provider, "get_models"):
|
|
|
|
provider.get_models()
|
2024-04-22 02:27:48 +03:00
|
|
|
parent = provider
|
|
|
|
if hasattr(provider, "parent"):
|
|
|
|
parent = __map__[provider.parent]
|
2024-04-22 19:08:04 +03:00
|
|
|
if parent.__name__ not in index:
|
|
|
|
for model in provider.image_models:
|
|
|
|
image_models.append({
|
|
|
|
"provider": parent.__name__,
|
|
|
|
"url": parent.url,
|
|
|
|
"label": parent.label if hasattr(parent, "label") else None,
|
|
|
|
"image_model": model,
|
|
|
|
"vision_model": parent.default_vision_model if hasattr(parent, "default_vision_model") else None
|
|
|
|
})
|
|
|
|
index.append(parent.__name__)
|
|
|
|
elif hasattr(provider, "default_vision_model") and provider.__name__ not in index:
|
|
|
|
image_models.append({
|
|
|
|
"provider": provider.__name__,
|
|
|
|
"url": provider.url,
|
|
|
|
"label": provider.label if hasattr(provider, "label") else None,
|
|
|
|
"image_model": None,
|
|
|
|
"vision_model": provider.default_vision_model
|
|
|
|
})
|
|
|
|
index.append(provider.__name__)
|
2024-04-21 16:15:55 +03:00
|
|
|
return image_models
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_providers() -> list[str]:
|
2024-03-16 12:48:37 +03:00
|
|
|
"""
|
|
|
|
Return a list of all working providers.
|
|
|
|
"""
|
2024-04-12 21:58:40 +03:00
|
|
|
return {
|
|
|
|
provider.__name__: (provider.label
|
|
|
|
if hasattr(provider, "label")
|
|
|
|
else provider.__name__) +
|
|
|
|
(" (WebDriver)"
|
|
|
|
if "webdriver" in provider.get_parameters()
|
2024-04-17 11:33:23 +03:00
|
|
|
else "") +
|
|
|
|
(" (Auth)"
|
|
|
|
if provider.needs_auth
|
2024-04-12 21:58:40 +03:00
|
|
|
else "")
|
|
|
|
for provider in __providers__
|
|
|
|
if provider.working
|
|
|
|
}
|
2024-03-16 12:48:37 +03:00
|
|
|
|
2024-04-21 16:15:55 +03:00
|
|
|
@staticmethod
|
|
|
|
def get_version():
|
2024-03-16 12:48:37 +03:00
|
|
|
"""
|
|
|
|
Returns the current and latest version of the application.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict: A dictionary containing the current and latest version.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
current_version = version.utils.current_version
|
|
|
|
except VersionNotFoundError:
|
|
|
|
current_version = None
|
|
|
|
return {
|
|
|
|
"version": current_version,
|
|
|
|
"latest_version": version.utils.latest_version,
|
|
|
|
}
|
|
|
|
|
2024-05-20 02:28:08 +03:00
|
|
|
def serve_images(self, name):
|
|
|
|
return send_from_directory(os.path.abspath(images_dir), name)
|
2024-03-16 12:48:37 +03:00
|
|
|
|
|
|
|
def _prepare_conversation_kwargs(self, json_data: dict, kwargs: dict):
|
|
|
|
"""
|
|
|
|
Prepares arguments for chat completion based on the request data.
|
|
|
|
|
|
|
|
Reads the request and prepares the necessary arguments for handling
|
|
|
|
a chat completion request.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict: Arguments prepared for chat completion.
|
|
|
|
"""
|
2024-04-08 08:24:00 +03:00
|
|
|
model = json_data.get('model') or models.default
|
|
|
|
provider = json_data.get('provider')
|
2024-03-16 12:48:37 +03:00
|
|
|
messages = json_data['messages']
|
2024-04-08 08:24:00 +03:00
|
|
|
api_key = json_data.get("api_key")
|
|
|
|
if api_key is not None:
|
|
|
|
kwargs["api_key"] = api_key
|
2024-03-16 12:48:37 +03:00
|
|
|
if json_data.get('web_search'):
|
2024-04-20 11:43:53 +03:00
|
|
|
if provider in ("Bing", "HuggingChat"):
|
2024-03-16 12:48:37 +03:00
|
|
|
kwargs['web_search'] = True
|
|
|
|
else:
|
|
|
|
from .internet import get_search_message
|
|
|
|
messages[-1]["content"] = get_search_message(messages[-1]["content"])
|
|
|
|
|
2024-03-16 20:07:53 +03:00
|
|
|
conversation_id = json_data.get("conversation_id")
|
2024-03-28 13:36:25 +03:00
|
|
|
if conversation_id and provider in conversations and conversation_id in conversations[provider]:
|
|
|
|
kwargs["conversation"] = conversations[provider][conversation_id]
|
2024-03-16 20:07:53 +03:00
|
|
|
|
2024-03-16 12:48:37 +03:00
|
|
|
return {
|
|
|
|
"model": model,
|
|
|
|
"provider": provider,
|
|
|
|
"messages": messages,
|
|
|
|
"stream": True,
|
|
|
|
"ignore_stream": True,
|
2024-03-16 20:07:53 +03:00
|
|
|
"return_conversation": True,
|
2024-03-16 12:48:37 +03:00
|
|
|
**kwargs
|
|
|
|
}
|
|
|
|
|
2024-03-28 13:36:25 +03:00
|
|
|
def _create_response_stream(self, kwargs: dict, conversation_id: str, provider: str) -> Iterator:
|
2024-03-16 12:48:37 +03:00
|
|
|
"""
|
|
|
|
Creates and returns a streaming response for the conversation.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
kwargs (dict): Arguments for creating the chat completion.
|
|
|
|
|
|
|
|
Yields:
|
|
|
|
str: JSON formatted response chunks for the stream.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
Exception: If an error occurs during the streaming process.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
first = True
|
|
|
|
for chunk in ChatCompletion.create(**kwargs):
|
|
|
|
if first:
|
|
|
|
first = False
|
2024-03-16 20:07:53 +03:00
|
|
|
yield self._format_json("provider", get_last_provider(True))
|
2024-03-26 08:42:47 +03:00
|
|
|
if isinstance(chunk, BaseConversation):
|
2024-03-28 13:36:25 +03:00
|
|
|
if provider not in conversations:
|
|
|
|
conversations[provider] = {}
|
|
|
|
conversations[provider][conversation_id] = chunk
|
2024-03-16 20:07:53 +03:00
|
|
|
yield self._format_json("conversation", conversation_id)
|
|
|
|
elif isinstance(chunk, Exception):
|
2024-03-16 12:48:37 +03:00
|
|
|
logging.exception(chunk)
|
2024-03-16 20:07:53 +03:00
|
|
|
yield self._format_json("message", get_error_message(chunk))
|
2024-04-21 08:22:59 +03:00
|
|
|
elif isinstance(chunk, ImagePreview):
|
|
|
|
yield self._format_json("preview", chunk.to_string())
|
2024-05-20 02:28:08 +03:00
|
|
|
elif isinstance(chunk, ImageResponse):
|
|
|
|
async def copy_images(images: list[str], cookies: Optional[Cookies] = None):
|
|
|
|
async with ClientSession(
|
|
|
|
connector=get_connector(None, os.environ.get("G4F_PROXY")),
|
|
|
|
cookies=cookies
|
|
|
|
) as session:
|
|
|
|
async def copy_image(image):
|
2024-09-04 20:56:07 +03:00
|
|
|
if image.startswith("data:"):
|
2024-09-04 22:31:00 +03:00
|
|
|
# Processing the data URL
|
2024-09-04 20:56:07 +03:00
|
|
|
data_uri_parts = image.split(",")
|
|
|
|
if len(data_uri_parts) == 2:
|
|
|
|
content_type, base64_data = data_uri_parts
|
|
|
|
extension = content_type.split("/")[-1].split(";")[0]
|
|
|
|
target = os.path.join(images_dir, f"{int(time.time())}_{str(uuid.uuid4())}.{extension}")
|
|
|
|
with open(target, "wb") as f:
|
|
|
|
f.write(base64.b64decode(base64_data))
|
|
|
|
return f"/images/{os.path.basename(target)}"
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
# Обробка звичайної URL-адреси
|
|
|
|
async with session.get(image) as response:
|
|
|
|
target = os.path.join(images_dir, f"{int(time.time())}_{str(uuid.uuid4())}")
|
|
|
|
with open(target, "wb") as f:
|
|
|
|
async for chunk in response.content.iter_any():
|
|
|
|
f.write(chunk)
|
|
|
|
with open(target, "rb") as f:
|
|
|
|
extension = is_accepted_format(f.read(12)).split("/")[-1]
|
|
|
|
extension = "jpg" if extension == "jpeg" else extension
|
|
|
|
new_target = f"{target}.{extension}"
|
|
|
|
os.rename(target, new_target)
|
|
|
|
return f"/images/{os.path.basename(new_target)}"
|
|
|
|
return await asyncio.gather(*[copy_image(image) for image in images])
|
2024-05-20 02:28:08 +03:00
|
|
|
images = asyncio.run(copy_images(chunk.get_list(), chunk.options.get("cookies")))
|
|
|
|
yield self._format_json("content", str(ImageResponse(images, chunk.alt)))
|
2024-04-10 09:14:50 +03:00
|
|
|
elif not isinstance(chunk, FinishReason):
|
2024-03-26 08:42:47 +03:00
|
|
|
yield self._format_json("content", str(chunk))
|
2024-03-16 12:48:37 +03:00
|
|
|
except Exception as e:
|
|
|
|
logging.exception(e)
|
|
|
|
yield self._format_json('error', get_error_message(e))
|
|
|
|
|
|
|
|
def _format_json(self, response_type: str, content):
|
|
|
|
"""
|
|
|
|
Formats and returns a JSON response.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
response_type (str): The type of the response.
|
|
|
|
content: The content to be included in the response.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: A JSON formatted string.
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
'type': response_type,
|
|
|
|
response_type: content
|
|
|
|
}
|
2024-04-06 18:22:11 +03:00
|
|
|
|
2024-03-16 12:48:37 +03:00
|
|
|
def get_error_message(exception: Exception) -> str:
|
|
|
|
"""
|
|
|
|
Generates a formatted error message from an exception.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
exception (Exception): The exception to format.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: A formatted error message string.
|
|
|
|
"""
|
2024-04-07 11:36:13 +03:00
|
|
|
message = f"{type(exception).__name__}: {exception}"
|
|
|
|
provider = get_last_provider()
|
|
|
|
if provider is None:
|
|
|
|
return message
|
2024-09-04 20:56:07 +03:00
|
|
|
return f"{provider.__name__}: {message}"
|