provider_manager.py 41 KB

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