provider_manager.py 40 KB

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