provider_configuration.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. import datetime
  2. import json
  3. import logging
  4. from collections import defaultdict
  5. from collections.abc import Iterator, Sequence
  6. from json import JSONDecodeError
  7. from typing import Optional
  8. from pydantic import BaseModel, ConfigDict, Field
  9. from sqlalchemy import or_
  10. from constants import HIDDEN_VALUE
  11. from core.entities.model_entities import ModelStatus, ModelWithProviderEntity, SimpleModelProviderEntity
  12. from core.entities.provider_entities import (
  13. CustomConfiguration,
  14. ModelSettings,
  15. SystemConfiguration,
  16. SystemConfigurationStatus,
  17. )
  18. from core.helper import encrypter
  19. from core.helper.model_provider_cache import ProviderCredentialsCache, ProviderCredentialsCacheType
  20. from core.model_runtime.entities.model_entities import AIModelEntity, FetchFrom, ModelType
  21. from core.model_runtime.entities.provider_entities import (
  22. ConfigurateMethod,
  23. CredentialFormSchema,
  24. FormType,
  25. ProviderEntity,
  26. )
  27. from core.model_runtime.model_providers.__base.ai_model import AIModel
  28. from core.model_runtime.model_providers.model_provider_factory import ModelProviderFactory
  29. from core.plugin.entities.plugin import ModelProviderID
  30. from extensions.ext_database import db
  31. from models.provider import (
  32. LoadBalancingModelConfig,
  33. Provider,
  34. ProviderModel,
  35. ProviderModelSetting,
  36. ProviderType,
  37. TenantPreferredModelProvider,
  38. )
  39. logger = logging.getLogger(__name__)
  40. original_provider_configurate_methods: dict[str, list[ConfigurateMethod]] = {}
  41. class ProviderConfiguration(BaseModel):
  42. """
  43. Model class for provider configuration.
  44. """
  45. tenant_id: str
  46. provider: ProviderEntity
  47. preferred_provider_type: ProviderType
  48. using_provider_type: ProviderType
  49. system_configuration: SystemConfiguration
  50. custom_configuration: CustomConfiguration
  51. model_settings: list[ModelSettings]
  52. # pydantic configs
  53. model_config = ConfigDict(protected_namespaces=())
  54. def __init__(self, **data):
  55. super().__init__(**data)
  56. if self.provider.provider not in original_provider_configurate_methods:
  57. original_provider_configurate_methods[self.provider.provider] = []
  58. for configurate_method in self.provider.configurate_methods:
  59. original_provider_configurate_methods[self.provider.provider].append(configurate_method)
  60. if original_provider_configurate_methods[self.provider.provider] == [ConfigurateMethod.CUSTOMIZABLE_MODEL]:
  61. if (
  62. any(
  63. len(quota_configuration.restrict_models) > 0
  64. for quota_configuration in self.system_configuration.quota_configurations
  65. )
  66. and ConfigurateMethod.PREDEFINED_MODEL not in self.provider.configurate_methods
  67. ):
  68. self.provider.configurate_methods.append(ConfigurateMethod.PREDEFINED_MODEL)
  69. def get_current_credentials(self, model_type: ModelType, model: str) -> Optional[dict]:
  70. """
  71. Get current credentials.
  72. :param model_type: model type
  73. :param model: model name
  74. :return:
  75. """
  76. if self.model_settings:
  77. # check if model is disabled by admin
  78. for model_setting in self.model_settings:
  79. if model_setting.model_type == model_type and model_setting.model == model:
  80. if not model_setting.enabled:
  81. raise ValueError(f"Model {model} is disabled.")
  82. if self.using_provider_type == ProviderType.SYSTEM:
  83. restrict_models = []
  84. for quota_configuration in self.system_configuration.quota_configurations:
  85. if self.system_configuration.current_quota_type != quota_configuration.quota_type:
  86. continue
  87. restrict_models = quota_configuration.restrict_models
  88. copy_credentials = (
  89. self.system_configuration.credentials.copy() if self.system_configuration.credentials else {}
  90. )
  91. if restrict_models:
  92. for restrict_model in restrict_models:
  93. if (
  94. restrict_model.model_type == model_type
  95. and restrict_model.model == model
  96. and restrict_model.base_model_name
  97. ):
  98. copy_credentials["base_model_name"] = restrict_model.base_model_name
  99. return copy_credentials
  100. else:
  101. credentials = None
  102. if self.custom_configuration.models:
  103. for model_configuration in self.custom_configuration.models:
  104. if model_configuration.model_type == model_type and model_configuration.model == model:
  105. credentials = model_configuration.credentials
  106. break
  107. if not credentials and self.custom_configuration.provider:
  108. credentials = self.custom_configuration.provider.credentials
  109. return credentials
  110. def get_system_configuration_status(self) -> Optional[SystemConfigurationStatus]:
  111. """
  112. Get system configuration status.
  113. :return:
  114. """
  115. if self.system_configuration.enabled is False:
  116. return SystemConfigurationStatus.UNSUPPORTED
  117. current_quota_type = self.system_configuration.current_quota_type
  118. current_quota_configuration = next(
  119. (q for q in self.system_configuration.quota_configurations if q.quota_type == current_quota_type), None
  120. )
  121. if current_quota_configuration is None:
  122. return None
  123. if not current_quota_configuration:
  124. return SystemConfigurationStatus.UNSUPPORTED
  125. return (
  126. SystemConfigurationStatus.ACTIVE
  127. if current_quota_configuration.is_valid
  128. else SystemConfigurationStatus.QUOTA_EXCEEDED
  129. )
  130. def is_custom_configuration_available(self) -> bool:
  131. """
  132. Check custom configuration available.
  133. :return:
  134. """
  135. return self.custom_configuration.provider is not None or len(self.custom_configuration.models) > 0
  136. def get_custom_credentials(self, obfuscated: bool = False) -> dict | None:
  137. """
  138. Get custom credentials.
  139. :param obfuscated: obfuscated secret data in credentials
  140. :return:
  141. """
  142. if self.custom_configuration.provider is None:
  143. return None
  144. credentials = self.custom_configuration.provider.credentials
  145. if not obfuscated:
  146. return credentials
  147. # Obfuscate credentials
  148. return self.obfuscated_credentials(
  149. credentials=credentials,
  150. credential_form_schemas=self.provider.provider_credential_schema.credential_form_schemas
  151. if self.provider.provider_credential_schema
  152. else [],
  153. )
  154. def custom_credentials_validate(self, credentials: dict) -> tuple[Provider | None, dict]:
  155. """
  156. Validate custom credentials.
  157. :param credentials: provider credentials
  158. :return:
  159. """
  160. # get provider
  161. provider_record = (
  162. db.session.query(Provider)
  163. .filter(
  164. Provider.tenant_id == self.tenant_id,
  165. Provider.provider_type == ProviderType.CUSTOM.value,
  166. or_(
  167. Provider.provider_name == ModelProviderID(self.provider.provider).plugin_name,
  168. Provider.provider_name == self.provider.provider,
  169. ),
  170. )
  171. .first()
  172. )
  173. # Get provider credential secret variables
  174. provider_credential_secret_variables = self.extract_secret_variables(
  175. self.provider.provider_credential_schema.credential_form_schemas
  176. if self.provider.provider_credential_schema
  177. else []
  178. )
  179. if provider_record:
  180. try:
  181. # fix origin data
  182. if provider_record.encrypted_config:
  183. if not provider_record.encrypted_config.startswith("{"):
  184. original_credentials = {"openai_api_key": provider_record.encrypted_config}
  185. else:
  186. original_credentials = json.loads(provider_record.encrypted_config)
  187. else:
  188. original_credentials = {}
  189. except JSONDecodeError:
  190. original_credentials = {}
  191. # encrypt credentials
  192. for key, value in credentials.items():
  193. if key in provider_credential_secret_variables:
  194. # if send [__HIDDEN__] in secret input, it will be same as original value
  195. if value == HIDDEN_VALUE and key in original_credentials:
  196. credentials[key] = encrypter.decrypt_token(self.tenant_id, original_credentials[key])
  197. model_provider_factory = ModelProviderFactory(self.tenant_id)
  198. credentials = model_provider_factory.provider_credentials_validate(
  199. provider=self.provider.provider, credentials=credentials
  200. )
  201. for key, value in credentials.items():
  202. if key in provider_credential_secret_variables:
  203. credentials[key] = encrypter.encrypt_token(self.tenant_id, value)
  204. return provider_record, credentials
  205. def add_or_update_custom_credentials(self, credentials: dict) -> None:
  206. """
  207. Add or update custom provider credentials.
  208. :param credentials:
  209. :return:
  210. """
  211. # validate custom provider config
  212. provider_record, credentials = self.custom_credentials_validate(credentials)
  213. # save provider
  214. # Note: Do not switch the preferred provider, which allows users to use quotas first
  215. if provider_record:
  216. provider_record.encrypted_config = json.dumps(credentials)
  217. provider_record.is_valid = True
  218. provider_record.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  219. db.session.commit()
  220. else:
  221. provider_record = Provider()
  222. provider_record.tenant_id = self.tenant_id
  223. provider_record.provider_name = self.provider.provider
  224. provider_record.provider_type = ProviderType.CUSTOM.value
  225. provider_record.encrypted_config = json.dumps(credentials)
  226. provider_record.is_valid = True
  227. db.session.add(provider_record)
  228. db.session.commit()
  229. provider_model_credentials_cache = ProviderCredentialsCache(
  230. tenant_id=self.tenant_id, identity_id=provider_record.id, cache_type=ProviderCredentialsCacheType.PROVIDER
  231. )
  232. provider_model_credentials_cache.delete()
  233. self.switch_preferred_provider_type(ProviderType.CUSTOM)
  234. def delete_custom_credentials(self) -> None:
  235. """
  236. Delete custom provider credentials.
  237. :return:
  238. """
  239. # get provider
  240. provider_record = (
  241. db.session.query(Provider)
  242. .filter(
  243. Provider.tenant_id == self.tenant_id,
  244. or_(
  245. Provider.provider_name == ModelProviderID(self.provider.provider).plugin_name,
  246. Provider.provider_name == self.provider.provider,
  247. ),
  248. Provider.provider_type == ProviderType.CUSTOM.value,
  249. )
  250. .first()
  251. )
  252. # delete provider
  253. if provider_record:
  254. self.switch_preferred_provider_type(ProviderType.SYSTEM)
  255. db.session.delete(provider_record)
  256. db.session.commit()
  257. provider_model_credentials_cache = ProviderCredentialsCache(
  258. tenant_id=self.tenant_id,
  259. identity_id=provider_record.id,
  260. cache_type=ProviderCredentialsCacheType.PROVIDER,
  261. )
  262. provider_model_credentials_cache.delete()
  263. def get_custom_model_credentials(
  264. self, model_type: ModelType, model: str, obfuscated: bool = False
  265. ) -> Optional[dict]:
  266. """
  267. Get custom model credentials.
  268. :param model_type: model type
  269. :param model: model name
  270. :param obfuscated: obfuscated secret data in credentials
  271. :return:
  272. """
  273. if not self.custom_configuration.models:
  274. return None
  275. for model_configuration in self.custom_configuration.models:
  276. if model_configuration.model_type == model_type and model_configuration.model == model:
  277. credentials = model_configuration.credentials
  278. if not obfuscated:
  279. return credentials
  280. # Obfuscate credentials
  281. return self.obfuscated_credentials(
  282. credentials=credentials,
  283. credential_form_schemas=self.provider.model_credential_schema.credential_form_schemas
  284. if self.provider.model_credential_schema
  285. else [],
  286. )
  287. return None
  288. def custom_model_credentials_validate(
  289. self, model_type: ModelType, model: str, credentials: dict
  290. ) -> tuple[ProviderModel | None, dict]:
  291. """
  292. Validate custom model credentials.
  293. :param model_type: model type
  294. :param model: model name
  295. :param credentials: model credentials
  296. :return:
  297. """
  298. # get provider model
  299. provider_model_record = (
  300. db.session.query(ProviderModel)
  301. .filter(
  302. ProviderModel.tenant_id == self.tenant_id,
  303. ProviderModel.provider_name == self.provider.provider,
  304. ProviderModel.model_name == model,
  305. ProviderModel.model_type == model_type.to_origin_model_type(),
  306. )
  307. .first()
  308. )
  309. # Get provider credential secret variables
  310. provider_credential_secret_variables = self.extract_secret_variables(
  311. self.provider.model_credential_schema.credential_form_schemas
  312. if self.provider.model_credential_schema
  313. else []
  314. )
  315. if provider_model_record:
  316. try:
  317. original_credentials = (
  318. json.loads(provider_model_record.encrypted_config) if provider_model_record.encrypted_config else {}
  319. )
  320. except JSONDecodeError:
  321. original_credentials = {}
  322. # decrypt credentials
  323. for key, value in credentials.items():
  324. if key in provider_credential_secret_variables:
  325. # if send [__HIDDEN__] in secret input, it will be same as original value
  326. if value == HIDDEN_VALUE and key in original_credentials:
  327. credentials[key] = encrypter.decrypt_token(self.tenant_id, original_credentials[key])
  328. model_provider_factory = ModelProviderFactory(self.tenant_id)
  329. credentials = model_provider_factory.model_credentials_validate(
  330. provider=self.provider.provider, model_type=model_type, model=model, credentials=credentials
  331. )
  332. for key, value in credentials.items():
  333. if key in provider_credential_secret_variables:
  334. credentials[key] = encrypter.encrypt_token(self.tenant_id, value)
  335. return provider_model_record, credentials
  336. def add_or_update_custom_model_credentials(self, model_type: ModelType, model: str, credentials: dict) -> None:
  337. """
  338. Add or update custom model credentials.
  339. :param model_type: model type
  340. :param model: model name
  341. :param credentials: model credentials
  342. :return:
  343. """
  344. # validate custom model config
  345. provider_model_record, credentials = self.custom_model_credentials_validate(model_type, model, credentials)
  346. # save provider model
  347. # Note: Do not switch the preferred provider, which allows users to use quotas first
  348. if provider_model_record:
  349. provider_model_record.encrypted_config = json.dumps(credentials)
  350. provider_model_record.is_valid = True
  351. provider_model_record.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  352. db.session.commit()
  353. else:
  354. provider_model_record = ProviderModel()
  355. provider_model_record.tenant_id = self.tenant_id
  356. provider_model_record.provider_name = self.provider.provider
  357. provider_model_record.model_name = model
  358. provider_model_record.model_type = model_type.to_origin_model_type()
  359. provider_model_record.encrypted_config = json.dumps(credentials)
  360. provider_model_record.is_valid = True
  361. db.session.add(provider_model_record)
  362. db.session.commit()
  363. provider_model_credentials_cache = ProviderCredentialsCache(
  364. tenant_id=self.tenant_id,
  365. identity_id=provider_model_record.id,
  366. cache_type=ProviderCredentialsCacheType.MODEL,
  367. )
  368. provider_model_credentials_cache.delete()
  369. def delete_custom_model_credentials(self, model_type: ModelType, model: str) -> None:
  370. """
  371. Delete custom model credentials.
  372. :param model_type: model type
  373. :param model: model name
  374. :return:
  375. """
  376. # get provider model
  377. provider_model_record = (
  378. db.session.query(ProviderModel)
  379. .filter(
  380. ProviderModel.tenant_id == self.tenant_id,
  381. ProviderModel.provider_name == self.provider.provider,
  382. ProviderModel.model_name == model,
  383. ProviderModel.model_type == model_type.to_origin_model_type(),
  384. )
  385. .first()
  386. )
  387. # delete provider model
  388. if provider_model_record:
  389. db.session.delete(provider_model_record)
  390. db.session.commit()
  391. provider_model_credentials_cache = ProviderCredentialsCache(
  392. tenant_id=self.tenant_id,
  393. identity_id=provider_model_record.id,
  394. cache_type=ProviderCredentialsCacheType.MODEL,
  395. )
  396. provider_model_credentials_cache.delete()
  397. def enable_model(self, model_type: ModelType, model: str) -> ProviderModelSetting:
  398. """
  399. Enable model.
  400. :param model_type: model type
  401. :param model: model name
  402. :return:
  403. """
  404. model_setting = (
  405. db.session.query(ProviderModelSetting)
  406. .filter(
  407. ProviderModelSetting.tenant_id == self.tenant_id,
  408. ProviderModelSetting.provider_name == self.provider.provider,
  409. ProviderModelSetting.model_type == model_type.to_origin_model_type(),
  410. ProviderModelSetting.model_name == model,
  411. )
  412. .first()
  413. )
  414. if model_setting:
  415. model_setting.enabled = True
  416. model_setting.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  417. db.session.commit()
  418. else:
  419. model_setting = ProviderModelSetting()
  420. model_setting.tenant_id = self.tenant_id
  421. model_setting.provider_name = self.provider.provider
  422. model_setting.model_type = model_type.to_origin_model_type()
  423. model_setting.model_name = model
  424. model_setting.enabled = True
  425. db.session.add(model_setting)
  426. db.session.commit()
  427. return model_setting
  428. def disable_model(self, model_type: ModelType, model: str) -> ProviderModelSetting:
  429. """
  430. Disable model.
  431. :param model_type: model type
  432. :param model: model name
  433. :return:
  434. """
  435. model_setting = (
  436. db.session.query(ProviderModelSetting)
  437. .filter(
  438. ProviderModelSetting.tenant_id == self.tenant_id,
  439. ProviderModelSetting.provider_name == self.provider.provider,
  440. ProviderModelSetting.model_type == model_type.to_origin_model_type(),
  441. ProviderModelSetting.model_name == model,
  442. )
  443. .first()
  444. )
  445. if model_setting:
  446. model_setting.enabled = False
  447. model_setting.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  448. db.session.commit()
  449. else:
  450. model_setting = ProviderModelSetting()
  451. model_setting.tenant_id = self.tenant_id
  452. model_setting.provider_name = self.provider.provider
  453. model_setting.model_type = model_type.to_origin_model_type()
  454. model_setting.model_name = model
  455. model_setting.enabled = False
  456. db.session.add(model_setting)
  457. db.session.commit()
  458. return model_setting
  459. def get_provider_model_setting(self, model_type: ModelType, model: str) -> Optional[ProviderModelSetting]:
  460. """
  461. Get provider model setting.
  462. :param model_type: model type
  463. :param model: model name
  464. :return:
  465. """
  466. return (
  467. db.session.query(ProviderModelSetting)
  468. .filter(
  469. ProviderModelSetting.tenant_id == self.tenant_id,
  470. ProviderModelSetting.provider_name == self.provider.provider,
  471. ProviderModelSetting.model_type == model_type.to_origin_model_type(),
  472. ProviderModelSetting.model_name == model,
  473. )
  474. .first()
  475. )
  476. def enable_model_load_balancing(self, model_type: ModelType, model: str) -> ProviderModelSetting:
  477. """
  478. Enable model load balancing.
  479. :param model_type: model type
  480. :param model: model name
  481. :return:
  482. """
  483. load_balancing_config_count = (
  484. db.session.query(LoadBalancingModelConfig)
  485. .filter(
  486. LoadBalancingModelConfig.tenant_id == self.tenant_id,
  487. LoadBalancingModelConfig.provider_name == self.provider.provider,
  488. LoadBalancingModelConfig.model_type == model_type.to_origin_model_type(),
  489. LoadBalancingModelConfig.model_name == model,
  490. )
  491. .count()
  492. )
  493. if load_balancing_config_count <= 1:
  494. raise ValueError("Model load balancing configuration must be more than 1.")
  495. model_setting = (
  496. db.session.query(ProviderModelSetting)
  497. .filter(
  498. ProviderModelSetting.tenant_id == self.tenant_id,
  499. ProviderModelSetting.provider_name == self.provider.provider,
  500. ProviderModelSetting.model_type == model_type.to_origin_model_type(),
  501. ProviderModelSetting.model_name == model,
  502. )
  503. .first()
  504. )
  505. if model_setting:
  506. model_setting.load_balancing_enabled = True
  507. model_setting.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  508. db.session.commit()
  509. else:
  510. model_setting = ProviderModelSetting()
  511. model_setting.tenant_id = self.tenant_id
  512. model_setting.provider_name = self.provider.provider
  513. model_setting.model_type = model_type.to_origin_model_type()
  514. model_setting.model_name = model
  515. model_setting.load_balancing_enabled = True
  516. db.session.add(model_setting)
  517. db.session.commit()
  518. return model_setting
  519. def disable_model_load_balancing(self, model_type: ModelType, model: str) -> ProviderModelSetting:
  520. """
  521. Disable model load balancing.
  522. :param model_type: model type
  523. :param model: model name
  524. :return:
  525. """
  526. model_setting = (
  527. db.session.query(ProviderModelSetting)
  528. .filter(
  529. ProviderModelSetting.tenant_id == self.tenant_id,
  530. ProviderModelSetting.provider_name == self.provider.provider,
  531. ProviderModelSetting.model_type == model_type.to_origin_model_type(),
  532. ProviderModelSetting.model_name == model,
  533. )
  534. .first()
  535. )
  536. if model_setting:
  537. model_setting.load_balancing_enabled = False
  538. model_setting.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  539. db.session.commit()
  540. else:
  541. model_setting = ProviderModelSetting()
  542. model_setting.tenant_id = self.tenant_id
  543. model_setting.provider_name = self.provider.provider
  544. model_setting.model_type = model_type.to_origin_model_type()
  545. model_setting.model_name = model
  546. model_setting.load_balancing_enabled = False
  547. db.session.add(model_setting)
  548. db.session.commit()
  549. return model_setting
  550. def get_model_type_instance(self, model_type: ModelType) -> AIModel:
  551. """
  552. Get current model type instance.
  553. :param model_type: model type
  554. :return:
  555. """
  556. model_provider_factory = ModelProviderFactory(self.tenant_id)
  557. # Get model instance of LLM
  558. return model_provider_factory.get_model_type_instance(provider=self.provider.provider, model_type=model_type)
  559. def get_model_schema(self, model_type: ModelType, model: str, credentials: dict) -> AIModelEntity | None:
  560. """
  561. Get model schema
  562. """
  563. model_provider_factory = ModelProviderFactory(self.tenant_id)
  564. return model_provider_factory.get_model_schema(
  565. provider=self.provider.provider, model_type=model_type, model=model, credentials=credentials
  566. )
  567. def switch_preferred_provider_type(self, provider_type: ProviderType) -> None:
  568. """
  569. Switch preferred provider type.
  570. :param provider_type:
  571. :return:
  572. """
  573. if provider_type == self.preferred_provider_type:
  574. return
  575. if provider_type == ProviderType.SYSTEM and not self.system_configuration.enabled:
  576. return
  577. # get preferred provider
  578. preferred_model_provider = (
  579. db.session.query(TenantPreferredModelProvider)
  580. .filter(
  581. TenantPreferredModelProvider.tenant_id == self.tenant_id,
  582. TenantPreferredModelProvider.provider_name == self.provider.provider,
  583. )
  584. .first()
  585. )
  586. if preferred_model_provider:
  587. preferred_model_provider.preferred_provider_type = provider_type.value
  588. else:
  589. preferred_model_provider = TenantPreferredModelProvider()
  590. preferred_model_provider.tenant_id = self.tenant_id
  591. preferred_model_provider.provider_name = self.provider.provider
  592. preferred_model_provider.preferred_provider_type = provider_type.value
  593. db.session.add(preferred_model_provider)
  594. db.session.commit()
  595. def extract_secret_variables(self, credential_form_schemas: list[CredentialFormSchema]) -> list[str]:
  596. """
  597. Extract secret input form variables.
  598. :param credential_form_schemas:
  599. :return:
  600. """
  601. secret_input_form_variables = []
  602. for credential_form_schema in credential_form_schemas:
  603. if credential_form_schema.type == FormType.SECRET_INPUT:
  604. secret_input_form_variables.append(credential_form_schema.variable)
  605. return secret_input_form_variables
  606. def obfuscated_credentials(self, credentials: dict, credential_form_schemas: list[CredentialFormSchema]) -> dict:
  607. """
  608. Obfuscated credentials.
  609. :param credentials: credentials
  610. :param credential_form_schemas: credential form schemas
  611. :return:
  612. """
  613. # Get provider credential secret variables
  614. credential_secret_variables = self.extract_secret_variables(credential_form_schemas)
  615. # Obfuscate provider credentials
  616. copy_credentials = credentials.copy()
  617. for key, value in copy_credentials.items():
  618. if key in credential_secret_variables:
  619. copy_credentials[key] = encrypter.obfuscated_token(value)
  620. return copy_credentials
  621. def get_provider_model(
  622. self, model_type: ModelType, model: str, only_active: bool = False
  623. ) -> Optional[ModelWithProviderEntity]:
  624. """
  625. Get provider model.
  626. :param model_type: model type
  627. :param model: model name
  628. :param only_active: return active model only
  629. :return:
  630. """
  631. provider_models = self.get_provider_models(model_type, only_active)
  632. for provider_model in provider_models:
  633. if provider_model.model == model:
  634. return provider_model
  635. return None
  636. def get_provider_models(
  637. self, model_type: Optional[ModelType] = None, only_active: bool = False
  638. ) -> list[ModelWithProviderEntity]:
  639. """
  640. Get provider models.
  641. :param model_type: model type
  642. :param only_active: only active models
  643. :return:
  644. """
  645. model_provider_factory = ModelProviderFactory(self.tenant_id)
  646. provider_schema = model_provider_factory.get_provider_schema(self.provider.provider)
  647. model_types: list[ModelType] = []
  648. if model_type:
  649. model_types.append(model_type)
  650. else:
  651. model_types = list(provider_schema.supported_model_types)
  652. # Group model settings by model type and model
  653. model_setting_map: defaultdict[ModelType, dict[str, ModelSettings]] = defaultdict(dict)
  654. for model_setting in self.model_settings:
  655. model_setting_map[model_setting.model_type][model_setting.model] = model_setting
  656. if self.using_provider_type == ProviderType.SYSTEM:
  657. provider_models = self._get_system_provider_models(
  658. model_types=model_types, provider_schema=provider_schema, model_setting_map=model_setting_map
  659. )
  660. else:
  661. provider_models = self._get_custom_provider_models(
  662. model_types=model_types, provider_schema=provider_schema, model_setting_map=model_setting_map
  663. )
  664. if only_active:
  665. provider_models = [m for m in provider_models if m.status == ModelStatus.ACTIVE]
  666. # resort provider_models
  667. return sorted(provider_models, key=lambda x: x.model_type.value)
  668. def _get_system_provider_models(
  669. self,
  670. model_types: Sequence[ModelType],
  671. provider_schema: ProviderEntity,
  672. model_setting_map: dict[ModelType, dict[str, ModelSettings]],
  673. ) -> list[ModelWithProviderEntity]:
  674. """
  675. Get system provider models.
  676. :param model_types: model types
  677. :param provider_schema: provider schema
  678. :param model_setting_map: model setting map
  679. :return:
  680. """
  681. provider_models = []
  682. for model_type in model_types:
  683. for m in provider_schema.models:
  684. if m.model_type != model_type:
  685. continue
  686. status = ModelStatus.ACTIVE
  687. if m.model in model_setting_map:
  688. model_setting = model_setting_map[m.model_type][m.model]
  689. if model_setting.enabled is False:
  690. status = ModelStatus.DISABLED
  691. provider_models.append(
  692. ModelWithProviderEntity(
  693. model=m.model,
  694. label=m.label,
  695. model_type=m.model_type,
  696. features=m.features,
  697. fetch_from=m.fetch_from,
  698. model_properties=m.model_properties,
  699. deprecated=m.deprecated,
  700. provider=SimpleModelProviderEntity(self.provider),
  701. status=status,
  702. )
  703. )
  704. if self.provider.provider not in original_provider_configurate_methods:
  705. original_provider_configurate_methods[self.provider.provider] = []
  706. for configurate_method in provider_schema.configurate_methods:
  707. original_provider_configurate_methods[self.provider.provider].append(configurate_method)
  708. should_use_custom_model = False
  709. if original_provider_configurate_methods[self.provider.provider] == [ConfigurateMethod.CUSTOMIZABLE_MODEL]:
  710. should_use_custom_model = True
  711. for quota_configuration in self.system_configuration.quota_configurations:
  712. if self.system_configuration.current_quota_type != quota_configuration.quota_type:
  713. continue
  714. restrict_models = quota_configuration.restrict_models
  715. if len(restrict_models) == 0:
  716. break
  717. if should_use_custom_model:
  718. if original_provider_configurate_methods[self.provider.provider] == [
  719. ConfigurateMethod.CUSTOMIZABLE_MODEL
  720. ]:
  721. # only customizable model
  722. for restrict_model in restrict_models:
  723. copy_credentials = (
  724. self.system_configuration.credentials.copy()
  725. if self.system_configuration.credentials
  726. else {}
  727. )
  728. if restrict_model.base_model_name:
  729. copy_credentials["base_model_name"] = restrict_model.base_model_name
  730. try:
  731. custom_model_schema = self.get_model_schema(
  732. model_type=restrict_model.model_type,
  733. model=restrict_model.model,
  734. credentials=copy_credentials,
  735. )
  736. except Exception as ex:
  737. logger.warning(f"get custom model schema failed, {ex}")
  738. if not custom_model_schema:
  739. continue
  740. if custom_model_schema.model_type not in model_types:
  741. continue
  742. status = ModelStatus.ACTIVE
  743. if (
  744. custom_model_schema.model_type in model_setting_map
  745. and custom_model_schema.model in model_setting_map[custom_model_schema.model_type]
  746. ):
  747. model_setting = model_setting_map[custom_model_schema.model_type][
  748. custom_model_schema.model
  749. ]
  750. if model_setting.enabled is False:
  751. status = ModelStatus.DISABLED
  752. provider_models.append(
  753. ModelWithProviderEntity(
  754. model=custom_model_schema.model,
  755. label=custom_model_schema.label,
  756. model_type=custom_model_schema.model_type,
  757. features=custom_model_schema.features,
  758. fetch_from=FetchFrom.PREDEFINED_MODEL,
  759. model_properties=custom_model_schema.model_properties,
  760. deprecated=custom_model_schema.deprecated,
  761. provider=SimpleModelProviderEntity(self.provider),
  762. status=status,
  763. )
  764. )
  765. # if llm name not in restricted llm list, remove it
  766. restrict_model_names = [rm.model for rm in restrict_models]
  767. for model in provider_models:
  768. if model.model_type == ModelType.LLM and model.model not in restrict_model_names:
  769. model.status = ModelStatus.NO_PERMISSION
  770. elif not quota_configuration.is_valid:
  771. model.status = ModelStatus.QUOTA_EXCEEDED
  772. return provider_models
  773. def _get_custom_provider_models(
  774. self,
  775. model_types: Sequence[ModelType],
  776. provider_schema: ProviderEntity,
  777. model_setting_map: dict[ModelType, dict[str, ModelSettings]],
  778. ) -> list[ModelWithProviderEntity]:
  779. """
  780. Get custom provider models.
  781. :param model_types: model types
  782. :param provider_schema: provider schema
  783. :param model_setting_map: model setting map
  784. :return:
  785. """
  786. provider_models = []
  787. credentials = None
  788. if self.custom_configuration.provider:
  789. credentials = self.custom_configuration.provider.credentials
  790. for model_type in model_types:
  791. if model_type not in self.provider.supported_model_types:
  792. continue
  793. for m in provider_schema.models:
  794. if m.model_type != model_type:
  795. continue
  796. status = ModelStatus.ACTIVE if credentials else ModelStatus.NO_CONFIGURE
  797. load_balancing_enabled = False
  798. if m.model_type in model_setting_map and m.model in model_setting_map[m.model_type]:
  799. model_setting = model_setting_map[m.model_type][m.model]
  800. if model_setting.enabled is False:
  801. status = ModelStatus.DISABLED
  802. if len(model_setting.load_balancing_configs) > 1:
  803. load_balancing_enabled = True
  804. provider_models.append(
  805. ModelWithProviderEntity(
  806. model=m.model,
  807. label=m.label,
  808. model_type=m.model_type,
  809. features=m.features,
  810. fetch_from=m.fetch_from,
  811. model_properties=m.model_properties,
  812. deprecated=m.deprecated,
  813. provider=SimpleModelProviderEntity(self.provider),
  814. status=status,
  815. load_balancing_enabled=load_balancing_enabled,
  816. )
  817. )
  818. # custom models
  819. for model_configuration in self.custom_configuration.models:
  820. if model_configuration.model_type not in model_types:
  821. continue
  822. try:
  823. custom_model_schema = self.get_model_schema(
  824. model_type=model_configuration.model_type,
  825. model=model_configuration.model,
  826. credentials=model_configuration.credentials,
  827. )
  828. except Exception as ex:
  829. logger.warning(f"get custom model schema failed, {ex}")
  830. continue
  831. if not custom_model_schema:
  832. continue
  833. status = ModelStatus.ACTIVE
  834. load_balancing_enabled = False
  835. if (
  836. custom_model_schema.model_type in model_setting_map
  837. and custom_model_schema.model in model_setting_map[custom_model_schema.model_type]
  838. ):
  839. model_setting = model_setting_map[custom_model_schema.model_type][custom_model_schema.model]
  840. if model_setting.enabled is False:
  841. status = ModelStatus.DISABLED
  842. if len(model_setting.load_balancing_configs) > 1:
  843. load_balancing_enabled = True
  844. provider_models.append(
  845. ModelWithProviderEntity(
  846. model=custom_model_schema.model,
  847. label=custom_model_schema.label,
  848. model_type=custom_model_schema.model_type,
  849. features=custom_model_schema.features,
  850. fetch_from=FetchFrom.CUSTOMIZABLE_MODEL,
  851. model_properties=custom_model_schema.model_properties,
  852. deprecated=custom_model_schema.deprecated,
  853. provider=SimpleModelProviderEntity(self.provider),
  854. status=status,
  855. load_balancing_enabled=load_balancing_enabled,
  856. )
  857. )
  858. return provider_models
  859. class ProviderConfigurations(BaseModel):
  860. """
  861. Model class for provider configuration dict.
  862. """
  863. tenant_id: str
  864. configurations: dict[str, ProviderConfiguration] = Field(default_factory=dict)
  865. def __init__(self, tenant_id: str):
  866. super().__init__(tenant_id=tenant_id)
  867. def get_models(
  868. self, provider: Optional[str] = None, model_type: Optional[ModelType] = None, only_active: bool = False
  869. ) -> list[ModelWithProviderEntity]:
  870. """
  871. Get available models.
  872. If preferred provider type is `system`:
  873. Get the current **system mode** if provider supported,
  874. if all system modes are not available (no quota), it is considered to be the **custom credential mode**.
  875. If there is no model configured in custom mode, it is treated as no_configure.
  876. system > custom > no_configure
  877. If preferred provider type is `custom`:
  878. If custom credentials are configured, it is treated as custom mode.
  879. Otherwise, get the current **system mode** if supported,
  880. If all system modes are not available (no quota), it is treated as no_configure.
  881. custom > system > no_configure
  882. If real mode is `system`, use system credentials to get models,
  883. paid quotas > provider free quotas > system free quotas
  884. include pre-defined models (exclude GPT-4, status marked as `no_permission`).
  885. If real mode is `custom`, use workspace custom credentials to get models,
  886. include pre-defined models, custom models(manual append).
  887. If real mode is `no_configure`, only return pre-defined models from `model runtime`.
  888. (model status marked as `no_configure` if preferred provider type is `custom` otherwise `quota_exceeded`)
  889. model status marked as `active` is available.
  890. :param provider: provider name
  891. :param model_type: model type
  892. :param only_active: only active models
  893. :return:
  894. """
  895. all_models = []
  896. for provider_configuration in self.values():
  897. if provider and provider_configuration.provider.provider != provider:
  898. continue
  899. all_models.extend(provider_configuration.get_provider_models(model_type, only_active))
  900. return all_models
  901. def to_list(self) -> list[ProviderConfiguration]:
  902. """
  903. Convert to list.
  904. :return:
  905. """
  906. return list(self.values())
  907. def __getitem__(self, key):
  908. if "/" not in key:
  909. key = str(ModelProviderID(key))
  910. return self.configurations[key]
  911. def __setitem__(self, key, value):
  912. self.configurations[key] = value
  913. def __iter__(self):
  914. return iter(self.configurations)
  915. def values(self) -> Iterator[ProviderConfiguration]:
  916. return iter(self.configurations.values())
  917. def get(self, key, default=None) -> ProviderConfiguration | None:
  918. if "/" not in key:
  919. key = str(ModelProviderID(key))
  920. return self.configurations.get(key, default) # type: ignore
  921. class ProviderModelBundle(BaseModel):
  922. """
  923. Provider model bundle.
  924. """
  925. configuration: ProviderConfiguration
  926. model_type_instance: AIModel
  927. # pydantic configs
  928. model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())