__init__.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from __future__ import annotations
  2. import os
  3. import logging
  4. from typing import Union, Optional, Coroutine
  5. from . import debug, version
  6. from .models import Model
  7. from .client import Client, AsyncClient
  8. from .typing import Messages, CreateResult, AsyncResult, ImageType
  9. from .errors import StreamNotSupportedError
  10. from .cookies import get_cookies, set_cookies
  11. from .providers.types import ProviderType
  12. from .providers.helper import concat_chunks, async_concat_chunks
  13. from .client.service import get_model_and_provider
  14. #Configure "g4f" logger
  15. logger = logging.getLogger(__name__)
  16. log_handler = logging.StreamHandler()
  17. log_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
  18. logger.addHandler(log_handler)
  19. logger.setLevel(logging.ERROR)
  20. class ChatCompletion:
  21. @staticmethod
  22. def create(model : Union[Model, str],
  23. messages : Messages,
  24. provider : Union[ProviderType, str, None] = None,
  25. stream : bool = False,
  26. image : ImageType = None,
  27. image_name: Optional[str] = None,
  28. ignore_working: bool = False,
  29. ignore_stream: bool = False,
  30. **kwargs) -> Union[CreateResult, str]:
  31. if image is not None:
  32. kwargs["images"] = [(image, image_name)]
  33. model, provider = get_model_and_provider(
  34. model, provider, stream,
  35. ignore_working,
  36. ignore_stream,
  37. has_images="images" in kwargs,
  38. )
  39. if "proxy" not in kwargs:
  40. proxy = os.environ.get("G4F_PROXY")
  41. if proxy:
  42. kwargs["proxy"] = proxy
  43. if ignore_stream:
  44. kwargs["ignore_stream"] = True
  45. result = provider.get_create_function()(model, messages, stream=stream, **kwargs)
  46. return result if stream else concat_chunks(result)
  47. @staticmethod
  48. def create_async(model : Union[Model, str],
  49. messages : Messages,
  50. provider : Union[ProviderType, str, None] = None,
  51. stream : bool = False,
  52. image : ImageType = None,
  53. image_name: Optional[str] = None,
  54. ignore_stream: bool = False,
  55. ignore_working: bool = False,
  56. **kwargs) -> Union[AsyncResult, Coroutine[str]]:
  57. if image is not None:
  58. kwargs["images"] = [(image, image_name)]
  59. model, provider = get_model_and_provider(model, provider, False, ignore_working, has_images="images" in kwargs)
  60. if "proxy" not in kwargs:
  61. proxy = os.environ.get("G4F_PROXY")
  62. if proxy:
  63. kwargs["proxy"] = proxy
  64. if ignore_stream:
  65. kwargs["ignore_stream"] = True
  66. result = provider.get_async_create_function()(model, messages, stream=stream, **kwargs)
  67. if not stream:
  68. if hasattr(result, "__aiter__"):
  69. result = async_concat_chunks(result)
  70. return result