mirror of
https://github.com/xtekky/gpt4free.git
synced 2025-12-06 02:30:41 -08:00
- In `g4f/__init__.py`, changed logger setup to use fixed "g4f" name and refactored `ChatCompletion.create` and `create_async` to share `_prepare_request` logic for preprocessing arguments - In `g4f/config.py`, added `__future__.annotations`, `lru_cache` import, wrapped `get_config_dir` with `@lru_cache`, and simplified platform branch logic - In `g4f/cookies.py`, added typing imports, renamed `browsers` to `BROWSERS`, reformatted `DOMAINS`, updated docstrings, improved loop logic in `load_cookies_from_browsers` with additional exception handling, split HAR/JSON parsing into `_parse_har_file` and `_parse_json_cookie_file`, and enhanced `read_cookie_files` with optional filters and `.env` loading - In `g4f/debug.py`, added enable/disable logging functions, updated log handler typing, appended messages to `logs` in `log()`, and improved `error()` formatting - In `g4f/errors.py`, introduced base `G4FError` and updated all exception classes to inherit from it or relevant subclasses, with descriptive docstrings for each - In `g4f/files.py`, added `max_length` parameter to `secure_filename`, adjusted regex formatting, and added docstring; updated `get_bucket_dir` to sanitize parts inline with docstring - In `g4f/typing.py`, added `__future__.annotations`, reorganized imports, restricted PIL import to type-checking, defined `ContentPart` and `Message` TypedDicts, updated type aliases and `__all__` to include new types - In `g4f/version.py`, added `lru_cache` and request timeout constant, applied caching to `get_pypi_version` and `get_github_version`, added response validation and explicit exceptions, refactored `VersionUtils.current_version` with clearer sources and error on miss, changed `check_version` to return a boolean with optional silent mode, and improved error handling outputs
91 lines
No EOL
3.5 KiB
Python
91 lines
No EOL
3.5 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import logging
|
|
from typing import Union, Optional, Coroutine
|
|
|
|
from . import debug, version
|
|
from .models import Model
|
|
from .client import Client, AsyncClient
|
|
from .typing import Messages, CreateResult, AsyncResult, ImageType
|
|
from .cookies import get_cookies, set_cookies
|
|
from .providers.types import ProviderType
|
|
from .providers.helper import concat_chunks, async_concat_chunks
|
|
from .client.service import get_model_and_provider
|
|
|
|
# Configure logger
|
|
logger = logging.getLogger("g4f")
|
|
handler = logging.StreamHandler()
|
|
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
|
|
logger.addHandler(handler)
|
|
logger.setLevel(logging.ERROR)
|
|
|
|
|
|
class ChatCompletion:
|
|
@staticmethod
|
|
def _prepare_request(model: Union[Model, str],
|
|
messages: Messages,
|
|
provider: Union[ProviderType, str, None],
|
|
stream: bool,
|
|
image: ImageType,
|
|
image_name: Optional[str],
|
|
ignore_working: bool,
|
|
ignore_stream: bool,
|
|
**kwargs):
|
|
"""Shared pre-processing for sync/async create methods."""
|
|
if image is not None:
|
|
kwargs["media"] = [(image, image_name)]
|
|
elif "images" in kwargs:
|
|
kwargs["media"] = kwargs.pop("images")
|
|
|
|
model, provider = get_model_and_provider(
|
|
model, provider, stream,
|
|
ignore_working,
|
|
ignore_stream,
|
|
has_images="media" in kwargs,
|
|
)
|
|
|
|
if "proxy" not in kwargs:
|
|
proxy = os.environ.get("G4F_PROXY")
|
|
if proxy:
|
|
kwargs["proxy"] = proxy
|
|
if ignore_stream:
|
|
kwargs["ignore_stream"] = True
|
|
|
|
return model, provider, kwargs
|
|
|
|
@staticmethod
|
|
def create(model: Union[Model, str],
|
|
messages: Messages,
|
|
provider: Union[ProviderType, str, None] = None,
|
|
stream: bool = False,
|
|
image: ImageType = None,
|
|
image_name: Optional[str] = None,
|
|
ignore_working: bool = False,
|
|
ignore_stream: bool = False,
|
|
**kwargs) -> Union[CreateResult, str]:
|
|
model, provider, kwargs = ChatCompletion._prepare_request(
|
|
model, messages, provider, stream, image, image_name,
|
|
ignore_working, ignore_stream, **kwargs
|
|
)
|
|
result = provider.create_function(model, messages, stream=stream, **kwargs)
|
|
return result if stream or ignore_stream else concat_chunks(result)
|
|
|
|
@staticmethod
|
|
def create_async(model: Union[Model, str],
|
|
messages: Messages,
|
|
provider: Union[ProviderType, str, None] = None,
|
|
stream: bool = False,
|
|
image: ImageType = None,
|
|
image_name: Optional[str] = None,
|
|
ignore_working: bool = False,
|
|
ignore_stream: bool = False,
|
|
**kwargs) -> Union[AsyncResult, Coroutine[str]]:
|
|
model, provider, kwargs = ChatCompletion._prepare_request(
|
|
model, messages, provider, stream, image, image_name,
|
|
ignore_working, ignore_stream, **kwargs
|
|
)
|
|
result = provider.async_create_function(model, messages, stream=stream, **kwargs)
|
|
if not stream and not ignore_stream and hasattr(result, "__aiter__"):
|
|
result = async_concat_chunks(result)
|
|
return result |