provider_manager.py 40 KB

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