model_provider_service.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. import logging
  2. import mimetypes
  3. import os
  4. from typing import Optional, cast
  5. import requests
  6. from flask import current_app
  7. from core.entities.model_entities import ModelStatus, ProviderModelWithStatusEntity
  8. from core.model_runtime.entities.model_entities import ModelType, ParameterRule
  9. from core.model_runtime.model_providers import model_provider_factory
  10. from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
  11. from core.provider_manager import ProviderManager
  12. from models.provider import ProviderType
  13. from services.entities.model_provider_entities import (
  14. CustomConfigurationResponse,
  15. CustomConfigurationStatus,
  16. DefaultModelResponse,
  17. ModelWithProviderEntityResponse,
  18. ProviderResponse,
  19. ProviderWithModelsResponse,
  20. SimpleProviderEntityResponse,
  21. SystemConfigurationResponse,
  22. )
  23. logger = logging.getLogger(__name__)
  24. class ModelProviderService:
  25. """
  26. Model Provider Service
  27. """
  28. def __init__(self) -> None:
  29. self.provider_manager = ProviderManager()
  30. def get_provider_list(self, tenant_id: str, model_type: Optional[str] = None) -> list[ProviderResponse]:
  31. """
  32. get provider list.
  33. :param tenant_id: workspace id
  34. :param model_type: model type
  35. :return:
  36. """
  37. # Get all provider configurations of the current workspace
  38. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  39. provider_responses = []
  40. for provider_configuration in provider_configurations.values():
  41. if model_type:
  42. model_type_entity = ModelType.value_of(model_type)
  43. if model_type_entity not in provider_configuration.provider.supported_model_types:
  44. continue
  45. provider_response = ProviderResponse(
  46. provider=provider_configuration.provider.provider,
  47. label=provider_configuration.provider.label,
  48. description=provider_configuration.provider.description,
  49. icon_small=provider_configuration.provider.icon_small,
  50. icon_large=provider_configuration.provider.icon_large,
  51. background=provider_configuration.provider.background,
  52. help=provider_configuration.provider.help,
  53. supported_model_types=provider_configuration.provider.supported_model_types,
  54. configurate_methods=provider_configuration.provider.configurate_methods,
  55. provider_credential_schema=provider_configuration.provider.provider_credential_schema,
  56. model_credential_schema=provider_configuration.provider.model_credential_schema,
  57. preferred_provider_type=provider_configuration.preferred_provider_type,
  58. custom_configuration=CustomConfigurationResponse(
  59. status=CustomConfigurationStatus.ACTIVE
  60. if provider_configuration.is_custom_configuration_available()
  61. else CustomConfigurationStatus.NO_CONFIGURE
  62. ),
  63. system_configuration=SystemConfigurationResponse(
  64. enabled=provider_configuration.system_configuration.enabled,
  65. current_quota_type=provider_configuration.system_configuration.current_quota_type,
  66. quota_configurations=provider_configuration.system_configuration.quota_configurations,
  67. ),
  68. )
  69. provider_responses.append(provider_response)
  70. return provider_responses
  71. def get_models_by_provider(self, tenant_id: str, provider: str) -> list[ModelWithProviderEntityResponse]:
  72. """
  73. get provider models.
  74. For the model provider page,
  75. only supports passing in a single provider to query the list of supported models.
  76. :param tenant_id:
  77. :param provider:
  78. :return:
  79. """
  80. # Get all provider configurations of the current workspace
  81. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  82. # Get provider available models
  83. return [
  84. ModelWithProviderEntityResponse(model) for model in provider_configurations.get_models(provider=provider)
  85. ]
  86. def get_provider_credentials(self, tenant_id: str, provider: str) -> dict:
  87. """
  88. get provider credentials.
  89. :param tenant_id:
  90. :param provider:
  91. :return:
  92. """
  93. # Get all provider configurations of the current workspace
  94. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  95. # Get provider configuration
  96. provider_configuration = provider_configurations.get(provider)
  97. if not provider_configuration:
  98. raise ValueError(f"Provider {provider} does not exist.")
  99. # Get provider custom credentials from workspace
  100. return provider_configuration.get_custom_credentials(obfuscated=True)
  101. def provider_credentials_validate(self, tenant_id: str, provider: str, credentials: dict) -> None:
  102. """
  103. validate provider credentials.
  104. :param tenant_id:
  105. :param provider:
  106. :param credentials:
  107. """
  108. # Get all provider configurations of the current workspace
  109. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  110. # Get provider configuration
  111. provider_configuration = provider_configurations.get(provider)
  112. if not provider_configuration:
  113. raise ValueError(f"Provider {provider} does not exist.")
  114. provider_configuration.custom_credentials_validate(credentials)
  115. def save_provider_credentials(self, tenant_id: str, provider: str, credentials: dict) -> None:
  116. """
  117. save custom provider config.
  118. :param tenant_id: workspace id
  119. :param provider: provider name
  120. :param credentials: provider credentials
  121. :return:
  122. """
  123. # Get all provider configurations of the current workspace
  124. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  125. # Get provider configuration
  126. provider_configuration = provider_configurations.get(provider)
  127. if not provider_configuration:
  128. raise ValueError(f"Provider {provider} does not exist.")
  129. # Add or update custom provider credentials.
  130. provider_configuration.add_or_update_custom_credentials(credentials)
  131. def remove_provider_credentials(self, tenant_id: str, provider: str) -> None:
  132. """
  133. remove custom provider config.
  134. :param tenant_id: workspace id
  135. :param provider: provider name
  136. :return:
  137. """
  138. # Get all provider configurations of the current workspace
  139. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  140. # Get provider configuration
  141. provider_configuration = provider_configurations.get(provider)
  142. if not provider_configuration:
  143. raise ValueError(f"Provider {provider} does not exist.")
  144. # Remove custom provider credentials.
  145. provider_configuration.delete_custom_credentials()
  146. def get_model_credentials(self, tenant_id: str, provider: str, model_type: str, model: str) -> dict:
  147. """
  148. get model credentials.
  149. :param tenant_id: workspace id
  150. :param provider: provider name
  151. :param model_type: model type
  152. :param model: model name
  153. :return:
  154. """
  155. # Get all provider configurations of the current workspace
  156. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  157. # Get provider configuration
  158. provider_configuration = provider_configurations.get(provider)
  159. if not provider_configuration:
  160. raise ValueError(f"Provider {provider} does not exist.")
  161. # Get model custom credentials from ProviderModel if exists
  162. return provider_configuration.get_custom_model_credentials(
  163. model_type=ModelType.value_of(model_type), model=model, obfuscated=True
  164. )
  165. def model_credentials_validate(
  166. self, tenant_id: str, provider: str, model_type: str, model: str, credentials: dict
  167. ) -> None:
  168. """
  169. validate model credentials.
  170. :param tenant_id: workspace id
  171. :param provider: provider name
  172. :param model_type: model type
  173. :param model: model name
  174. :param credentials: model credentials
  175. :return:
  176. """
  177. # Get all provider configurations of the current workspace
  178. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  179. # Get provider configuration
  180. provider_configuration = provider_configurations.get(provider)
  181. if not provider_configuration:
  182. raise ValueError(f"Provider {provider} does not exist.")
  183. # Validate model credentials
  184. provider_configuration.custom_model_credentials_validate(
  185. model_type=ModelType.value_of(model_type), model=model, credentials=credentials
  186. )
  187. def save_model_credentials(
  188. self, tenant_id: str, provider: str, model_type: str, model: str, credentials: dict
  189. ) -> None:
  190. """
  191. save model credentials.
  192. :param tenant_id: workspace id
  193. :param provider: provider name
  194. :param model_type: model type
  195. :param model: model name
  196. :param credentials: model credentials
  197. :return:
  198. """
  199. # Get all provider configurations of the current workspace
  200. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  201. # Get provider configuration
  202. provider_configuration = provider_configurations.get(provider)
  203. if not provider_configuration:
  204. raise ValueError(f"Provider {provider} does not exist.")
  205. # Add or update custom model credentials
  206. provider_configuration.add_or_update_custom_model_credentials(
  207. model_type=ModelType.value_of(model_type), model=model, credentials=credentials
  208. )
  209. def remove_model_credentials(self, tenant_id: str, provider: str, model_type: str, model: str) -> None:
  210. """
  211. remove model credentials.
  212. :param tenant_id: workspace id
  213. :param provider: provider name
  214. :param model_type: model type
  215. :param model: model name
  216. :return:
  217. """
  218. # Get all provider configurations of the current workspace
  219. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  220. # Get provider configuration
  221. provider_configuration = provider_configurations.get(provider)
  222. if not provider_configuration:
  223. raise ValueError(f"Provider {provider} does not exist.")
  224. # Remove custom model credentials
  225. provider_configuration.delete_custom_model_credentials(model_type=ModelType.value_of(model_type), model=model)
  226. def get_models_by_model_type(self, tenant_id: str, model_type: str) -> list[ProviderWithModelsResponse]:
  227. """
  228. get models by model type.
  229. :param tenant_id: workspace id
  230. :param model_type: model type
  231. :return:
  232. """
  233. # Get all provider configurations of the current workspace
  234. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  235. # Get provider available models
  236. models = provider_configurations.get_models(model_type=ModelType.value_of(model_type))
  237. # Group models by provider
  238. provider_models = {}
  239. for model in models:
  240. if model.provider.provider not in provider_models:
  241. provider_models[model.provider.provider] = []
  242. if model.deprecated:
  243. continue
  244. if model.status != ModelStatus.ACTIVE:
  245. continue
  246. provider_models[model.provider.provider].append(model)
  247. # convert to ProviderWithModelsResponse list
  248. providers_with_models: list[ProviderWithModelsResponse] = []
  249. for provider, models in provider_models.items():
  250. if not models:
  251. continue
  252. first_model = models[0]
  253. providers_with_models.append(
  254. ProviderWithModelsResponse(
  255. provider=provider,
  256. label=first_model.provider.label,
  257. icon_small=first_model.provider.icon_small,
  258. icon_large=first_model.provider.icon_large,
  259. status=CustomConfigurationStatus.ACTIVE,
  260. models=[
  261. ProviderModelWithStatusEntity(
  262. model=model.model,
  263. label=model.label,
  264. model_type=model.model_type,
  265. features=model.features,
  266. fetch_from=model.fetch_from,
  267. model_properties=model.model_properties,
  268. status=model.status,
  269. load_balancing_enabled=model.load_balancing_enabled,
  270. )
  271. for model in models
  272. ],
  273. )
  274. )
  275. return providers_with_models
  276. def get_model_parameter_rules(self, tenant_id: str, provider: str, model: str) -> list[ParameterRule]:
  277. """
  278. get model parameter rules.
  279. Only supports LLM.
  280. :param tenant_id: workspace id
  281. :param provider: provider name
  282. :param model: model name
  283. :return:
  284. """
  285. # Get all provider configurations of the current workspace
  286. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  287. # Get provider configuration
  288. provider_configuration = provider_configurations.get(provider)
  289. if not provider_configuration:
  290. raise ValueError(f"Provider {provider} does not exist.")
  291. # Get model instance of LLM
  292. model_type_instance = provider_configuration.get_model_type_instance(ModelType.LLM)
  293. model_type_instance = cast(LargeLanguageModel, model_type_instance)
  294. # fetch credentials
  295. credentials = provider_configuration.get_current_credentials(model_type=ModelType.LLM, model=model)
  296. if not credentials:
  297. return []
  298. # Call get_parameter_rules method of model instance to get model parameter rules
  299. return model_type_instance.get_parameter_rules(model=model, credentials=credentials)
  300. def get_default_model_of_model_type(self, tenant_id: str, model_type: str) -> Optional[DefaultModelResponse]:
  301. """
  302. get default model of model type.
  303. :param tenant_id: workspace id
  304. :param model_type: model type
  305. :return:
  306. """
  307. model_type_enum = ModelType.value_of(model_type)
  308. result = self.provider_manager.get_default_model(tenant_id=tenant_id, model_type=model_type_enum)
  309. try:
  310. return (
  311. DefaultModelResponse(
  312. model=result.model,
  313. model_type=result.model_type,
  314. provider=SimpleProviderEntityResponse(
  315. provider=result.provider.provider,
  316. label=result.provider.label,
  317. icon_small=result.provider.icon_small,
  318. icon_large=result.provider.icon_large,
  319. supported_model_types=result.provider.supported_model_types,
  320. ),
  321. )
  322. if result
  323. else None
  324. )
  325. except Exception as e:
  326. logger.info(f"get_default_model_of_model_type error: {e}")
  327. return None
  328. def update_default_model_of_model_type(self, tenant_id: str, model_type: str, provider: str, model: str) -> None:
  329. """
  330. update default model of model type.
  331. :param tenant_id: workspace id
  332. :param model_type: model type
  333. :param provider: provider name
  334. :param model: model name
  335. :return:
  336. """
  337. model_type_enum = ModelType.value_of(model_type)
  338. self.provider_manager.update_default_model_record(
  339. tenant_id=tenant_id, model_type=model_type_enum, provider=provider, model=model
  340. )
  341. def get_model_provider_icon(
  342. self, provider: str, icon_type: str, lang: str
  343. ) -> tuple[Optional[bytes], Optional[str]]:
  344. """
  345. get model provider icon.
  346. :param provider: provider name
  347. :param icon_type: icon type (icon_small or icon_large)
  348. :param lang: language (zh_Hans or en_US)
  349. :return:
  350. """
  351. provider_instance = model_provider_factory.get_provider_instance(provider)
  352. provider_schema = provider_instance.get_provider_schema()
  353. if icon_type.lower() == "icon_small":
  354. if not provider_schema.icon_small:
  355. raise ValueError(f"Provider {provider} does not have small icon.")
  356. if lang.lower() == "zh_hans":
  357. file_name = provider_schema.icon_small.zh_Hans
  358. else:
  359. file_name = provider_schema.icon_small.en_US
  360. else:
  361. if not provider_schema.icon_large:
  362. raise ValueError(f"Provider {provider} does not have large icon.")
  363. if lang.lower() == "zh_hans":
  364. file_name = provider_schema.icon_large.zh_Hans
  365. else:
  366. file_name = provider_schema.icon_large.en_US
  367. root_path = current_app.root_path
  368. provider_instance_path = os.path.dirname(
  369. os.path.join(root_path, provider_instance.__class__.__module__.replace(".", "/"))
  370. )
  371. file_path = os.path.join(provider_instance_path, "_assets")
  372. file_path = os.path.join(file_path, file_name)
  373. if not os.path.exists(file_path):
  374. return None, None
  375. mimetype, _ = mimetypes.guess_type(file_path)
  376. mimetype = mimetype or "application/octet-stream"
  377. # read binary from file
  378. with open(file_path, "rb") as f:
  379. byte_data = f.read()
  380. return byte_data, mimetype
  381. def switch_preferred_provider(self, tenant_id: str, provider: str, preferred_provider_type: str) -> None:
  382. """
  383. switch preferred provider.
  384. :param tenant_id: workspace id
  385. :param provider: provider name
  386. :param preferred_provider_type: preferred provider type
  387. :return:
  388. """
  389. # Get all provider configurations of the current workspace
  390. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  391. # Convert preferred_provider_type to ProviderType
  392. preferred_provider_type_enum = ProviderType.value_of(preferred_provider_type)
  393. # Get provider configuration
  394. provider_configuration = provider_configurations.get(provider)
  395. if not provider_configuration:
  396. raise ValueError(f"Provider {provider} does not exist.")
  397. # Switch preferred provider type
  398. provider_configuration.switch_preferred_provider_type(preferred_provider_type_enum)
  399. def enable_model(self, tenant_id: str, provider: str, model: str, model_type: str) -> None:
  400. """
  401. enable model.
  402. :param tenant_id: workspace id
  403. :param provider: provider name
  404. :param model: model name
  405. :param model_type: model type
  406. :return:
  407. """
  408. # Get all provider configurations of the current workspace
  409. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  410. # Get provider configuration
  411. provider_configuration = provider_configurations.get(provider)
  412. if not provider_configuration:
  413. raise ValueError(f"Provider {provider} does not exist.")
  414. # Enable model
  415. provider_configuration.enable_model(model=model, model_type=ModelType.value_of(model_type))
  416. def disable_model(self, tenant_id: str, provider: str, model: str, model_type: str) -> None:
  417. """
  418. disable model.
  419. :param tenant_id: workspace id
  420. :param provider: provider name
  421. :param model: model name
  422. :param model_type: model type
  423. :return:
  424. """
  425. # Get all provider configurations of the current workspace
  426. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  427. # Get provider configuration
  428. provider_configuration = provider_configurations.get(provider)
  429. if not provider_configuration:
  430. raise ValueError(f"Provider {provider} does not exist.")
  431. # Enable model
  432. provider_configuration.disable_model(model=model, model_type=ModelType.value_of(model_type))
  433. def free_quota_submit(self, tenant_id: str, provider: str):
  434. api_key = os.environ.get("FREE_QUOTA_APPLY_API_KEY")
  435. api_base_url = os.environ.get("FREE_QUOTA_APPLY_BASE_URL")
  436. api_url = api_base_url + "/api/v1/providers/apply"
  437. headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
  438. response = requests.post(api_url, headers=headers, json={"workspace_id": tenant_id, "provider_name": provider})
  439. if not response.ok:
  440. logger.error(f"Request FREE QUOTA APPLY SERVER Error: {response.status_code} ")
  441. raise ValueError(f"Error: {response.status_code} ")
  442. if response.json()["code"] != "success":
  443. raise ValueError(f"error: {response.json()['message']}")
  444. rst = response.json()
  445. if rst["type"] == "redirect":
  446. return {"type": rst["type"], "redirect_url": rst["redirect_url"]}
  447. else:
  448. return {"type": rst["type"], "result": "success"}
  449. def free_quota_qualification_verify(self, tenant_id: str, provider: str, token: Optional[str]):
  450. api_key = os.environ.get("FREE_QUOTA_APPLY_API_KEY")
  451. api_base_url = os.environ.get("FREE_QUOTA_APPLY_BASE_URL")
  452. api_url = api_base_url + "/api/v1/providers/qualification-verify"
  453. headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
  454. json_data = {"workspace_id": tenant_id, "provider_name": provider}
  455. if token:
  456. json_data["token"] = token
  457. response = requests.post(api_url, headers=headers, json=json_data)
  458. if not response.ok:
  459. logger.error(f"Request FREE QUOTA APPLY SERVER Error: {response.status_code} ")
  460. raise ValueError(f"Error: {response.status_code} ")
  461. rst = response.json()
  462. if rst["code"] != "success":
  463. raise ValueError(f"error: {rst['message']}")
  464. data = rst["data"]
  465. if data["qualified"] is True:
  466. return {"result": "success", "provider_name": provider, "flag": True}
  467. else:
  468. return {"result": "success", "provider_name": provider, "flag": False, "reason": data["reason"]}