provider_manager.py 40 KB

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