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 47KB

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