provider_manager.py 30 KB

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