provider_manager.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. import json
  2. from collections import defaultdict
  3. from json import JSONDecodeError
  4. from typing import Optional
  5. from sqlalchemy.exc import IntegrityError
  6. from core.entities.model_entities import DefaultModelEntity, DefaultModelProviderEntity
  7. from core.entities.provider_configuration import ProviderConfiguration, ProviderConfigurations, ProviderModelBundle
  8. from core.entities.provider_entities import (
  9. CustomConfiguration,
  10. CustomModelConfiguration,
  11. CustomProviderConfiguration,
  12. QuotaConfiguration,
  13. SystemConfiguration,
  14. )
  15. from core.helper import encrypter
  16. from core.helper.model_provider_cache import ProviderCredentialsCache, ProviderCredentialsCacheType
  17. from core.model_runtime.entities.model_entities import ModelType
  18. from core.model_runtime.entities.provider_entities import (
  19. CredentialFormSchema,
  20. FormType,
  21. ProviderEntity,
  22. )
  23. from core.model_runtime.model_providers import model_provider_factory
  24. from extensions import ext_hosting_provider
  25. from extensions.ext_database import db
  26. from models.provider import (
  27. Provider,
  28. ProviderModel,
  29. ProviderQuotaType,
  30. ProviderType,
  31. TenantDefaultModel,
  32. TenantPreferredModelProvider,
  33. )
  34. class ProviderManager:
  35. """
  36. ProviderManager is a class that manages the model providers includes Hosting and Customize Model Providers.
  37. """
  38. def __init__(self) -> None:
  39. self.decoding_rsa_key = None
  40. self.decoding_cipher_rsa = None
  41. def get_configurations(self, tenant_id: str) -> ProviderConfigurations:
  42. """
  43. Get model provider configurations.
  44. Construct ProviderConfiguration objects for each provider
  45. Including:
  46. 1. Basic information of the provider
  47. 2. Hosting configuration information, including:
  48. (1. Whether to enable (support) hosting type, if enabled, the following information exists
  49. (2. List of hosting type provider configurations
  50. (including quota type, quota limit, current remaining quota, etc.)
  51. (3. The current hosting type in use (whether there is a quota or not)
  52. paid quotas > provider free quotas > hosting trial quotas
  53. (4. Unified credentials for hosting providers
  54. 3. Custom configuration information, including:
  55. (1. Whether to enable (support) custom type, if enabled, the following information exists
  56. (2. Custom provider configuration (including credentials)
  57. (3. List of custom provider model configurations (including credentials)
  58. 4. Hosting/custom preferred provider type.
  59. Provide methods:
  60. - Get the current configuration (including credentials)
  61. - Get the availability and status of the hosting configuration: active available,
  62. quota_exceeded insufficient quota, unsupported hosting
  63. - Get the availability of custom configuration
  64. Custom provider available conditions:
  65. (1. custom provider credentials available
  66. (2. at least one custom model credentials available
  67. - Verify, update, and delete custom provider configuration
  68. - Verify, update, and delete custom provider model configuration
  69. - Get the list of available models (optional provider filtering, model type filtering)
  70. Append custom provider models to the list
  71. - Get provider instance
  72. - Switch selection priority
  73. :param tenant_id:
  74. :return:
  75. """
  76. # Get all provider records of the workspace
  77. provider_name_to_provider_records_dict = self._get_all_providers(tenant_id)
  78. # Initialize trial provider records if not exist
  79. provider_name_to_provider_records_dict = self._init_trial_provider_records(
  80. tenant_id,
  81. provider_name_to_provider_records_dict
  82. )
  83. # Get all provider model records of the workspace
  84. provider_name_to_provider_model_records_dict = self._get_all_provider_models(tenant_id)
  85. # Get all provider entities
  86. provider_entities = model_provider_factory.get_providers()
  87. # Get All preferred provider types of the workspace
  88. provider_name_to_preferred_model_provider_records_dict = self._get_all_preferred_model_providers(tenant_id)
  89. provider_configurations = ProviderConfigurations(
  90. tenant_id=tenant_id
  91. )
  92. # Construct ProviderConfiguration objects for each provider
  93. for provider_entity in provider_entities:
  94. provider_name = provider_entity.provider
  95. provider_records = provider_name_to_provider_records_dict.get(provider_entity.provider, [])
  96. provider_model_records = provider_name_to_provider_model_records_dict.get(provider_entity.provider, [])
  97. # Convert to custom configuration
  98. custom_configuration = self._to_custom_configuration(
  99. tenant_id,
  100. provider_entity,
  101. provider_records,
  102. provider_model_records
  103. )
  104. # Convert to system configuration
  105. system_configuration = self._to_system_configuration(
  106. tenant_id,
  107. provider_entity,
  108. provider_records
  109. )
  110. # Get preferred provider type
  111. preferred_provider_type_record = provider_name_to_preferred_model_provider_records_dict.get(provider_name)
  112. if preferred_provider_type_record:
  113. preferred_provider_type = ProviderType.value_of(preferred_provider_type_record.preferred_provider_type)
  114. elif custom_configuration.provider or custom_configuration.models:
  115. preferred_provider_type = ProviderType.CUSTOM
  116. elif system_configuration.enabled:
  117. preferred_provider_type = ProviderType.SYSTEM
  118. else:
  119. preferred_provider_type = ProviderType.CUSTOM
  120. using_provider_type = preferred_provider_type
  121. has_valid_quota = any(quota_conf.is_valid for quota_conf in system_configuration.quota_configurations)
  122. if preferred_provider_type == ProviderType.SYSTEM:
  123. if not system_configuration.enabled or not has_valid_quota:
  124. using_provider_type = ProviderType.CUSTOM
  125. else:
  126. if not custom_configuration.provider and not custom_configuration.models:
  127. if system_configuration.enabled and has_valid_quota:
  128. using_provider_type = ProviderType.SYSTEM
  129. provider_configuration = ProviderConfiguration(
  130. tenant_id=tenant_id,
  131. provider=provider_entity,
  132. preferred_provider_type=preferred_provider_type,
  133. using_provider_type=using_provider_type,
  134. system_configuration=system_configuration,
  135. custom_configuration=custom_configuration
  136. )
  137. provider_configurations[provider_name] = provider_configuration
  138. # Return the encapsulated object
  139. return provider_configurations
  140. def get_provider_model_bundle(self, tenant_id: str, provider: str, model_type: ModelType) -> ProviderModelBundle:
  141. """
  142. Get provider model bundle.
  143. :param tenant_id: workspace id
  144. :param provider: provider name
  145. :param model_type: model type
  146. :return:
  147. """
  148. provider_configurations = self.get_configurations(tenant_id)
  149. # get provider instance
  150. provider_configuration = provider_configurations.get(provider)
  151. if not provider_configuration:
  152. raise ValueError(f"Provider {provider} does not exist.")
  153. provider_instance = provider_configuration.get_provider_instance()
  154. model_type_instance = provider_instance.get_model_instance(model_type)
  155. return ProviderModelBundle(
  156. configuration=provider_configuration,
  157. provider_instance=provider_instance,
  158. model_type_instance=model_type_instance
  159. )
  160. def get_default_model(self, tenant_id: str, model_type: ModelType) -> Optional[DefaultModelEntity]:
  161. """
  162. Get default model.
  163. :param tenant_id: workspace id
  164. :param model_type: model type
  165. :return:
  166. """
  167. # Get the corresponding TenantDefaultModel record
  168. default_model = db.session.query(TenantDefaultModel) \
  169. .filter(
  170. TenantDefaultModel.tenant_id == tenant_id,
  171. TenantDefaultModel.model_type == model_type.to_origin_model_type()
  172. ).first()
  173. # If it does not exist, get the first available provider model from get_configurations
  174. # and update the TenantDefaultModel record
  175. if not default_model:
  176. # Get provider configurations
  177. provider_configurations = self.get_configurations(tenant_id)
  178. # get available models from provider_configurations
  179. available_models = provider_configurations.get_models(
  180. model_type=model_type,
  181. only_active=True
  182. )
  183. if available_models:
  184. available_model = next((model for model in available_models if model.model == "gpt-4"),
  185. available_models[0])
  186. default_model = TenantDefaultModel(
  187. tenant_id=tenant_id,
  188. model_type=model_type.to_origin_model_type(),
  189. provider_name=available_model.provider.provider,
  190. model_name=available_model.model
  191. )
  192. db.session.add(default_model)
  193. db.session.commit()
  194. if not default_model:
  195. return None
  196. provider_instance = model_provider_factory.get_provider_instance(default_model.provider_name)
  197. provider_schema = provider_instance.get_provider_schema()
  198. return DefaultModelEntity(
  199. model=default_model.model_name,
  200. model_type=model_type,
  201. provider=DefaultModelProviderEntity(
  202. provider=provider_schema.provider,
  203. label=provider_schema.label,
  204. icon_small=provider_schema.icon_small,
  205. icon_large=provider_schema.icon_large,
  206. supported_model_types=provider_schema.supported_model_types
  207. )
  208. )
  209. def update_default_model_record(self, tenant_id: str, model_type: ModelType, provider: str, model: str) \
  210. -> TenantDefaultModel:
  211. """
  212. Update default model record.
  213. :param tenant_id: workspace id
  214. :param model_type: model type
  215. :param provider: provider name
  216. :param model: model name
  217. :return:
  218. """
  219. provider_configurations = self.get_configurations(tenant_id)
  220. if provider not in provider_configurations:
  221. raise ValueError(f"Provider {provider} does not exist.")
  222. # get available models from provider_configurations
  223. available_models = provider_configurations.get_models(
  224. model_type=model_type,
  225. only_active=True
  226. )
  227. # check if the model is exist in available models
  228. model_names = [model.model for model in available_models]
  229. if model not in model_names:
  230. raise ValueError(f"Model {model} does not exist.")
  231. # Get the list of available models from get_configurations and check if it is LLM
  232. default_model = db.session.query(TenantDefaultModel) \
  233. .filter(
  234. TenantDefaultModel.tenant_id == tenant_id,
  235. TenantDefaultModel.model_type == model_type.to_origin_model_type()
  236. ).first()
  237. # create or update TenantDefaultModel record
  238. if default_model:
  239. # update default model
  240. default_model.provider_name = provider
  241. default_model.model_name = model
  242. db.session.commit()
  243. else:
  244. # create default model
  245. default_model = TenantDefaultModel(
  246. tenant_id=tenant_id,
  247. model_type=model_type.value,
  248. provider_name=provider,
  249. model_name=model,
  250. )
  251. db.session.add(default_model)
  252. db.session.commit()
  253. return default_model
  254. def _get_all_providers(self, tenant_id: str) -> dict[str, list[Provider]]:
  255. """
  256. Get all provider records of the workspace.
  257. :param tenant_id: workspace id
  258. :return:
  259. """
  260. providers = db.session.query(Provider) \
  261. .filter(
  262. Provider.tenant_id == tenant_id,
  263. Provider.is_valid == True
  264. ).all()
  265. provider_name_to_provider_records_dict = defaultdict(list)
  266. for provider in providers:
  267. provider_name_to_provider_records_dict[provider.provider_name].append(provider)
  268. return provider_name_to_provider_records_dict
  269. def _get_all_provider_models(self, tenant_id: str) -> dict[str, list[ProviderModel]]:
  270. """
  271. Get all provider model records of the workspace.
  272. :param tenant_id: workspace id
  273. :return:
  274. """
  275. # Get all provider model records of the workspace
  276. provider_models = db.session.query(ProviderModel) \
  277. .filter(
  278. ProviderModel.tenant_id == tenant_id,
  279. ProviderModel.is_valid == True
  280. ).all()
  281. provider_name_to_provider_model_records_dict = defaultdict(list)
  282. for provider_model in provider_models:
  283. provider_name_to_provider_model_records_dict[provider_model.provider_name].append(provider_model)
  284. return provider_name_to_provider_model_records_dict
  285. def _get_all_preferred_model_providers(self, tenant_id: str) -> dict[str, TenantPreferredModelProvider]:
  286. """
  287. Get All preferred provider types of the workspace.
  288. :param tenant_id:
  289. :return:
  290. """
  291. preferred_provider_types = db.session.query(TenantPreferredModelProvider) \
  292. .filter(
  293. TenantPreferredModelProvider.tenant_id == tenant_id
  294. ).all()
  295. provider_name_to_preferred_provider_type_records_dict = {
  296. preferred_provider_type.provider_name: preferred_provider_type
  297. for preferred_provider_type in preferred_provider_types
  298. }
  299. return provider_name_to_preferred_provider_type_records_dict
  300. def _init_trial_provider_records(self, tenant_id: str,
  301. provider_name_to_provider_records_dict: dict[str, list]) -> dict[str, list]:
  302. """
  303. Initialize trial provider records if not exists.
  304. :param tenant_id: workspace id
  305. :param provider_name_to_provider_records_dict: provider name to provider records dict
  306. :return:
  307. """
  308. # Get hosting configuration
  309. hosting_configuration = ext_hosting_provider.hosting_configuration
  310. for provider_name, configuration in hosting_configuration.provider_map.items():
  311. if not configuration.enabled:
  312. continue
  313. provider_records = provider_name_to_provider_records_dict.get(provider_name)
  314. if not provider_records:
  315. provider_records = []
  316. provider_quota_to_provider_record_dict = dict()
  317. for provider_record in provider_records:
  318. if provider_record.provider_type != ProviderType.SYSTEM.value:
  319. continue
  320. provider_quota_to_provider_record_dict[ProviderQuotaType.value_of(provider_record.quota_type)] \
  321. = provider_record
  322. for quota in configuration.quotas:
  323. if quota.quota_type == ProviderQuotaType.TRIAL:
  324. # Init trial provider records if not exists
  325. if ProviderQuotaType.TRIAL not in provider_quota_to_provider_record_dict:
  326. try:
  327. provider_record = Provider(
  328. tenant_id=tenant_id,
  329. provider_name=provider_name,
  330. provider_type=ProviderType.SYSTEM.value,
  331. quota_type=ProviderQuotaType.TRIAL.value,
  332. quota_limit=quota.quota_limit,
  333. quota_used=0,
  334. is_valid=True
  335. )
  336. db.session.add(provider_record)
  337. db.session.commit()
  338. except IntegrityError:
  339. db.session.rollback()
  340. provider_record = db.session.query(Provider) \
  341. .filter(
  342. Provider.tenant_id == tenant_id,
  343. Provider.provider_name == provider_name,
  344. Provider.provider_type == ProviderType.SYSTEM.value,
  345. Provider.quota_type == ProviderQuotaType.TRIAL.value
  346. ).first()
  347. if provider_record and not provider_record.is_valid:
  348. provider_record.is_valid = True
  349. db.session.commit()
  350. provider_name_to_provider_records_dict[provider_name].append(provider_record)
  351. return provider_name_to_provider_records_dict
  352. def _to_custom_configuration(self,
  353. tenant_id: str,
  354. provider_entity: ProviderEntity,
  355. provider_records: list[Provider],
  356. provider_model_records: list[ProviderModel]) -> CustomConfiguration:
  357. """
  358. Convert to custom configuration.
  359. :param tenant_id: workspace id
  360. :param provider_entity: provider entity
  361. :param provider_records: provider records
  362. :param provider_model_records: provider model records
  363. :return:
  364. """
  365. # Get provider credential secret variables
  366. provider_credential_secret_variables = self._extract_secret_variables(
  367. provider_entity.provider_credential_schema.credential_form_schemas
  368. if provider_entity.provider_credential_schema else []
  369. )
  370. # Get custom provider record
  371. custom_provider_record = None
  372. for provider_record in provider_records:
  373. if provider_record.provider_type == ProviderType.SYSTEM.value:
  374. continue
  375. if not provider_record.encrypted_config:
  376. continue
  377. custom_provider_record = provider_record
  378. # Get custom provider credentials
  379. custom_provider_configuration = None
  380. if custom_provider_record:
  381. provider_credentials_cache = ProviderCredentialsCache(
  382. tenant_id=tenant_id,
  383. identity_id=custom_provider_record.id,
  384. cache_type=ProviderCredentialsCacheType.PROVIDER
  385. )
  386. # Get cached provider credentials
  387. cached_provider_credentials = provider_credentials_cache.get()
  388. if not cached_provider_credentials:
  389. try:
  390. # fix origin data
  391. if (custom_provider_record.encrypted_config
  392. and not custom_provider_record.encrypted_config.startswith("{")):
  393. provider_credentials = {
  394. "openai_api_key": custom_provider_record.encrypted_config
  395. }
  396. else:
  397. provider_credentials = json.loads(custom_provider_record.encrypted_config)
  398. except JSONDecodeError:
  399. provider_credentials = {}
  400. # Get decoding rsa key and cipher for decrypting credentials
  401. if self.decoding_rsa_key is None or self.decoding_cipher_rsa is None:
  402. self.decoding_rsa_key, self.decoding_cipher_rsa = encrypter.get_decrypt_decoding(tenant_id)
  403. for variable in provider_credential_secret_variables:
  404. if variable in provider_credentials:
  405. try:
  406. provider_credentials[variable] = encrypter.decrypt_token_with_decoding(
  407. provider_credentials.get(variable),
  408. self.decoding_rsa_key,
  409. self.decoding_cipher_rsa
  410. )
  411. except ValueError:
  412. pass
  413. # cache provider credentials
  414. provider_credentials_cache.set(
  415. credentials=provider_credentials
  416. )
  417. else:
  418. provider_credentials = cached_provider_credentials
  419. custom_provider_configuration = CustomProviderConfiguration(
  420. credentials=provider_credentials
  421. )
  422. # Get provider model credential secret variables
  423. model_credential_secret_variables = self._extract_secret_variables(
  424. provider_entity.model_credential_schema.credential_form_schemas
  425. if provider_entity.model_credential_schema else []
  426. )
  427. # Get custom provider model credentials
  428. custom_model_configurations = []
  429. for provider_model_record in provider_model_records:
  430. if not provider_model_record.encrypted_config:
  431. continue
  432. provider_model_credentials_cache = ProviderCredentialsCache(
  433. tenant_id=tenant_id,
  434. identity_id=provider_model_record.id,
  435. cache_type=ProviderCredentialsCacheType.MODEL
  436. )
  437. # Get cached provider model credentials
  438. cached_provider_model_credentials = provider_model_credentials_cache.get()
  439. if not cached_provider_model_credentials:
  440. try:
  441. provider_model_credentials = json.loads(provider_model_record.encrypted_config)
  442. except JSONDecodeError:
  443. continue
  444. # Get decoding rsa key and cipher for decrypting credentials
  445. if self.decoding_rsa_key is None or self.decoding_cipher_rsa is None:
  446. self.decoding_rsa_key, self.decoding_cipher_rsa = encrypter.get_decrypt_decoding(tenant_id)
  447. for variable in model_credential_secret_variables:
  448. if variable in provider_model_credentials:
  449. try:
  450. provider_model_credentials[variable] = encrypter.decrypt_token_with_decoding(
  451. provider_model_credentials.get(variable),
  452. self.decoding_rsa_key,
  453. self.decoding_cipher_rsa
  454. )
  455. except ValueError:
  456. pass
  457. # cache provider model credentials
  458. provider_model_credentials_cache.set(
  459. credentials=provider_model_credentials
  460. )
  461. else:
  462. provider_model_credentials = cached_provider_model_credentials
  463. custom_model_configurations.append(
  464. CustomModelConfiguration(
  465. model=provider_model_record.model_name,
  466. model_type=ModelType.value_of(provider_model_record.model_type),
  467. credentials=provider_model_credentials
  468. )
  469. )
  470. return CustomConfiguration(
  471. provider=custom_provider_configuration,
  472. models=custom_model_configurations
  473. )
  474. def _to_system_configuration(self,
  475. tenant_id: str,
  476. provider_entity: ProviderEntity,
  477. provider_records: list[Provider]) -> SystemConfiguration:
  478. """
  479. Convert to system configuration.
  480. :param tenant_id: workspace id
  481. :param provider_entity: provider entity
  482. :param provider_records: provider records
  483. :return:
  484. """
  485. # Get hosting configuration
  486. hosting_configuration = ext_hosting_provider.hosting_configuration
  487. if provider_entity.provider not in hosting_configuration.provider_map \
  488. or not hosting_configuration.provider_map.get(provider_entity.provider).enabled:
  489. return SystemConfiguration(
  490. enabled=False
  491. )
  492. provider_hosting_configuration = hosting_configuration.provider_map.get(provider_entity.provider)
  493. # Convert provider_records to dict
  494. quota_type_to_provider_records_dict = dict()
  495. for provider_record in provider_records:
  496. if provider_record.provider_type != ProviderType.SYSTEM.value:
  497. continue
  498. quota_type_to_provider_records_dict[ProviderQuotaType.value_of(provider_record.quota_type)] \
  499. = provider_record
  500. quota_configurations = []
  501. for provider_quota in provider_hosting_configuration.quotas:
  502. if provider_quota.quota_type not in quota_type_to_provider_records_dict:
  503. if provider_quota.quota_type == ProviderQuotaType.FREE:
  504. quota_configuration = QuotaConfiguration(
  505. quota_type=provider_quota.quota_type,
  506. quota_unit=provider_hosting_configuration.quota_unit,
  507. quota_used=0,
  508. quota_limit=0,
  509. is_valid=False,
  510. restrict_models=provider_quota.restrict_models
  511. )
  512. else:
  513. continue
  514. else:
  515. provider_record = quota_type_to_provider_records_dict[provider_quota.quota_type]
  516. quota_configuration = QuotaConfiguration(
  517. quota_type=provider_quota.quota_type,
  518. quota_unit=provider_hosting_configuration.quota_unit,
  519. quota_used=provider_record.quota_used,
  520. quota_limit=provider_record.quota_limit,
  521. is_valid=provider_record.quota_limit > provider_record.quota_used or provider_record.quota_limit == -1,
  522. restrict_models=provider_quota.restrict_models
  523. )
  524. quota_configurations.append(quota_configuration)
  525. if len(quota_configurations) == 0:
  526. return SystemConfiguration(
  527. enabled=False
  528. )
  529. current_quota_type = self._choice_current_using_quota_type(quota_configurations)
  530. current_using_credentials = provider_hosting_configuration.credentials
  531. if current_quota_type == ProviderQuotaType.FREE:
  532. provider_record = quota_type_to_provider_records_dict.get(current_quota_type)
  533. if provider_record:
  534. provider_credentials_cache = ProviderCredentialsCache(
  535. tenant_id=tenant_id,
  536. identity_id=provider_record.id,
  537. cache_type=ProviderCredentialsCacheType.PROVIDER
  538. )
  539. # Get cached provider credentials
  540. cached_provider_credentials = provider_credentials_cache.get()
  541. if not cached_provider_credentials:
  542. try:
  543. provider_credentials = json.loads(provider_record.encrypted_config)
  544. except JSONDecodeError:
  545. provider_credentials = {}
  546. # Get provider credential secret variables
  547. provider_credential_secret_variables = self._extract_secret_variables(
  548. provider_entity.provider_credential_schema.credential_form_schemas
  549. if provider_entity.provider_credential_schema else []
  550. )
  551. # Get decoding rsa key and cipher for decrypting credentials
  552. if self.decoding_rsa_key is None or self.decoding_cipher_rsa is None:
  553. self.decoding_rsa_key, self.decoding_cipher_rsa = encrypter.get_decrypt_decoding(tenant_id)
  554. for variable in provider_credential_secret_variables:
  555. if variable in provider_credentials:
  556. try:
  557. provider_credentials[variable] = encrypter.decrypt_token_with_decoding(
  558. provider_credentials.get(variable),
  559. self.decoding_rsa_key,
  560. self.decoding_cipher_rsa
  561. )
  562. except ValueError:
  563. pass
  564. current_using_credentials = provider_credentials
  565. # cache provider credentials
  566. provider_credentials_cache.set(
  567. credentials=current_using_credentials
  568. )
  569. else:
  570. current_using_credentials = cached_provider_credentials
  571. else:
  572. current_using_credentials = {}
  573. quota_configurations = []
  574. return SystemConfiguration(
  575. enabled=True,
  576. current_quota_type=current_quota_type,
  577. quota_configurations=quota_configurations,
  578. credentials=current_using_credentials
  579. )
  580. def _choice_current_using_quota_type(self, quota_configurations: list[QuotaConfiguration]) -> ProviderQuotaType:
  581. """
  582. Choice current using quota type.
  583. paid quotas > provider free quotas > hosting trial quotas
  584. If there is still quota for the corresponding quota type according to the sorting,
  585. :param quota_configurations:
  586. :return:
  587. """
  588. # convert to dict
  589. quota_type_to_quota_configuration_dict = {
  590. quota_configuration.quota_type: quota_configuration
  591. for quota_configuration in quota_configurations
  592. }
  593. last_quota_configuration = None
  594. for quota_type in [ProviderQuotaType.PAID, ProviderQuotaType.FREE, ProviderQuotaType.TRIAL]:
  595. if quota_type in quota_type_to_quota_configuration_dict:
  596. last_quota_configuration = quota_type_to_quota_configuration_dict[quota_type]
  597. if last_quota_configuration.is_valid:
  598. return quota_type
  599. if last_quota_configuration:
  600. return last_quota_configuration.quota_type
  601. raise ValueError('No quota type available')
  602. def _extract_secret_variables(self, credential_form_schemas: list[CredentialFormSchema]) -> list[str]:
  603. """
  604. Extract secret input form variables.
  605. :param credential_form_schemas:
  606. :return:
  607. """
  608. secret_input_form_variables = []
  609. for credential_form_schema in credential_form_schemas:
  610. if credential_form_schema.type == FormType.SECRET_INPUT:
  611. secret_input_form_variables.append(credential_form_schema.variable)
  612. return secret_input_form_variables