model_provider_service.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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 [ModelWithProviderEntityResponse(model) for model in provider_configurations.get_models(
  84. 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),
  164. model=model,
  165. obfuscated=True
  166. )
  167. def model_credentials_validate(self, tenant_id: str, provider: str, model_type: str, model: str,
  168. credentials: dict) -> 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),
  187. model=model,
  188. credentials=credentials
  189. )
  190. def save_model_credentials(self, tenant_id: str, provider: str, model_type: str, model: str,
  191. credentials: dict) -> None:
  192. """
  193. save model credentials.
  194. :param tenant_id: workspace id
  195. :param provider: provider name
  196. :param model_type: model type
  197. :param model: model name
  198. :param credentials: model credentials
  199. :return:
  200. """
  201. # Get all provider configurations of the current workspace
  202. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  203. # Get provider configuration
  204. provider_configuration = provider_configurations.get(provider)
  205. if not provider_configuration:
  206. raise ValueError(f"Provider {provider} does not exist.")
  207. # Add or update custom model credentials
  208. provider_configuration.add_or_update_custom_model_credentials(
  209. model_type=ModelType.value_of(model_type),
  210. model=model,
  211. credentials=credentials
  212. )
  213. def remove_model_credentials(self, tenant_id: str, provider: str, model_type: str, model: str) -> None:
  214. """
  215. remove model credentials.
  216. :param tenant_id: workspace id
  217. :param provider: provider name
  218. :param model_type: model type
  219. :param model: model name
  220. :return:
  221. """
  222. # Get all provider configurations of the current workspace
  223. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  224. # Get provider configuration
  225. provider_configuration = provider_configurations.get(provider)
  226. if not provider_configuration:
  227. raise ValueError(f"Provider {provider} does not exist.")
  228. # Remove custom model credentials
  229. provider_configuration.delete_custom_model_credentials(
  230. model_type=ModelType.value_of(model_type),
  231. model=model
  232. )
  233. def get_models_by_model_type(self, tenant_id: str, model_type: str) -> list[ProviderWithModelsResponse]:
  234. """
  235. get models by model type.
  236. :param tenant_id: workspace id
  237. :param model_type: model type
  238. :return:
  239. """
  240. # Get all provider configurations of the current workspace
  241. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  242. # Get provider available models
  243. models = provider_configurations.get_models(
  244. model_type=ModelType.value_of(model_type)
  245. )
  246. # Group models by provider
  247. provider_models = {}
  248. for model in models:
  249. if model.provider.provider not in provider_models:
  250. provider_models[model.provider.provider] = []
  251. if model.deprecated:
  252. continue
  253. if model.status != ModelStatus.ACTIVE:
  254. continue
  255. provider_models[model.provider.provider].append(model)
  256. # convert to ProviderWithModelsResponse list
  257. providers_with_models: list[ProviderWithModelsResponse] = []
  258. for provider, models in provider_models.items():
  259. if not models:
  260. continue
  261. first_model = models[0]
  262. providers_with_models.append(
  263. ProviderWithModelsResponse(
  264. provider=provider,
  265. label=first_model.provider.label,
  266. icon_small=first_model.provider.icon_small,
  267. icon_large=first_model.provider.icon_large,
  268. status=CustomConfigurationStatus.ACTIVE,
  269. models=[ProviderModelWithStatusEntity(
  270. model=model.model,
  271. label=model.label,
  272. model_type=model.model_type,
  273. features=model.features,
  274. fetch_from=model.fetch_from,
  275. model_properties=model.model_properties,
  276. status=model.status,
  277. load_balancing_enabled=model.load_balancing_enabled
  278. ) for model in models]
  279. )
  280. )
  281. return providers_with_models
  282. def get_model_parameter_rules(self, tenant_id: str, provider: str, model: str) -> list[ParameterRule]:
  283. """
  284. get model parameter rules.
  285. Only supports LLM.
  286. :param tenant_id: workspace id
  287. :param provider: provider name
  288. :param model: model name
  289. :return:
  290. """
  291. # Get all provider configurations of the current workspace
  292. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  293. # Get provider configuration
  294. provider_configuration = provider_configurations.get(provider)
  295. if not provider_configuration:
  296. raise ValueError(f"Provider {provider} does not exist.")
  297. # Get model instance of LLM
  298. model_type_instance = provider_configuration.get_model_type_instance(ModelType.LLM)
  299. model_type_instance = cast(LargeLanguageModel, model_type_instance)
  300. # fetch credentials
  301. credentials = provider_configuration.get_current_credentials(
  302. model_type=ModelType.LLM,
  303. model=model
  304. )
  305. if not credentials:
  306. return []
  307. # Call get_parameter_rules method of model instance to get model parameter rules
  308. return model_type_instance.get_parameter_rules(
  309. model=model,
  310. credentials=credentials
  311. )
  312. def get_default_model_of_model_type(self, tenant_id: str, model_type: str) -> Optional[DefaultModelResponse]:
  313. """
  314. get default model of model type.
  315. :param tenant_id: workspace id
  316. :param model_type: model type
  317. :return:
  318. """
  319. model_type_enum = ModelType.value_of(model_type)
  320. result = self.provider_manager.get_default_model(
  321. tenant_id=tenant_id,
  322. model_type=model_type_enum
  323. )
  324. return DefaultModelResponse(
  325. model=result.model,
  326. model_type=result.model_type,
  327. provider=SimpleProviderEntityResponse(
  328. provider=result.provider.provider,
  329. label=result.provider.label,
  330. icon_small=result.provider.icon_small,
  331. icon_large=result.provider.icon_large,
  332. supported_model_types=result.provider.supported_model_types
  333. )
  334. ) if result else None
  335. def update_default_model_of_model_type(self, tenant_id: str, model_type: str, provider: str, model: str) -> None:
  336. """
  337. update default model of model type.
  338. :param tenant_id: workspace id
  339. :param model_type: model type
  340. :param provider: provider name
  341. :param model: model name
  342. :return:
  343. """
  344. model_type_enum = ModelType.value_of(model_type)
  345. self.provider_manager.update_default_model_record(
  346. tenant_id=tenant_id,
  347. model_type=model_type_enum,
  348. provider=provider,
  349. model=model
  350. )
  351. def get_model_provider_icon(self, provider: str, icon_type: str, lang: str) -> tuple[Optional[bytes], Optional[str]]:
  352. """
  353. get model provider icon.
  354. :param provider: provider name
  355. :param icon_type: icon type (icon_small or icon_large)
  356. :param lang: language (zh_Hans or en_US)
  357. :return:
  358. """
  359. provider_instance = model_provider_factory.get_provider_instance(provider)
  360. provider_schema = provider_instance.get_provider_schema()
  361. if icon_type.lower() == 'icon_small':
  362. if not provider_schema.icon_small:
  363. raise ValueError(f"Provider {provider} does not have small icon.")
  364. if lang.lower() == 'zh_hans':
  365. file_name = provider_schema.icon_small.zh_Hans
  366. else:
  367. file_name = provider_schema.icon_small.en_US
  368. else:
  369. if not provider_schema.icon_large:
  370. raise ValueError(f"Provider {provider} does not have large icon.")
  371. if lang.lower() == 'zh_hans':
  372. file_name = provider_schema.icon_large.zh_Hans
  373. else:
  374. file_name = provider_schema.icon_large.en_US
  375. root_path = current_app.root_path
  376. provider_instance_path = os.path.dirname(os.path.join(root_path, provider_instance.__class__.__module__.replace('.', '/')))
  377. file_path = os.path.join(provider_instance_path, "_assets")
  378. file_path = os.path.join(file_path, file_name)
  379. if not os.path.exists(file_path):
  380. return None, None
  381. mimetype, _ = mimetypes.guess_type(file_path)
  382. mimetype = mimetype or 'application/octet-stream'
  383. # read binary from file
  384. with open(file_path, 'rb') as f:
  385. byte_data = f.read()
  386. return byte_data, mimetype
  387. def switch_preferred_provider(self, tenant_id: str, provider: str, preferred_provider_type: str) -> None:
  388. """
  389. switch preferred provider.
  390. :param tenant_id: workspace id
  391. :param provider: provider name
  392. :param preferred_provider_type: preferred provider type
  393. :return:
  394. """
  395. # Get all provider configurations of the current workspace
  396. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  397. # Convert preferred_provider_type to ProviderType
  398. preferred_provider_type_enum = ProviderType.value_of(preferred_provider_type)
  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. # Switch preferred provider type
  404. provider_configuration.switch_preferred_provider_type(preferred_provider_type_enum)
  405. def enable_model(self, tenant_id: str, provider: str, model: str, model_type: str) -> None:
  406. """
  407. enable model.
  408. :param tenant_id: workspace id
  409. :param provider: provider name
  410. :param model: model name
  411. :param model_type: model type
  412. :return:
  413. """
  414. # Get all provider configurations of the current workspace
  415. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  416. # Get provider configuration
  417. provider_configuration = provider_configurations.get(provider)
  418. if not provider_configuration:
  419. raise ValueError(f"Provider {provider} does not exist.")
  420. # Enable model
  421. provider_configuration.enable_model(
  422. model=model,
  423. model_type=ModelType.value_of(model_type)
  424. )
  425. def disable_model(self, tenant_id: str, provider: str, model: str, model_type: str) -> None:
  426. """
  427. disable model.
  428. :param tenant_id: workspace id
  429. :param provider: provider name
  430. :param model: model name
  431. :param model_type: model type
  432. :return:
  433. """
  434. # Get all provider configurations of the current workspace
  435. provider_configurations = self.provider_manager.get_configurations(tenant_id)
  436. # Get provider configuration
  437. provider_configuration = provider_configurations.get(provider)
  438. if not provider_configuration:
  439. raise ValueError(f"Provider {provider} does not exist.")
  440. # Enable model
  441. provider_configuration.disable_model(
  442. model=model,
  443. model_type=ModelType.value_of(model_type)
  444. )
  445. def free_quota_submit(self, tenant_id: str, provider: str):
  446. api_key = os.environ.get("FREE_QUOTA_APPLY_API_KEY")
  447. api_base_url = os.environ.get("FREE_QUOTA_APPLY_BASE_URL")
  448. api_url = api_base_url + '/api/v1/providers/apply'
  449. headers = {
  450. 'Content-Type': 'application/json',
  451. 'Authorization': f"Bearer {api_key}"
  452. }
  453. response = requests.post(api_url, headers=headers, json={'workspace_id': tenant_id, 'provider_name': provider})
  454. if not response.ok:
  455. logger.error(f"Request FREE QUOTA APPLY SERVER Error: {response.status_code} ")
  456. raise ValueError(f"Error: {response.status_code} ")
  457. if response.json()["code"] != 'success':
  458. raise ValueError(
  459. f"error: {response.json()['message']}"
  460. )
  461. rst = response.json()
  462. if rst['type'] == 'redirect':
  463. return {
  464. 'type': rst['type'],
  465. 'redirect_url': rst['redirect_url']
  466. }
  467. else:
  468. return {
  469. 'type': rst['type'],
  470. 'result': 'success'
  471. }
  472. def free_quota_qualification_verify(self, tenant_id: str, provider: str, token: Optional[str]):
  473. api_key = os.environ.get("FREE_QUOTA_APPLY_API_KEY")
  474. api_base_url = os.environ.get("FREE_QUOTA_APPLY_BASE_URL")
  475. api_url = api_base_url + '/api/v1/providers/qualification-verify'
  476. headers = {
  477. 'Content-Type': 'application/json',
  478. 'Authorization': f"Bearer {api_key}"
  479. }
  480. json_data = {'workspace_id': tenant_id, 'provider_name': provider}
  481. if token:
  482. json_data['token'] = token
  483. response = requests.post(api_url, headers=headers,
  484. json=json_data)
  485. if not response.ok:
  486. logger.error(f"Request FREE QUOTA APPLY SERVER Error: {response.status_code} ")
  487. raise ValueError(f"Error: {response.status_code} ")
  488. rst = response.json()
  489. if rst["code"] != 'success':
  490. raise ValueError(
  491. f"error: {rst['message']}"
  492. )
  493. data = rst['data']
  494. if data['qualified'] is True:
  495. return {
  496. 'result': 'success',
  497. 'provider_name': provider,
  498. 'flag': True
  499. }
  500. else:
  501. return {
  502. 'result': 'success',
  503. 'provider_name': provider,
  504. 'flag': False,
  505. 'reason': data['reason']
  506. }