provider_configuration.py 41 KB

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