provider_manager.py 43 KB

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