model_provider_service.py 19 KB

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