You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

provider_manager.py 44KB

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