model_provider_service.py 22 KB

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