provider_manager.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. import json
  2. from collections import defaultdict
  3. from json import JSONDecodeError
  4. from typing import Any, Optional, cast
  5. from sqlalchemy.exc import IntegrityError
  6. from configs import dify_config
  7. from core.entities.model_entities import DefaultModelEntity, DefaultModelProviderEntity
  8. from core.entities.provider_configuration import ProviderConfiguration, ProviderConfigurations, ProviderModelBundle
  9. from core.entities.provider_entities import (
  10. CustomConfiguration,
  11. CustomModelConfiguration,
  12. CustomProviderConfiguration,
  13. ModelLoadBalancingConfiguration,
  14. ModelSettings,
  15. ProviderQuotaType,
  16. QuotaConfiguration,
  17. QuotaUnit,
  18. SystemConfiguration,
  19. )
  20. from core.helper import encrypter
  21. from core.helper.model_provider_cache import ProviderCredentialsCache, ProviderCredentialsCacheType
  22. from core.helper.position_helper import is_filtered
  23. from core.model_runtime.entities.model_entities import ModelType
  24. from core.model_runtime.entities.provider_entities import (
  25. ConfigurateMethod,
  26. CredentialFormSchema,
  27. FormType,
  28. ProviderEntity,
  29. )
  30. from core.model_runtime.model_providers.model_provider_factory import ModelProviderFactory
  31. from core.plugin.entities.plugin import ModelProviderID
  32. from extensions import ext_hosting_provider
  33. from extensions.ext_database import db
  34. from extensions.ext_redis import redis_client
  35. from models.provider import (
  36. LoadBalancingModelConfig,
  37. Provider,
  38. ProviderModel,
  39. ProviderModelSetting,
  40. ProviderType,
  41. TenantDefaultModel,
  42. TenantPreferredModelProvider,
  43. )
  44. from services.feature_service import FeatureService
  45. class ProviderManager:
  46. """
  47. ProviderManager is a class that manages the model providers includes Hosting and Customize Model Providers.
  48. """
  49. def __init__(self) -> None:
  50. self.decoding_rsa_key = None
  51. self.decoding_cipher_rsa = None
  52. def get_configurations(self, tenant_id: str) -> ProviderConfigurations:
  53. """
  54. Get model provider configurations.
  55. Construct ProviderConfiguration objects for each provider
  56. Including:
  57. 1. Basic information of the provider
  58. 2. Hosting configuration information, including:
  59. (1. Whether to enable (support) hosting type, if enabled, the following information exists
  60. (2. List of hosting type provider configurations
  61. (including quota type, quota limit, current remaining quota, etc.)
  62. (3. The current hosting type in use (whether there is a quota or not)
  63. paid quotas > provider free quotas > hosting trial quotas
  64. (4. Unified credentials for hosting providers
  65. 3. Custom configuration information, including:
  66. (1. Whether to enable (support) custom type, if enabled, the following information exists
  67. (2. Custom provider configuration (including credentials)
  68. (3. List of custom provider model configurations (including credentials)
  69. 4. Hosting/custom preferred provider type.
  70. Provide methods:
  71. - Get the current configuration (including credentials)
  72. - Get the availability and status of the hosting configuration: active available,
  73. quota_exceeded insufficient quota, unsupported hosting
  74. - Get the availability of custom configuration
  75. Custom provider available conditions:
  76. (1. custom provider credentials available
  77. (2. at least one custom model credentials available
  78. - Verify, update, and delete custom provider configuration
  79. - Verify, update, and delete custom provider model configuration
  80. - Get the list of available models (optional provider filtering, model type filtering)
  81. Append custom provider models to the list
  82. - Get provider instance
  83. - Switch selection priority
  84. :param tenant_id:
  85. :return:
  86. """
  87. # Get all provider records of the workspace
  88. provider_name_to_provider_records_dict = self._get_all_providers(tenant_id)
  89. # Initialize trial provider records if not exist
  90. provider_name_to_provider_records_dict = self._init_trial_provider_records(
  91. tenant_id, provider_name_to_provider_records_dict
  92. )
  93. # append providers with langgenius/openai/openai
  94. provider_name_list = list(provider_name_to_provider_records_dict.keys())
  95. for provider_name in provider_name_list:
  96. provider_id = ModelProviderID(provider_name)
  97. if str(provider_id) not in provider_name_list:
  98. provider_name_to_provider_records_dict[str(provider_id)] = provider_name_to_provider_records_dict[
  99. provider_name
  100. ]
  101. # Get all provider model records of the workspace
  102. provider_name_to_provider_model_records_dict = self._get_all_provider_models(tenant_id)
  103. for provider_name in list(provider_name_to_provider_model_records_dict.keys()):
  104. provider_id = ModelProviderID(provider_name)
  105. if str(provider_id) not in provider_name_to_provider_model_records_dict:
  106. provider_name_to_provider_model_records_dict[str(provider_id)] = (
  107. provider_name_to_provider_model_records_dict[provider_name]
  108. )
  109. # Get all provider entities
  110. model_provider_factory = ModelProviderFactory(tenant_id)
  111. provider_entities = model_provider_factory.get_providers()
  112. # Get All preferred provider types of the workspace
  113. provider_name_to_preferred_model_provider_records_dict = self._get_all_preferred_model_providers(tenant_id)
  114. # Get All provider model settings
  115. provider_name_to_provider_model_settings_dict = self._get_all_provider_model_settings(tenant_id)
  116. # Get All load balancing configs
  117. provider_name_to_provider_load_balancing_model_configs_dict = self._get_all_provider_load_balancing_configs(
  118. tenant_id
  119. )
  120. provider_configurations = ProviderConfigurations(tenant_id=tenant_id)
  121. # Construct ProviderConfiguration objects for each provider
  122. for provider_entity in provider_entities:
  123. # handle include, exclude
  124. if is_filtered(
  125. include_set=cast(set[str], dify_config.POSITION_PROVIDER_INCLUDES_SET),
  126. exclude_set=cast(set[str], dify_config.POSITION_PROVIDER_EXCLUDES_SET),
  127. data=provider_entity,
  128. name_func=lambda x: x.provider,
  129. ):
  130. continue
  131. provider_name = provider_entity.provider
  132. provider_records = provider_name_to_provider_records_dict.get(provider_entity.provider, [])
  133. provider_model_records = provider_name_to_provider_model_records_dict.get(provider_entity.provider, [])
  134. # Convert to custom configuration
  135. custom_configuration = self._to_custom_configuration(
  136. tenant_id, provider_entity, provider_records, provider_model_records
  137. )
  138. # Convert to system configuration
  139. system_configuration = self._to_system_configuration(tenant_id, provider_entity, provider_records)
  140. # Get preferred provider type
  141. preferred_provider_type_record = provider_name_to_preferred_model_provider_records_dict.get(provider_name)
  142. if preferred_provider_type_record:
  143. preferred_provider_type = ProviderType.value_of(preferred_provider_type_record.preferred_provider_type)
  144. elif custom_configuration.provider or custom_configuration.models:
  145. preferred_provider_type = ProviderType.CUSTOM
  146. elif system_configuration.enabled:
  147. preferred_provider_type = ProviderType.SYSTEM
  148. else:
  149. preferred_provider_type = ProviderType.CUSTOM
  150. using_provider_type = preferred_provider_type
  151. has_valid_quota = any(quota_conf.is_valid for quota_conf in system_configuration.quota_configurations)
  152. if preferred_provider_type == ProviderType.SYSTEM:
  153. if not system_configuration.enabled or not has_valid_quota:
  154. using_provider_type = ProviderType.CUSTOM
  155. else:
  156. if not custom_configuration.provider and not custom_configuration.models:
  157. if system_configuration.enabled and has_valid_quota:
  158. using_provider_type = ProviderType.SYSTEM
  159. # Get provider load balancing configs
  160. provider_model_settings = provider_name_to_provider_model_settings_dict.get(provider_name)
  161. # Get provider load balancing configs
  162. provider_load_balancing_configs = provider_name_to_provider_load_balancing_model_configs_dict.get(
  163. provider_name
  164. )
  165. # Convert to model settings
  166. model_settings = self._to_model_settings(
  167. provider_entity=provider_entity,
  168. provider_model_settings=provider_model_settings,
  169. load_balancing_model_configs=provider_load_balancing_configs,
  170. )
  171. provider_configuration = ProviderConfiguration(
  172. tenant_id=tenant_id,
  173. provider=provider_entity,
  174. preferred_provider_type=preferred_provider_type,
  175. using_provider_type=using_provider_type,
  176. system_configuration=system_configuration,
  177. custom_configuration=custom_configuration,
  178. model_settings=model_settings,
  179. )
  180. provider_configurations[str(ModelProviderID(provider_name))] = provider_configuration
  181. # Return the encapsulated object
  182. return provider_configurations
  183. def get_provider_model_bundle(self, tenant_id: str, provider: str, model_type: ModelType) -> ProviderModelBundle:
  184. """
  185. Get provider model bundle.
  186. :param tenant_id: workspace id
  187. :param provider: provider name
  188. :param model_type: model type
  189. :return:
  190. """
  191. provider_configurations = self.get_configurations(tenant_id)
  192. # get provider instance
  193. provider_configuration = provider_configurations.get(provider)
  194. if not provider_configuration:
  195. raise ValueError(f"Provider {provider} does not exist.")
  196. model_type_instance = provider_configuration.get_model_type_instance(model_type)
  197. return ProviderModelBundle(
  198. configuration=provider_configuration,
  199. model_type_instance=model_type_instance,
  200. )
  201. def get_default_model(self, tenant_id: str, model_type: ModelType) -> Optional[DefaultModelEntity]:
  202. """
  203. Get default model.
  204. :param tenant_id: workspace id
  205. :param model_type: model type
  206. :return:
  207. """
  208. # Get the corresponding TenantDefaultModel record
  209. default_model = (
  210. db.session.query(TenantDefaultModel)
  211. .filter(
  212. TenantDefaultModel.tenant_id == tenant_id,
  213. TenantDefaultModel.model_type == model_type.to_origin_model_type(),
  214. )
  215. .first()
  216. )
  217. # If it does not exist, get the first available provider model from get_configurations
  218. # and update the TenantDefaultModel record
  219. if not default_model:
  220. # Get provider configurations
  221. provider_configurations = self.get_configurations(tenant_id)
  222. # get available models from provider_configurations
  223. available_models = provider_configurations.get_models(model_type=model_type, only_active=True)
  224. if available_models:
  225. available_model = next(
  226. (model for model in available_models if model.model == "gpt-4"), available_models[0]
  227. )
  228. default_model = TenantDefaultModel()
  229. default_model.tenant_id = tenant_id
  230. default_model.model_type = model_type.to_origin_model_type()
  231. default_model.provider_name = available_model.provider.provider
  232. default_model.model_name = available_model.model
  233. db.session.add(default_model)
  234. db.session.commit()
  235. if not default_model:
  236. return None
  237. model_provider_factory = ModelProviderFactory(tenant_id)
  238. provider_schema = model_provider_factory.get_provider_schema(provider=default_model.provider_name)
  239. return DefaultModelEntity(
  240. model=default_model.model_name,
  241. model_type=model_type,
  242. provider=DefaultModelProviderEntity(
  243. provider=provider_schema.provider,
  244. label=provider_schema.label,
  245. icon_small=provider_schema.icon_small,
  246. icon_large=provider_schema.icon_large,
  247. supported_model_types=provider_schema.supported_model_types,
  248. ),
  249. )
  250. def get_first_provider_first_model(self, tenant_id: str, model_type: ModelType) -> tuple[str | None, str | None]:
  251. """
  252. Get names of first model and its provider
  253. :param tenant_id: workspace id
  254. :param model_type: model type
  255. :return: provider name, model name
  256. """
  257. provider_configurations = self.get_configurations(tenant_id)
  258. # get available models from provider_configurations
  259. all_models = provider_configurations.get_models(model_type=model_type, only_active=False)
  260. if not all_models:
  261. return None, None
  262. return all_models[0].provider.provider, all_models[0].model
  263. def update_default_model_record(
  264. self, tenant_id: str, model_type: ModelType, provider: str, model: str
  265. ) -> TenantDefaultModel:
  266. """
  267. Update default model record.
  268. :param tenant_id: workspace id
  269. :param model_type: model type
  270. :param provider: provider name
  271. :param model: model name
  272. :return:
  273. """
  274. provider_configurations = self.get_configurations(tenant_id)
  275. if provider not in provider_configurations:
  276. raise ValueError(f"Provider {provider} does not exist.")
  277. # get available models from provider_configurations
  278. available_models = provider_configurations.get_models(model_type=model_type, only_active=True)
  279. # check if the model is exist in available models
  280. model_names = [model.model for model in available_models]
  281. if model not in model_names:
  282. raise ValueError(f"Model {model} does not exist.")
  283. # Get the list of available models from get_configurations and check if it is LLM
  284. default_model = (
  285. db.session.query(TenantDefaultModel)
  286. .filter(
  287. TenantDefaultModel.tenant_id == tenant_id,
  288. TenantDefaultModel.model_type == model_type.to_origin_model_type(),
  289. )
  290. .first()
  291. )
  292. # create or update TenantDefaultModel record
  293. if default_model:
  294. # update default model
  295. default_model.provider_name = provider
  296. default_model.model_name = model
  297. db.session.commit()
  298. else:
  299. # create default model
  300. default_model = TenantDefaultModel(
  301. tenant_id=tenant_id,
  302. model_type=model_type.value,
  303. provider_name=provider,
  304. model_name=model,
  305. )
  306. db.session.add(default_model)
  307. db.session.commit()
  308. return default_model
  309. @staticmethod
  310. def _get_all_providers(tenant_id: str) -> dict[str, list[Provider]]:
  311. """
  312. Get all provider records of the workspace.
  313. :param tenant_id: workspace id
  314. :return:
  315. """
  316. providers = db.session.query(Provider).filter(Provider.tenant_id == tenant_id, Provider.is_valid == True).all()
  317. provider_name_to_provider_records_dict = defaultdict(list)
  318. for provider in providers:
  319. # TODO: Use provider name with prefix after the data migration
  320. provider_name_to_provider_records_dict[str(ModelProviderID(provider.provider_name))].append(provider)
  321. return provider_name_to_provider_records_dict
  322. @staticmethod
  323. def _get_all_provider_models(tenant_id: str) -> dict[str, list[ProviderModel]]:
  324. """
  325. Get all provider model records of the workspace.
  326. :param tenant_id: workspace id
  327. :return:
  328. """
  329. # Get all provider model records of the workspace
  330. provider_models = (
  331. db.session.query(ProviderModel)
  332. .filter(ProviderModel.tenant_id == tenant_id, ProviderModel.is_valid == True)
  333. .all()
  334. )
  335. provider_name_to_provider_model_records_dict = defaultdict(list)
  336. for provider_model in provider_models:
  337. provider_name_to_provider_model_records_dict[provider_model.provider_name].append(provider_model)
  338. return provider_name_to_provider_model_records_dict
  339. @staticmethod
  340. def _get_all_preferred_model_providers(tenant_id: str) -> dict[str, TenantPreferredModelProvider]:
  341. """
  342. Get All preferred provider types of the workspace.
  343. :param tenant_id: workspace id
  344. :return:
  345. """
  346. preferred_provider_types = (
  347. db.session.query(TenantPreferredModelProvider)
  348. .filter(TenantPreferredModelProvider.tenant_id == tenant_id)
  349. .all()
  350. )
  351. provider_name_to_preferred_provider_type_records_dict = {
  352. preferred_provider_type.provider_name: preferred_provider_type
  353. for preferred_provider_type in preferred_provider_types
  354. }
  355. return provider_name_to_preferred_provider_type_records_dict
  356. @staticmethod
  357. def _get_all_provider_model_settings(tenant_id: str) -> dict[str, list[ProviderModelSetting]]:
  358. """
  359. Get All provider model settings of the workspace.
  360. :param tenant_id: workspace id
  361. :return:
  362. """
  363. provider_model_settings = (
  364. db.session.query(ProviderModelSetting).filter(ProviderModelSetting.tenant_id == tenant_id).all()
  365. )
  366. provider_name_to_provider_model_settings_dict = defaultdict(list)
  367. for provider_model_setting in provider_model_settings:
  368. (
  369. provider_name_to_provider_model_settings_dict[provider_model_setting.provider_name].append(
  370. provider_model_setting
  371. )
  372. )
  373. return provider_name_to_provider_model_settings_dict
  374. @staticmethod
  375. def _get_all_provider_load_balancing_configs(tenant_id: str) -> dict[str, list[LoadBalancingModelConfig]]:
  376. """
  377. Get All provider load balancing configs of the workspace.
  378. :param tenant_id: workspace id
  379. :return:
  380. """
  381. cache_key = f"tenant:{tenant_id}:model_load_balancing_enabled"
  382. cache_result = redis_client.get(cache_key)
  383. if cache_result is None:
  384. model_load_balancing_enabled = FeatureService.get_features(tenant_id).model_load_balancing_enabled
  385. redis_client.setex(cache_key, 120, str(model_load_balancing_enabled))
  386. else:
  387. cache_result = cache_result.decode("utf-8")
  388. model_load_balancing_enabled = cache_result == "True"
  389. if not model_load_balancing_enabled:
  390. return {}
  391. provider_load_balancing_configs = (
  392. db.session.query(LoadBalancingModelConfig).filter(LoadBalancingModelConfig.tenant_id == tenant_id).all()
  393. )
  394. provider_name_to_provider_load_balancing_model_configs_dict = defaultdict(list)
  395. for provider_load_balancing_config in provider_load_balancing_configs:
  396. provider_name_to_provider_load_balancing_model_configs_dict[
  397. provider_load_balancing_config.provider_name
  398. ].append(provider_load_balancing_config)
  399. return provider_name_to_provider_load_balancing_model_configs_dict
  400. @staticmethod
  401. def _init_trial_provider_records(
  402. tenant_id: str, provider_name_to_provider_records_dict: dict[str, list]
  403. ) -> dict[str, list]:
  404. """
  405. Initialize trial provider records if not exists.
  406. :param tenant_id: workspace id
  407. :param provider_name_to_provider_records_dict: provider name to provider records dict
  408. :return:
  409. """
  410. # Get hosting configuration
  411. hosting_configuration = ext_hosting_provider.hosting_configuration
  412. for provider_name, configuration in hosting_configuration.provider_map.items():
  413. if not configuration.enabled:
  414. continue
  415. provider_records = provider_name_to_provider_records_dict.get(provider_name)
  416. if not provider_records:
  417. provider_records = []
  418. provider_quota_to_provider_record_dict = {}
  419. for provider_record in provider_records:
  420. if provider_record.provider_type != ProviderType.SYSTEM.value:
  421. continue
  422. provider_quota_to_provider_record_dict[ProviderQuotaType.value_of(provider_record.quota_type)] = (
  423. provider_record
  424. )
  425. for quota in configuration.quotas:
  426. if quota.quota_type == ProviderQuotaType.TRIAL:
  427. # Init trial provider records if not exists
  428. if ProviderQuotaType.TRIAL not in provider_quota_to_provider_record_dict:
  429. try:
  430. # FIXME ignore the type errork, onyl TrialHostingQuota has limit need to change the logic
  431. provider_record = Provider(
  432. tenant_id=tenant_id,
  433. # TODO: Use provider name with prefix after the data migration.
  434. provider_name=ModelProviderID(provider_name).provider_name,
  435. provider_type=ProviderType.SYSTEM.value,
  436. quota_type=ProviderQuotaType.TRIAL.value,
  437. quota_limit=quota.quota_limit, # type: ignore
  438. quota_used=0,
  439. is_valid=True,
  440. )
  441. db.session.add(provider_record)
  442. db.session.commit()
  443. except IntegrityError:
  444. db.session.rollback()
  445. provider_record = (
  446. db.session.query(Provider)
  447. .filter(
  448. Provider.tenant_id == tenant_id,
  449. Provider.provider_name == ModelProviderID(provider_name).provider_name,
  450. Provider.provider_type == ProviderType.SYSTEM.value,
  451. Provider.quota_type == ProviderQuotaType.TRIAL.value,
  452. )
  453. .first()
  454. )
  455. if provider_record and not provider_record.is_valid:
  456. provider_record.is_valid = True
  457. db.session.commit()
  458. provider_name_to_provider_records_dict[provider_name].append(provider_record)
  459. return provider_name_to_provider_records_dict
  460. def _to_custom_configuration(
  461. self,
  462. tenant_id: str,
  463. provider_entity: ProviderEntity,
  464. provider_records: list[Provider],
  465. provider_model_records: list[ProviderModel],
  466. ) -> CustomConfiguration:
  467. """
  468. Convert to custom configuration.
  469. :param tenant_id: workspace id
  470. :param provider_entity: provider entity
  471. :param provider_records: provider records
  472. :param provider_model_records: provider model records
  473. :return:
  474. """
  475. # Get provider credential secret variables
  476. provider_credential_secret_variables = self._extract_secret_variables(
  477. provider_entity.provider_credential_schema.credential_form_schemas
  478. if provider_entity.provider_credential_schema
  479. else []
  480. )
  481. # Get custom provider record
  482. custom_provider_record = None
  483. for provider_record in provider_records:
  484. if provider_record.provider_type == ProviderType.SYSTEM.value:
  485. continue
  486. if not provider_record.encrypted_config:
  487. continue
  488. custom_provider_record = provider_record
  489. # Get custom provider credentials
  490. custom_provider_configuration = None
  491. if custom_provider_record:
  492. provider_credentials_cache = ProviderCredentialsCache(
  493. tenant_id=tenant_id,
  494. identity_id=custom_provider_record.id,
  495. cache_type=ProviderCredentialsCacheType.PROVIDER,
  496. )
  497. # Get cached provider credentials
  498. cached_provider_credentials = provider_credentials_cache.get()
  499. if not cached_provider_credentials:
  500. try:
  501. # fix origin data
  502. if (
  503. custom_provider_record.encrypted_config
  504. and not custom_provider_record.encrypted_config.startswith("{")
  505. ):
  506. provider_credentials = {"openai_api_key": custom_provider_record.encrypted_config}
  507. else:
  508. provider_credentials = json.loads(custom_provider_record.encrypted_config)
  509. except JSONDecodeError:
  510. provider_credentials = {}
  511. # Get decoding rsa key and cipher for decrypting credentials
  512. if self.decoding_rsa_key is None or self.decoding_cipher_rsa is None:
  513. self.decoding_rsa_key, self.decoding_cipher_rsa = encrypter.get_decrypt_decoding(tenant_id)
  514. for variable in provider_credential_secret_variables:
  515. if variable in provider_credentials:
  516. try:
  517. provider_credentials[variable] = encrypter.decrypt_token_with_decoding(
  518. provider_credentials.get(variable) or "", # type: ignore
  519. self.decoding_rsa_key,
  520. self.decoding_cipher_rsa,
  521. )
  522. except ValueError:
  523. pass
  524. # cache provider credentials
  525. provider_credentials_cache.set(credentials=provider_credentials)
  526. else:
  527. provider_credentials = cached_provider_credentials
  528. custom_provider_configuration = CustomProviderConfiguration(credentials=provider_credentials)
  529. # Get provider model credential secret variables
  530. model_credential_secret_variables = self._extract_secret_variables(
  531. provider_entity.model_credential_schema.credential_form_schemas
  532. if provider_entity.model_credential_schema
  533. else []
  534. )
  535. # Get custom provider model credentials
  536. custom_model_configurations = []
  537. for provider_model_record in provider_model_records:
  538. if not provider_model_record.encrypted_config:
  539. continue
  540. provider_model_credentials_cache = ProviderCredentialsCache(
  541. tenant_id=tenant_id, identity_id=provider_model_record.id, cache_type=ProviderCredentialsCacheType.MODEL
  542. )
  543. # Get cached provider model credentials
  544. cached_provider_model_credentials = provider_model_credentials_cache.get()
  545. if not cached_provider_model_credentials:
  546. try:
  547. provider_model_credentials = json.loads(provider_model_record.encrypted_config)
  548. except JSONDecodeError:
  549. continue
  550. # Get decoding rsa key and cipher for decrypting credentials
  551. if self.decoding_rsa_key is None or self.decoding_cipher_rsa is None:
  552. self.decoding_rsa_key, self.decoding_cipher_rsa = encrypter.get_decrypt_decoding(tenant_id)
  553. for variable in model_credential_secret_variables:
  554. if variable in provider_model_credentials:
  555. try:
  556. provider_model_credentials[variable] = encrypter.decrypt_token_with_decoding(
  557. provider_model_credentials.get(variable),
  558. self.decoding_rsa_key,
  559. self.decoding_cipher_rsa,
  560. )
  561. except ValueError:
  562. pass
  563. # cache provider model credentials
  564. provider_model_credentials_cache.set(credentials=provider_model_credentials)
  565. else:
  566. provider_model_credentials = cached_provider_model_credentials
  567. custom_model_configurations.append(
  568. CustomModelConfiguration(
  569. model=provider_model_record.model_name,
  570. model_type=ModelType.value_of(provider_model_record.model_type),
  571. credentials=provider_model_credentials,
  572. )
  573. )
  574. return CustomConfiguration(provider=custom_provider_configuration, models=custom_model_configurations)
  575. def _to_system_configuration(
  576. self, tenant_id: str, provider_entity: ProviderEntity, provider_records: list[Provider]
  577. ) -> SystemConfiguration:
  578. """
  579. Convert to system configuration.
  580. :param tenant_id: workspace id
  581. :param provider_entity: provider entity
  582. :param provider_records: provider records
  583. :return:
  584. """
  585. # Get hosting configuration
  586. hosting_configuration = ext_hosting_provider.hosting_configuration
  587. provider_hosting_configuration = hosting_configuration.provider_map.get(provider_entity.provider)
  588. if provider_hosting_configuration is None or not provider_hosting_configuration.enabled:
  589. return SystemConfiguration(enabled=False)
  590. # Convert provider_records to dict
  591. quota_type_to_provider_records_dict = {}
  592. for provider_record in provider_records:
  593. if provider_record.provider_type != ProviderType.SYSTEM.value:
  594. continue
  595. quota_type_to_provider_records_dict[ProviderQuotaType.value_of(provider_record.quota_type)] = (
  596. provider_record
  597. )
  598. quota_configurations = []
  599. for provider_quota in provider_hosting_configuration.quotas:
  600. if provider_quota.quota_type not in quota_type_to_provider_records_dict:
  601. if provider_quota.quota_type == ProviderQuotaType.FREE:
  602. quota_configuration = QuotaConfiguration(
  603. quota_type=provider_quota.quota_type,
  604. quota_unit=provider_hosting_configuration.quota_unit or QuotaUnit.TOKENS,
  605. quota_used=0,
  606. quota_limit=0,
  607. is_valid=False,
  608. restrict_models=provider_quota.restrict_models,
  609. )
  610. else:
  611. continue
  612. else:
  613. provider_record = quota_type_to_provider_records_dict[provider_quota.quota_type]
  614. quota_configuration = QuotaConfiguration(
  615. quota_type=provider_quota.quota_type,
  616. quota_unit=provider_hosting_configuration.quota_unit or QuotaUnit.TOKENS,
  617. quota_used=provider_record.quota_used,
  618. quota_limit=provider_record.quota_limit,
  619. is_valid=provider_record.quota_limit > provider_record.quota_used
  620. or provider_record.quota_limit == -1,
  621. restrict_models=provider_quota.restrict_models,
  622. )
  623. quota_configurations.append(quota_configuration)
  624. if len(quota_configurations) == 0:
  625. return SystemConfiguration(enabled=False)
  626. current_quota_type = self._choice_current_using_quota_type(quota_configurations)
  627. current_using_credentials = provider_hosting_configuration.credentials
  628. if current_quota_type == ProviderQuotaType.FREE:
  629. provider_record_quota_free = quota_type_to_provider_records_dict.get(current_quota_type)
  630. if provider_record_quota_free:
  631. provider_credentials_cache = ProviderCredentialsCache(
  632. tenant_id=tenant_id,
  633. identity_id=provider_record_quota_free.id,
  634. cache_type=ProviderCredentialsCacheType.PROVIDER,
  635. )
  636. # Get cached provider credentials
  637. # error occurs
  638. cached_provider_credentials = provider_credentials_cache.get()
  639. if not cached_provider_credentials:
  640. try:
  641. provider_credentials: dict[str, Any] = json.loads(provider_record.encrypted_config)
  642. except JSONDecodeError:
  643. provider_credentials = {}
  644. # Get provider credential secret variables
  645. provider_credential_secret_variables = self._extract_secret_variables(
  646. provider_entity.provider_credential_schema.credential_form_schemas
  647. if provider_entity.provider_credential_schema
  648. else []
  649. )
  650. # Get decoding rsa key and cipher for decrypting credentials
  651. if self.decoding_rsa_key is None or self.decoding_cipher_rsa is None:
  652. self.decoding_rsa_key, self.decoding_cipher_rsa = encrypter.get_decrypt_decoding(tenant_id)
  653. for variable in provider_credential_secret_variables:
  654. if variable in provider_credentials:
  655. try:
  656. provider_credentials[variable] = encrypter.decrypt_token_with_decoding(
  657. provider_credentials.get(variable, ""),
  658. self.decoding_rsa_key,
  659. self.decoding_cipher_rsa,
  660. )
  661. except ValueError:
  662. pass
  663. current_using_credentials = provider_credentials or {}
  664. # cache provider credentials
  665. provider_credentials_cache.set(credentials=current_using_credentials)
  666. else:
  667. current_using_credentials = cached_provider_credentials
  668. else:
  669. current_using_credentials = {}
  670. quota_configurations = []
  671. return SystemConfiguration(
  672. enabled=True,
  673. current_quota_type=current_quota_type,
  674. quota_configurations=quota_configurations,
  675. credentials=current_using_credentials,
  676. )
  677. @staticmethod
  678. def _choice_current_using_quota_type(quota_configurations: list[QuotaConfiguration]) -> ProviderQuotaType:
  679. """
  680. Choice current using quota type.
  681. paid quotas > provider free quotas > hosting trial quotas
  682. If there is still quota for the corresponding quota type according to the sorting,
  683. :param quota_configurations:
  684. :return:
  685. """
  686. # convert to dict
  687. quota_type_to_quota_configuration_dict = {
  688. quota_configuration.quota_type: quota_configuration for quota_configuration in quota_configurations
  689. }
  690. last_quota_configuration = None
  691. for quota_type in [ProviderQuotaType.PAID, ProviderQuotaType.FREE, ProviderQuotaType.TRIAL]:
  692. if quota_type in quota_type_to_quota_configuration_dict:
  693. last_quota_configuration = quota_type_to_quota_configuration_dict[quota_type]
  694. if last_quota_configuration.is_valid:
  695. return quota_type
  696. if last_quota_configuration:
  697. return last_quota_configuration.quota_type
  698. raise ValueError("No quota type available")
  699. @staticmethod
  700. def _extract_secret_variables(credential_form_schemas: list[CredentialFormSchema]) -> list[str]:
  701. """
  702. Extract secret input form variables.
  703. :param credential_form_schemas:
  704. :return:
  705. """
  706. secret_input_form_variables = []
  707. for credential_form_schema in credential_form_schemas:
  708. if credential_form_schema.type == FormType.SECRET_INPUT:
  709. secret_input_form_variables.append(credential_form_schema.variable)
  710. return secret_input_form_variables
  711. def _to_model_settings(
  712. self,
  713. provider_entity: ProviderEntity,
  714. provider_model_settings: Optional[list[ProviderModelSetting]] = None,
  715. load_balancing_model_configs: Optional[list[LoadBalancingModelConfig]] = None,
  716. ) -> list[ModelSettings]:
  717. """
  718. Convert to model settings.
  719. :param provider_entity: provider entity
  720. :param provider_model_settings: provider model settings include enabled, load balancing enabled
  721. :param load_balancing_model_configs: load balancing model configs
  722. :return:
  723. """
  724. # Get provider model credential secret variables
  725. if ConfigurateMethod.PREDEFINED_MODEL in provider_entity.configurate_methods:
  726. model_credential_secret_variables = self._extract_secret_variables(
  727. provider_entity.provider_credential_schema.credential_form_schemas
  728. if provider_entity.provider_credential_schema
  729. else []
  730. )
  731. else:
  732. model_credential_secret_variables = self._extract_secret_variables(
  733. provider_entity.model_credential_schema.credential_form_schemas
  734. if provider_entity.model_credential_schema
  735. else []
  736. )
  737. model_settings: list[ModelSettings] = []
  738. if not provider_model_settings:
  739. return model_settings
  740. for provider_model_setting in provider_model_settings:
  741. load_balancing_configs = []
  742. if provider_model_setting.load_balancing_enabled and load_balancing_model_configs:
  743. for load_balancing_model_config in load_balancing_model_configs:
  744. if (
  745. load_balancing_model_config.model_name == provider_model_setting.model_name
  746. and load_balancing_model_config.model_type == provider_model_setting.model_type
  747. ):
  748. if not load_balancing_model_config.enabled:
  749. continue
  750. if not load_balancing_model_config.encrypted_config:
  751. if load_balancing_model_config.name == "__inherit__":
  752. load_balancing_configs.append(
  753. ModelLoadBalancingConfiguration(
  754. id=load_balancing_model_config.id,
  755. name=load_balancing_model_config.name,
  756. credentials={},
  757. )
  758. )
  759. continue
  760. provider_model_credentials_cache = ProviderCredentialsCache(
  761. tenant_id=load_balancing_model_config.tenant_id,
  762. identity_id=load_balancing_model_config.id,
  763. cache_type=ProviderCredentialsCacheType.LOAD_BALANCING_MODEL,
  764. )
  765. # Get cached provider model credentials
  766. cached_provider_model_credentials = provider_model_credentials_cache.get()
  767. if not cached_provider_model_credentials:
  768. try:
  769. provider_model_credentials = json.loads(load_balancing_model_config.encrypted_config)
  770. except JSONDecodeError:
  771. continue
  772. # Get decoding rsa key and cipher for decrypting credentials
  773. if self.decoding_rsa_key is None or self.decoding_cipher_rsa is None:
  774. self.decoding_rsa_key, self.decoding_cipher_rsa = encrypter.get_decrypt_decoding(
  775. load_balancing_model_config.tenant_id
  776. )
  777. for variable in model_credential_secret_variables:
  778. if variable in provider_model_credentials:
  779. try:
  780. provider_model_credentials[variable] = encrypter.decrypt_token_with_decoding(
  781. provider_model_credentials.get(variable),
  782. self.decoding_rsa_key,
  783. self.decoding_cipher_rsa,
  784. )
  785. except ValueError:
  786. pass
  787. # cache provider model credentials
  788. provider_model_credentials_cache.set(credentials=provider_model_credentials)
  789. else:
  790. provider_model_credentials = cached_provider_model_credentials
  791. load_balancing_configs.append(
  792. ModelLoadBalancingConfiguration(
  793. id=load_balancing_model_config.id,
  794. name=load_balancing_model_config.name,
  795. credentials=provider_model_credentials,
  796. )
  797. )
  798. model_settings.append(
  799. ModelSettings(
  800. model=provider_model_setting.model_name,
  801. model_type=ModelType.value_of(provider_model_setting.model_type),
  802. enabled=provider_model_setting.enabled,
  803. load_balancing_configs=load_balancing_configs if len(load_balancing_configs) > 1 else [],
  804. )
  805. )
  806. return model_settings