service.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. from __future__ import annotations
  2. from typing import Union
  3. from .. import debug, version
  4. from ..errors import ProviderNotFoundError, ModelNotFoundError, ProviderNotWorkingError, StreamNotSupportedError
  5. from ..models import Model, ModelUtils, default
  6. from ..Provider import ProviderUtils
  7. from ..providers.types import BaseRetryProvider, ProviderType
  8. from ..providers.retry_provider import IterListProvider
  9. def convert_to_provider(provider: str) -> ProviderType:
  10. if " " in provider:
  11. provider_list = [ProviderUtils.convert[p] for p in provider.split() if p in ProviderUtils.convert]
  12. if not provider_list:
  13. raise ProviderNotFoundError(f'Providers not found: {provider}')
  14. provider = IterListProvider(provider_list, False)
  15. elif provider in ProviderUtils.convert:
  16. provider = ProviderUtils.convert[provider]
  17. elif provider:
  18. raise ProviderNotFoundError(f'Provider not found: {provider}')
  19. return provider
  20. def get_model_and_provider(model : Union[Model, str],
  21. provider : Union[ProviderType, str, None],
  22. stream : bool,
  23. ignored : list[str] = None,
  24. ignore_working: bool = False,
  25. ignore_stream: bool = False) -> tuple[str, ProviderType]:
  26. """
  27. Retrieves the model and provider based on input parameters.
  28. Args:
  29. model (Union[Model, str]): The model to use, either as an object or a string identifier.
  30. provider (Union[ProviderType, str, None]): The provider to use, either as an object, a string identifier, or None.
  31. stream (bool): Indicates if the operation should be performed as a stream.
  32. ignored (list[str], optional): List of provider names to be ignored.
  33. ignore_working (bool, optional): If True, ignores the working status of the provider.
  34. ignore_stream (bool, optional): If True, ignores the streaming capability of the provider.
  35. Returns:
  36. tuple[str, ProviderType]: A tuple containing the model name and the provider type.
  37. Raises:
  38. ProviderNotFoundError: If the provider is not found.
  39. ModelNotFoundError: If the model is not found.
  40. ProviderNotWorkingError: If the provider is not working.
  41. StreamNotSupportedError: If streaming is not supported by the provider.
  42. """
  43. if debug.version_check:
  44. debug.version_check = False
  45. version.utils.check_version()
  46. if isinstance(provider, str):
  47. provider = convert_to_provider(provider)
  48. if isinstance(model, str):
  49. if model in ModelUtils.convert:
  50. model = ModelUtils.convert[model]
  51. if not provider:
  52. if not model:
  53. model = default
  54. provider = model.best_provider
  55. elif isinstance(model, str):
  56. if model in ProviderUtils.convert:
  57. provider = ProviderUtils.convert[model]
  58. model = provider.default_model if hasattr(provider, "default_model") else ""
  59. else:
  60. raise ModelNotFoundError(f'Model not found: {model}')
  61. elif isinstance(model, Model):
  62. provider = model.best_provider
  63. else:
  64. raise ValueError(f"Unexpected type: {type(model)}")
  65. if not provider:
  66. raise ProviderNotFoundError(f'No provider found for model: {model}')
  67. provider_name = provider.__name__ if hasattr(provider, "__name__") else type(provider).__name__
  68. if isinstance(model, Model):
  69. model = model.name
  70. if not ignore_working and not provider.working:
  71. raise ProviderNotWorkingError(f"{provider_name} is not working")
  72. if isinstance(provider, BaseRetryProvider):
  73. if not ignore_working:
  74. provider.providers = [p for p in provider.providers if p.working]
  75. if ignored:
  76. provider.providers = [p for p in provider.providers if p.__name__ not in ignored]
  77. if not ignore_stream and not provider.supports_stream and stream:
  78. raise StreamNotSupportedError(f'{provider_name} does not support "stream" argument')
  79. if model:
  80. debug.log(f'Using {provider_name} provider and {model} model')
  81. else:
  82. debug.log(f'Using {provider_name} provider')
  83. debug.last_provider = provider
  84. debug.last_model = model
  85. return model, provider
  86. def get_last_provider(as_dict: bool = False) -> Union[ProviderType, dict[str, str], None]:
  87. """
  88. Retrieves the last used provider.
  89. Args:
  90. as_dict (bool, optional): If True, returns the provider information as a dictionary.
  91. Returns:
  92. Union[ProviderType, dict[str, str]]: The last used provider, either as an object or a dictionary.
  93. """
  94. last = debug.last_provider
  95. if isinstance(last, BaseRetryProvider):
  96. last = last.last_provider
  97. if as_dict:
  98. if last:
  99. return {
  100. "name": last.__name__ if hasattr(last, "__name__") else type(last).__name__,
  101. "url": last.url,
  102. "model": debug.last_model,
  103. "label": getattr(last, "label", None) if hasattr(last, "label") else None
  104. }
  105. else:
  106. return {}
  107. return last