provider_manager.py 41 KB

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