provider_manager.py 30 KB

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