provider_manager.py 40 KB

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