model_provider_service.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import logging
  2. from typing import Optional
  3. from core.entities.model_entities import ModelStatus, ProviderModelWithStatusEntity
  4. from core.model_runtime.entities.model_entities import ModelType, ParameterRule
  5. from core.model_runtime.model_providers.model_provider_factory import ModelProviderFactory
  6. from core.provider_manager import ProviderManager
  7. from models.provider import ProviderType
  8. from services.entities.model_provider_entities import (
  9. CustomConfigurationResponse,
  10. CustomConfigurationStatus,
  11. DefaultModelResponse,
  12. ModelWithProviderEntityResponse,
  13. ProviderResponse,
  14. ProviderWithModelsResponse,
  15. SimpleProviderEntityResponse,
  16. SystemConfigurationResponse,
  17. )
  18. logger = logging.getLogger(__name__)
  19. class ModelProviderService:
  20. """
  21. Model Provider Service
  22. """
  23. def __init__(self) -> None:
  24. self.provider_manager = ProviderManager()
  25. def get_provider_list(self, tenant_id: str, model_type: Optional[str] = None) -> list[ProviderResponse]:
  26. """
  27. get provider list.
  28. :param tenant_id: workspace id
  29. :param model_type: model type
  30. :return:
  31. """
  32. # Get all provider configurations of the current workspace
  33. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  34. provider_responses = []
  35. for provider_configuration in provider_configurations.values():
  36. if model_type:
  37. model_type_entity = ModelType.value_of(model_type)
  38. if model_type_entity not in provider_configuration.provider.supported_model_types:
  39. continue
  40. provider_response = ProviderResponse(
  41. provider=provider_configuration.provider.provider,
  42. label=provider_configuration.provider.label,
  43. description=provider_configuration.provider.description,
  44. icon_small=provider_configuration.provider.icon_small,
  45. icon_large=provider_configuration.provider.icon_large,
  46. background=provider_configuration.provider.background,
  47. help=provider_configuration.provider.help,
  48. supported_model_types=provider_configuration.provider.supported_model_types,
  49. configurate_methods=provider_configuration.provider.configurate_methods,
  50. provider_credential_schema=provider_configuration.provider.provider_credential_schema,
  51. model_credential_schema=provider_configuration.provider.model_credential_schema,
  52. preferred_provider_type=provider_configuration.preferred_provider_type,
  53. custom_configuration=CustomConfigurationResponse(
  54. status=CustomConfigurationStatus.ACTIVE
  55. if provider_configuration.is_custom_configuration_available()
  56. else CustomConfigurationStatus.NO_CONFIGURE
  57. ),
  58. system_configuration=SystemConfigurationResponse(
  59. enabled=provider_configuration.system_configuration.enabled,
  60. current_quota_type=provider_configuration.system_configuration.current_quota_type,
  61. quota_configurations=provider_configuration.system_configuration.quota_configurations,
  62. ),
  63. )
  64. provider_responses.append(provider_response)
  65. return provider_responses
  66. def get_models_by_provider(self, tenant_id: str, provider: str) -> list[ModelWithProviderEntityResponse]:
  67. """
  68. get provider models.
  69. For the model provider page,
  70. only supports passing in a single provider to query the list of supported models.
  71. :param tenant_id:
  72. :param provider:
  73. :return:
  74. """
  75. # Get all provider configurations of the current workspace
  76. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  77. # Get provider available models
  78. return [
  79. ModelWithProviderEntityResponse(model) for model in provider_configurations.get_models(provider=provider)
  80. ]
  81. def get_provider_credentials(self, tenant_id: str, provider: str) -> Optional[dict]:
  82. """
  83. get provider credentials.
  84. :param tenant_id:
  85. :param provider:
  86. :return:
  87. """
  88. # Get all provider configurations of the current workspace
  89. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  90. # Get provider configuration
  91. provider_configuration = provider_configurations.get(provider)
  92. if not provider_configuration:
  93. raise ValueError(f"Provider {provider} does not exist.")
  94. # Get provider custom credentials from workspace
  95. return provider_configuration.get_custom_credentials(obfuscated=True)
  96. def provider_credentials_validate(self, tenant_id: str, provider: str, credentials: dict) -> None:
  97. """
  98. validate provider credentials.
  99. :param tenant_id:
  100. :param provider:
  101. :param credentials:
  102. """
  103. # Get all provider configurations of the current workspace
  104. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  105. # Get provider configuration
  106. provider_configuration = provider_configurations.get(provider)
  107. if not provider_configuration:
  108. raise ValueError(f"Provider {provider} does not exist.")
  109. provider_configuration.custom_credentials_validate(credentials)
  110. def save_provider_credentials(self, tenant_id: str, provider: str, credentials: dict) -> None:
  111. """
  112. save custom provider config.
  113. :param tenant_id: workspace id
  114. :param provider: provider name
  115. :param credentials: provider credentials
  116. :return:
  117. """
  118. # Get all provider configurations of the current workspace
  119. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  120. # Get provider configuration
  121. provider_configuration = provider_configurations.get(provider)
  122. if not provider_configuration:
  123. raise ValueError(f"Provider {provider} does not exist.")
  124. # Add or update custom provider credentials.
  125. provider_configuration.add_or_update_custom_credentials(credentials)
  126. def remove_provider_credentials(self, tenant_id: str, provider: str) -> None:
  127. """
  128. remove custom provider config.
  129. :param tenant_id: workspace id
  130. :param provider: provider name
  131. :return:
  132. """
  133. # Get all provider configurations of the current workspace
  134. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  135. # Get provider configuration
  136. provider_configuration = provider_configurations.get(provider)
  137. if not provider_configuration:
  138. raise ValueError(f"Provider {provider} does not exist.")
  139. # Remove custom provider credentials.
  140. provider_configuration.delete_custom_credentials()
  141. def get_model_credentials(self, tenant_id: str, provider: str, model_type: str, model: str) -> Optional[dict]:
  142. """
  143. get model credentials.
  144. :param tenant_id: workspace id
  145. :param provider: provider name
  146. :param model_type: model type
  147. :param model: model name
  148. :return:
  149. """
  150. # Get all provider configurations of the current workspace
  151. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  152. # Get provider configuration
  153. provider_configuration = provider_configurations.get(provider)
  154. if not provider_configuration:
  155. raise ValueError(f"Provider {provider} does not exist.")
  156. # Get model custom credentials from ProviderModel if exists
  157. return provider_configuration.get_custom_model_credentials(
  158. model_type=ModelType.value_of(model_type), model=model, obfuscated=True
  159. )
  160. def model_credentials_validate(
  161. self, tenant_id: str, provider: str, model_type: str, model: str, credentials: dict
  162. ) -> None:
  163. """
  164. validate model credentials.
  165. :param tenant_id: workspace id
  166. :param provider: provider name
  167. :param model_type: model type
  168. :param model: model name
  169. :param credentials: model credentials
  170. :return:
  171. """
  172. # Get all provider configurations of the current workspace
  173. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  174. # Get provider configuration
  175. provider_configuration = provider_configurations.get(provider)
  176. if not provider_configuration:
  177. raise ValueError(f"Provider {provider} does not exist.")
  178. # Validate model credentials
  179. provider_configuration.custom_model_credentials_validate(
  180. model_type=ModelType.value_of(model_type), model=model, credentials=credentials
  181. )
  182. def save_model_credentials(
  183. self, tenant_id: str, provider: str, model_type: str, model: str, credentials: dict
  184. ) -> None:
  185. """
  186. save model credentials.
  187. :param tenant_id: workspace id
  188. :param provider: provider name
  189. :param model_type: model type
  190. :param model: model name
  191. :param credentials: model credentials
  192. :return:
  193. """
  194. # Get all provider configurations of the current workspace
  195. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  196. # Get provider configuration
  197. provider_configuration = provider_configurations.get(provider)
  198. if not provider_configuration:
  199. raise ValueError(f"Provider {provider} does not exist.")
  200. # Add or update custom model credentials
  201. provider_configuration.add_or_update_custom_model_credentials(
  202. model_type=ModelType.value_of(model_type), model=model, credentials=credentials
  203. )
  204. def remove_model_credentials(self, tenant_id: str, provider: str, model_type: str, model: str) -> None:
  205. """
  206. remove model credentials.
  207. :param tenant_id: workspace id
  208. :param provider: provider name
  209. :param model_type: model type
  210. :param model: model name
  211. :return:
  212. """
  213. # Get all provider configurations of the current workspace
  214. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  215. # Get provider configuration
  216. provider_configuration = provider_configurations.get(provider)
  217. if not provider_configuration:
  218. raise ValueError(f"Provider {provider} does not exist.")
  219. # Remove custom model credentials
  220. provider_configuration.delete_custom_model_credentials(model_type=ModelType.value_of(model_type), model=model)
  221. def get_models_by_model_type(self, tenant_id: str, model_type: str) -> list[ProviderWithModelsResponse]:
  222. """
  223. get models by model type.
  224. :param tenant_id: workspace id
  225. :param model_type: model type
  226. :return:
  227. """
  228. # Get all provider configurations of the current workspace
  229. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  230. # Get provider available models
  231. models = provider_configurations.get_models(model_type=ModelType.value_of(model_type))
  232. # Group models by provider
  233. provider_models = {}
  234. for model in models:
  235. if model.provider.provider not in provider_models:
  236. provider_models[model.provider.provider] = []
  237. if model.deprecated:
  238. continue
  239. if model.status != ModelStatus.ACTIVE:
  240. continue
  241. provider_models[model.provider.provider].append(model)
  242. # convert to ProviderWithModelsResponse list
  243. providers_with_models: list[ProviderWithModelsResponse] = []
  244. for provider, models in provider_models.items():
  245. if not models:
  246. continue
  247. first_model = models[0]
  248. providers_with_models.append(
  249. ProviderWithModelsResponse(
  250. provider=provider,
  251. label=first_model.provider.label,
  252. icon_small=first_model.provider.icon_small,
  253. icon_large=first_model.provider.icon_large,
  254. status=CustomConfigurationStatus.ACTIVE,
  255. models=[
  256. ProviderModelWithStatusEntity(
  257. model=model.model,
  258. label=model.label,
  259. model_type=model.model_type,
  260. features=model.features,
  261. fetch_from=model.fetch_from,
  262. model_properties=model.model_properties,
  263. status=model.status,
  264. load_balancing_enabled=model.load_balancing_enabled,
  265. )
  266. for model in models
  267. ],
  268. )
  269. )
  270. return providers_with_models
  271. def get_model_parameter_rules(self, tenant_id: str, provider: str, model: str) -> list[ParameterRule]:
  272. """
  273. get model parameter rules.
  274. Only supports LLM.
  275. :param tenant_id: workspace id
  276. :param provider: provider name
  277. :param model: model name
  278. :return:
  279. """
  280. # Get all provider configurations of the current workspace
  281. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  282. # Get provider configuration
  283. provider_configuration = provider_configurations.get(provider)
  284. if not provider_configuration:
  285. raise ValueError(f"Provider {provider} does not exist.")
  286. # fetch credentials
  287. credentials = provider_configuration.get_current_credentials(model_type=ModelType.LLM, model=model)
  288. if not credentials:
  289. return []
  290. model_schema = provider_configuration.get_model_schema(
  291. model_type=ModelType.LLM, model=model, credentials=credentials
  292. )
  293. return model_schema.parameter_rules if model_schema else []
  294. def get_default_model_of_model_type(self, tenant_id: str, model_type: str) -> Optional[DefaultModelResponse]:
  295. """
  296. get default model of model type.
  297. :param tenant_id: workspace id
  298. :param model_type: model type
  299. :return:
  300. """
  301. model_type_enum = ModelType.value_of(model_type)
  302. try:
  303. result = self.provider_manager.get_default_model(tenant_id=tenant_id, model_type=model_type_enum)
  304. return (
  305. DefaultModelResponse(
  306. model=result.model,
  307. model_type=result.model_type,
  308. provider=SimpleProviderEntityResponse(
  309. provider=result.provider.provider,
  310. label=result.provider.label,
  311. icon_small=result.provider.icon_small,
  312. icon_large=result.provider.icon_large,
  313. supported_model_types=result.provider.supported_model_types,
  314. ),
  315. )
  316. if result
  317. else None
  318. )
  319. except Exception as e:
  320. logger.debug(f"get_default_model_of_model_type error: {e}")
  321. return None
  322. def update_default_model_of_model_type(self, tenant_id: str, model_type: str, provider: str, model: str) -> None:
  323. """
  324. update default model of model type.
  325. :param tenant_id: workspace id
  326. :param model_type: model type
  327. :param provider: provider name
  328. :param model: model name
  329. :return:
  330. """
  331. model_type_enum = ModelType.value_of(model_type)
  332. self.provider_manager.update_default_model_record(
  333. tenant_id=tenant_id, model_type=model_type_enum, provider=provider, model=model
  334. )
  335. def get_model_provider_icon(
  336. self, tenant_id: str, provider: str, icon_type: str, lang: str
  337. ) -> tuple[Optional[bytes], Optional[str]]:
  338. """
  339. get model provider icon.
  340. :param tenant_id: workspace id
  341. :param provider: provider name
  342. :param icon_type: icon type (icon_small or icon_large)
  343. :param lang: language (zh_Hans or en_US)
  344. :return:
  345. """
  346. model_provider_factory = ModelProviderFactory(tenant_id)
  347. byte_data, mime_type = model_provider_factory.get_provider_icon(provider, icon_type, lang)
  348. return byte_data, mime_type
  349. def switch_preferred_provider(self, tenant_id: str, provider: str, preferred_provider_type: str) -> None:
  350. """
  351. switch preferred provider.
  352. :param tenant_id: workspace id
  353. :param provider: provider name
  354. :param preferred_provider_type: preferred provider type
  355. :return:
  356. """
  357. # Get all provider configurations of the current workspace
  358. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  359. # Convert preferred_provider_type to ProviderType
  360. preferred_provider_type_enum = ProviderType.value_of(preferred_provider_type)
  361. # Get provider configuration
  362. provider_configuration = provider_configurations.get(provider)
  363. if not provider_configuration:
  364. raise ValueError(f"Provider {provider} does not exist.")
  365. # Switch preferred provider type
  366. provider_configuration.switch_preferred_provider_type(preferred_provider_type_enum)
  367. def enable_model(self, tenant_id: str, provider: str, model: str, model_type: str) -> None:
  368. """
  369. enable model.
  370. :param tenant_id: workspace id
  371. :param provider: provider name
  372. :param model: model name
  373. :param model_type: model type
  374. :return:
  375. """
  376. # Get all provider configurations of the current workspace
  377. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  378. # Get provider configuration
  379. provider_configuration = provider_configurations.get(provider)
  380. if not provider_configuration:
  381. raise ValueError(f"Provider {provider} does not exist.")
  382. # Enable model
  383. provider_configuration.enable_model(model=model, model_type=ModelType.value_of(model_type))
  384. def disable_model(self, tenant_id: str, provider: str, model: str, model_type: str) -> None:
  385. """
  386. disable model.
  387. :param tenant_id: workspace id
  388. :param provider: provider name
  389. :param model: model name
  390. :param model_type: model type
  391. :return:
  392. """
  393. # Get all provider configurations of the current workspace
  394. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  395. # Get provider configuration
  396. provider_configuration = provider_configurations.get(provider)
  397. if not provider_configuration:
  398. raise ValueError(f"Provider {provider} does not exist.")
  399. # Enable model
  400. provider_configuration.disable_model(model=model, model_type=ModelType.value_of(model_type))