provider_configuration.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. import datetime
  2. import json
  3. import logging
  4. from json import JSONDecodeError
  5. from typing import Dict, Iterator, List, Optional, Tuple
  6. from core.entities.model_entities import ModelStatus, ModelWithProviderEntity, SimpleModelProviderEntity
  7. from core.entities.provider_entities import CustomConfiguration, SystemConfiguration, SystemConfigurationStatus
  8. from core.helper import encrypter
  9. from core.helper.model_provider_cache import ProviderCredentialsCache, ProviderCredentialsCacheType
  10. from core.model_runtime.entities.model_entities import FetchFrom, ModelType
  11. from core.model_runtime.entities.provider_entities import (ConfigurateMethod, CredentialFormSchema, FormType,
  12. ProviderEntity)
  13. from core.model_runtime.model_providers import model_provider_factory
  14. from core.model_runtime.model_providers.__base.ai_model import AIModel
  15. from core.model_runtime.model_providers.__base.model_provider import ModelProvider
  16. from core.model_runtime.utils import encoders
  17. from extensions.ext_database import db
  18. from models.provider import Provider, ProviderModel, ProviderType, TenantPreferredModelProvider
  19. from pydantic import BaseModel
  20. logger = logging.getLogger(__name__)
  21. original_provider_configurate_methods = {}
  22. class ProviderConfiguration(BaseModel):
  23. """
  24. Model class for provider configuration.
  25. """
  26. tenant_id: str
  27. provider: ProviderEntity
  28. preferred_provider_type: ProviderType
  29. using_provider_type: ProviderType
  30. system_configuration: SystemConfiguration
  31. custom_configuration: CustomConfiguration
  32. def __init__(self, **data):
  33. super().__init__(**data)
  34. if self.provider.provider not in original_provider_configurate_methods:
  35. original_provider_configurate_methods[self.provider.provider] = []
  36. for configurate_method in self.provider.configurate_methods:
  37. original_provider_configurate_methods[self.provider.provider].append(configurate_method)
  38. if original_provider_configurate_methods[self.provider.provider] == [ConfigurateMethod.CUSTOMIZABLE_MODEL]:
  39. if (any([len(quota_configuration.restrict_models) > 0
  40. for quota_configuration in self.system_configuration.quota_configurations])
  41. and ConfigurateMethod.PREDEFINED_MODEL not in self.provider.configurate_methods):
  42. self.provider.configurate_methods.append(ConfigurateMethod.PREDEFINED_MODEL)
  43. def get_current_credentials(self, model_type: ModelType, model: str) -> Optional[dict]:
  44. """
  45. Get current credentials.
  46. :param model_type: model type
  47. :param model: model name
  48. :return:
  49. """
  50. if self.using_provider_type == ProviderType.SYSTEM:
  51. restrict_models = []
  52. for quota_configuration in self.system_configuration.quota_configurations:
  53. if self.system_configuration.current_quota_type != quota_configuration.quota_type:
  54. continue
  55. restrict_models = quota_configuration.restrict_models
  56. copy_credentials = self.system_configuration.credentials.copy()
  57. if restrict_models:
  58. for restrict_model in restrict_models:
  59. if (restrict_model.model_type == model_type
  60. and restrict_model.model == model
  61. and restrict_model.base_model_name):
  62. copy_credentials['base_model_name'] = restrict_model.base_model_name
  63. return copy_credentials
  64. else:
  65. if self.custom_configuration.models:
  66. for model_configuration in self.custom_configuration.models:
  67. if model_configuration.model_type == model_type and model_configuration.model == model:
  68. return model_configuration.credentials
  69. if self.custom_configuration.provider:
  70. return self.custom_configuration.provider.credentials
  71. else:
  72. return None
  73. def get_system_configuration_status(self) -> SystemConfigurationStatus:
  74. """
  75. Get system configuration status.
  76. :return:
  77. """
  78. if self.system_configuration.enabled is False:
  79. return SystemConfigurationStatus.UNSUPPORTED
  80. current_quota_type = self.system_configuration.current_quota_type
  81. current_quota_configuration = next(
  82. (q for q in self.system_configuration.quota_configurations if q.quota_type == current_quota_type),
  83. None
  84. )
  85. return SystemConfigurationStatus.ACTIVE if current_quota_configuration.is_valid else \
  86. SystemConfigurationStatus.QUOTA_EXCEEDED
  87. def is_custom_configuration_available(self) -> bool:
  88. """
  89. Check custom configuration available.
  90. :return:
  91. """
  92. return (self.custom_configuration.provider is not None
  93. or len(self.custom_configuration.models) > 0)
  94. def get_custom_credentials(self, obfuscated: bool = False) -> Optional[dict]:
  95. """
  96. Get custom credentials.
  97. :param obfuscated: obfuscated secret data in credentials
  98. :return:
  99. """
  100. if self.custom_configuration.provider is None:
  101. return None
  102. credentials = self.custom_configuration.provider.credentials
  103. if not obfuscated:
  104. return credentials
  105. # Obfuscate credentials
  106. return self._obfuscated_credentials(
  107. credentials=credentials,
  108. credential_form_schemas=self.provider.provider_credential_schema.credential_form_schemas
  109. if self.provider.provider_credential_schema else []
  110. )
  111. def custom_credentials_validate(self, credentials: dict) -> Tuple[Provider, dict]:
  112. """
  113. Validate custom credentials.
  114. :param credentials: provider credentials
  115. :return:
  116. """
  117. # get provider
  118. provider_record = db.session.query(Provider) \
  119. .filter(
  120. Provider.tenant_id == self.tenant_id,
  121. Provider.provider_name == self.provider.provider,
  122. Provider.provider_type == ProviderType.CUSTOM.value
  123. ).first()
  124. # Get provider credential secret variables
  125. provider_credential_secret_variables = self._extract_secret_variables(
  126. self.provider.provider_credential_schema.credential_form_schemas
  127. if self.provider.provider_credential_schema else []
  128. )
  129. if provider_record:
  130. try:
  131. # fix origin data
  132. if provider_record.encrypted_config:
  133. if not provider_record.encrypted_config.startswith("{"):
  134. original_credentials = {
  135. "openai_api_key": provider_record.encrypted_config
  136. }
  137. else:
  138. original_credentials = json.loads(provider_record.encrypted_config)
  139. else:
  140. original_credentials = {}
  141. except JSONDecodeError:
  142. original_credentials = {}
  143. # encrypt credentials
  144. for key, value in credentials.items():
  145. if key in provider_credential_secret_variables:
  146. # if send [__HIDDEN__] in secret input, it will be same as original value
  147. if value == '[__HIDDEN__]' and key in original_credentials:
  148. credentials[key] = encrypter.decrypt_token(self.tenant_id, original_credentials[key])
  149. credentials = model_provider_factory.provider_credentials_validate(
  150. self.provider.provider,
  151. credentials
  152. )
  153. for key, value in credentials.items():
  154. if key in provider_credential_secret_variables:
  155. credentials[key] = encrypter.encrypt_token(self.tenant_id, value)
  156. return provider_record, credentials
  157. def add_or_update_custom_credentials(self, credentials: dict) -> None:
  158. """
  159. Add or update custom provider credentials.
  160. :param credentials:
  161. :return:
  162. """
  163. # validate custom provider config
  164. provider_record, credentials = self.custom_credentials_validate(credentials)
  165. # save provider
  166. # Note: Do not switch the preferred provider, which allows users to use quotas first
  167. if provider_record:
  168. provider_record.encrypted_config = json.dumps(credentials)
  169. provider_record.is_valid = True
  170. provider_record.updated_at = datetime.datetime.utcnow()
  171. db.session.commit()
  172. else:
  173. provider_record = Provider(
  174. tenant_id=self.tenant_id,
  175. provider_name=self.provider.provider,
  176. provider_type=ProviderType.CUSTOM.value,
  177. encrypted_config=json.dumps(credentials),
  178. is_valid=True
  179. )
  180. db.session.add(provider_record)
  181. db.session.commit()
  182. provider_model_credentials_cache = ProviderCredentialsCache(
  183. tenant_id=self.tenant_id,
  184. identity_id=provider_record.id,
  185. cache_type=ProviderCredentialsCacheType.PROVIDER
  186. )
  187. provider_model_credentials_cache.delete()
  188. self.switch_preferred_provider_type(ProviderType.CUSTOM)
  189. def delete_custom_credentials(self) -> None:
  190. """
  191. Delete custom provider credentials.
  192. :return:
  193. """
  194. # get provider
  195. provider_record = db.session.query(Provider) \
  196. .filter(
  197. Provider.tenant_id == self.tenant_id,
  198. Provider.provider_name == self.provider.provider,
  199. Provider.provider_type == ProviderType.CUSTOM.value
  200. ).first()
  201. # delete provider
  202. if provider_record:
  203. self.switch_preferred_provider_type(ProviderType.SYSTEM)
  204. db.session.delete(provider_record)
  205. db.session.commit()
  206. provider_model_credentials_cache = ProviderCredentialsCache(
  207. tenant_id=self.tenant_id,
  208. identity_id=provider_record.id,
  209. cache_type=ProviderCredentialsCacheType.PROVIDER
  210. )
  211. provider_model_credentials_cache.delete()
  212. def get_custom_model_credentials(self, model_type: ModelType, model: str, obfuscated: bool = False) \
  213. -> Optional[dict]:
  214. """
  215. Get custom model credentials.
  216. :param model_type: model type
  217. :param model: model name
  218. :param obfuscated: obfuscated secret data in credentials
  219. :return:
  220. """
  221. if not self.custom_configuration.models:
  222. return None
  223. for model_configuration in self.custom_configuration.models:
  224. if model_configuration.model_type == model_type and model_configuration.model == model:
  225. credentials = model_configuration.credentials
  226. if not obfuscated:
  227. return credentials
  228. # Obfuscate credentials
  229. return self._obfuscated_credentials(
  230. credentials=credentials,
  231. credential_form_schemas=self.provider.model_credential_schema.credential_form_schemas
  232. if self.provider.model_credential_schema else []
  233. )
  234. return None
  235. def custom_model_credentials_validate(self, model_type: ModelType, model: str, credentials: dict) \
  236. -> Tuple[ProviderModel, dict]:
  237. """
  238. Validate custom model credentials.
  239. :param model_type: model type
  240. :param model: model name
  241. :param credentials: model credentials
  242. :return:
  243. """
  244. # get provider model
  245. provider_model_record = db.session.query(ProviderModel) \
  246. .filter(
  247. ProviderModel.tenant_id == self.tenant_id,
  248. ProviderModel.provider_name == self.provider.provider,
  249. ProviderModel.model_name == model,
  250. ProviderModel.model_type == model_type.to_origin_model_type()
  251. ).first()
  252. # Get provider credential secret variables
  253. provider_credential_secret_variables = self._extract_secret_variables(
  254. self.provider.model_credential_schema.credential_form_schemas
  255. if self.provider.model_credential_schema else []
  256. )
  257. if provider_model_record:
  258. try:
  259. original_credentials = json.loads(
  260. provider_model_record.encrypted_config) if provider_model_record.encrypted_config else {}
  261. except JSONDecodeError:
  262. original_credentials = {}
  263. # decrypt credentials
  264. for key, value in credentials.items():
  265. if key in provider_credential_secret_variables:
  266. # if send [__HIDDEN__] in secret input, it will be same as original value
  267. if value == '[__HIDDEN__]' and key in original_credentials:
  268. credentials[key] = encrypter.decrypt_token(self.tenant_id, original_credentials[key])
  269. credentials = model_provider_factory.model_credentials_validate(
  270. provider=self.provider.provider,
  271. model_type=model_type,
  272. model=model,
  273. credentials=credentials
  274. )
  275. for key, value in credentials.items():
  276. if key in provider_credential_secret_variables:
  277. credentials[key] = encrypter.encrypt_token(self.tenant_id, value)
  278. return provider_model_record, credentials
  279. def add_or_update_custom_model_credentials(self, model_type: ModelType, model: str, credentials: dict) -> None:
  280. """
  281. Add or update custom model credentials.
  282. :param model_type: model type
  283. :param model: model name
  284. :param credentials: model credentials
  285. :return:
  286. """
  287. # validate custom model config
  288. provider_model_record, credentials = self.custom_model_credentials_validate(model_type, model, credentials)
  289. # save provider model
  290. # Note: Do not switch the preferred provider, which allows users to use quotas first
  291. if provider_model_record:
  292. provider_model_record.encrypted_config = json.dumps(credentials)
  293. provider_model_record.is_valid = True
  294. provider_model_record.updated_at = datetime.datetime.utcnow()
  295. db.session.commit()
  296. else:
  297. provider_model_record = ProviderModel(
  298. tenant_id=self.tenant_id,
  299. provider_name=self.provider.provider,
  300. model_name=model,
  301. model_type=model_type.to_origin_model_type(),
  302. encrypted_config=json.dumps(credentials),
  303. is_valid=True
  304. )
  305. db.session.add(provider_model_record)
  306. db.session.commit()
  307. provider_model_credentials_cache = ProviderCredentialsCache(
  308. tenant_id=self.tenant_id,
  309. identity_id=provider_model_record.id,
  310. cache_type=ProviderCredentialsCacheType.MODEL
  311. )
  312. provider_model_credentials_cache.delete()
  313. def delete_custom_model_credentials(self, model_type: ModelType, model: str) -> None:
  314. """
  315. Delete custom model credentials.
  316. :param model_type: model type
  317. :param model: model name
  318. :return:
  319. """
  320. # get provider model
  321. provider_model_record = db.session.query(ProviderModel) \
  322. .filter(
  323. ProviderModel.tenant_id == self.tenant_id,
  324. ProviderModel.provider_name == self.provider.provider,
  325. ProviderModel.model_name == model,
  326. ProviderModel.model_type == model_type.to_origin_model_type()
  327. ).first()
  328. # delete provider model
  329. if provider_model_record:
  330. db.session.delete(provider_model_record)
  331. db.session.commit()
  332. provider_model_credentials_cache = ProviderCredentialsCache(
  333. tenant_id=self.tenant_id,
  334. identity_id=provider_model_record.id,
  335. cache_type=ProviderCredentialsCacheType.MODEL
  336. )
  337. provider_model_credentials_cache.delete()
  338. def get_provider_instance(self) -> ModelProvider:
  339. """
  340. Get provider instance.
  341. :return:
  342. """
  343. return model_provider_factory.get_provider_instance(self.provider.provider)
  344. def get_model_type_instance(self, model_type: ModelType) -> AIModel:
  345. """
  346. Get current model type instance.
  347. :param model_type: model type
  348. :return:
  349. """
  350. # Get provider instance
  351. provider_instance = self.get_provider_instance()
  352. # Get model instance of LLM
  353. return provider_instance.get_model_instance(model_type)
  354. def switch_preferred_provider_type(self, provider_type: ProviderType) -> None:
  355. """
  356. Switch preferred provider type.
  357. :param provider_type:
  358. :return:
  359. """
  360. if provider_type == self.preferred_provider_type:
  361. return
  362. if provider_type == ProviderType.SYSTEM and not self.system_configuration.enabled:
  363. return
  364. # get preferred provider
  365. preferred_model_provider = db.session.query(TenantPreferredModelProvider) \
  366. .filter(
  367. TenantPreferredModelProvider.tenant_id == self.tenant_id,
  368. TenantPreferredModelProvider.provider_name == self.provider.provider
  369. ).first()
  370. if preferred_model_provider:
  371. preferred_model_provider.preferred_provider_type = provider_type.value
  372. else:
  373. preferred_model_provider = TenantPreferredModelProvider(
  374. tenant_id=self.tenant_id,
  375. provider_name=self.provider.provider,
  376. preferred_provider_type=provider_type.value
  377. )
  378. db.session.add(preferred_model_provider)
  379. db.session.commit()
  380. def _extract_secret_variables(self, credential_form_schemas: list[CredentialFormSchema]) -> list[str]:
  381. """
  382. Extract secret input form variables.
  383. :param credential_form_schemas:
  384. :return:
  385. """
  386. secret_input_form_variables = []
  387. for credential_form_schema in credential_form_schemas:
  388. if credential_form_schema.type == FormType.SECRET_INPUT:
  389. secret_input_form_variables.append(credential_form_schema.variable)
  390. return secret_input_form_variables
  391. def _obfuscated_credentials(self, credentials: dict, credential_form_schemas: list[CredentialFormSchema]) -> dict:
  392. """
  393. Obfuscated credentials.
  394. :param credentials: credentials
  395. :param credential_form_schemas: credential form schemas
  396. :return:
  397. """
  398. # Get provider credential secret variables
  399. credential_secret_variables = self._extract_secret_variables(
  400. credential_form_schemas
  401. )
  402. # Obfuscate provider credentials
  403. copy_credentials = credentials.copy()
  404. for key, value in copy_credentials.items():
  405. if key in credential_secret_variables:
  406. copy_credentials[key] = encrypter.obfuscated_token(value)
  407. return copy_credentials
  408. def get_provider_model(self, model_type: ModelType,
  409. model: str,
  410. only_active: bool = False) -> Optional[ModelWithProviderEntity]:
  411. """
  412. Get provider model.
  413. :param model_type: model type
  414. :param model: model name
  415. :param only_active: return active model only
  416. :return:
  417. """
  418. provider_models = self.get_provider_models(model_type, only_active)
  419. for provider_model in provider_models:
  420. if provider_model.model == model:
  421. return provider_model
  422. return None
  423. def get_provider_models(self, model_type: Optional[ModelType] = None,
  424. only_active: bool = False) -> list[ModelWithProviderEntity]:
  425. """
  426. Get provider models.
  427. :param model_type: model type
  428. :param only_active: only active models
  429. :return:
  430. """
  431. provider_instance = self.get_provider_instance()
  432. model_types = []
  433. if model_type:
  434. model_types.append(model_type)
  435. else:
  436. model_types = provider_instance.get_provider_schema().supported_model_types
  437. if self.using_provider_type == ProviderType.SYSTEM:
  438. provider_models = self._get_system_provider_models(
  439. model_types=model_types,
  440. provider_instance=provider_instance
  441. )
  442. else:
  443. provider_models = self._get_custom_provider_models(
  444. model_types=model_types,
  445. provider_instance=provider_instance
  446. )
  447. if only_active:
  448. provider_models = [m for m in provider_models if m.status == ModelStatus.ACTIVE]
  449. # resort provider_models
  450. return sorted(provider_models, key=lambda x: x.model_type.value)
  451. def _get_system_provider_models(self,
  452. model_types: list[ModelType],
  453. provider_instance: ModelProvider) -> list[ModelWithProviderEntity]:
  454. """
  455. Get system provider models.
  456. :param model_types: model types
  457. :param provider_instance: provider instance
  458. :return:
  459. """
  460. provider_models = []
  461. for model_type in model_types:
  462. provider_models.extend(
  463. [
  464. ModelWithProviderEntity(
  465. model=m.model,
  466. label=m.label,
  467. model_type=m.model_type,
  468. features=m.features,
  469. fetch_from=m.fetch_from,
  470. model_properties=m.model_properties,
  471. deprecated=m.deprecated,
  472. provider=SimpleModelProviderEntity(self.provider),
  473. status=ModelStatus.ACTIVE
  474. )
  475. for m in provider_instance.models(model_type)
  476. ]
  477. )
  478. if self.provider.provider not in original_provider_configurate_methods:
  479. original_provider_configurate_methods[self.provider.provider] = []
  480. for configurate_method in provider_instance.get_provider_schema().configurate_methods:
  481. original_provider_configurate_methods[self.provider.provider].append(configurate_method)
  482. should_use_custom_model = False
  483. if original_provider_configurate_methods[self.provider.provider] == [ConfigurateMethod.CUSTOMIZABLE_MODEL]:
  484. should_use_custom_model = True
  485. for quota_configuration in self.system_configuration.quota_configurations:
  486. if self.system_configuration.current_quota_type != quota_configuration.quota_type:
  487. continue
  488. restrict_models = quota_configuration.restrict_models
  489. if len(restrict_models) == 0:
  490. break
  491. if should_use_custom_model:
  492. if original_provider_configurate_methods[self.provider.provider] == [ConfigurateMethod.CUSTOMIZABLE_MODEL]:
  493. # only customizable model
  494. for restrict_model in restrict_models:
  495. copy_credentials = self.system_configuration.credentials.copy()
  496. if restrict_model.base_model_name:
  497. copy_credentials['base_model_name'] = restrict_model.base_model_name
  498. try:
  499. custom_model_schema = (
  500. provider_instance.get_model_instance(restrict_model.model_type)
  501. .get_customizable_model_schema_from_credentials(
  502. restrict_model.model,
  503. copy_credentials
  504. )
  505. )
  506. except Exception as ex:
  507. logger.warning(f'get custom model schema failed, {ex}')
  508. continue
  509. if not custom_model_schema:
  510. continue
  511. if custom_model_schema.model_type not in model_types:
  512. continue
  513. provider_models.append(
  514. ModelWithProviderEntity(
  515. model=custom_model_schema.model,
  516. label=custom_model_schema.label,
  517. model_type=custom_model_schema.model_type,
  518. features=custom_model_schema.features,
  519. fetch_from=FetchFrom.PREDEFINED_MODEL,
  520. model_properties=custom_model_schema.model_properties,
  521. deprecated=custom_model_schema.deprecated,
  522. provider=SimpleModelProviderEntity(self.provider),
  523. status=ModelStatus.ACTIVE
  524. )
  525. )
  526. # if llm name not in restricted llm list, remove it
  527. restrict_model_names = [rm.model for rm in restrict_models]
  528. for m in provider_models:
  529. if m.model_type == ModelType.LLM and m.model not in restrict_model_names:
  530. m.status = ModelStatus.NO_PERMISSION
  531. elif not quota_configuration.is_valid:
  532. m.status = ModelStatus.QUOTA_EXCEEDED
  533. return provider_models
  534. def _get_custom_provider_models(self,
  535. model_types: list[ModelType],
  536. provider_instance: ModelProvider) -> list[ModelWithProviderEntity]:
  537. """
  538. Get custom provider models.
  539. :param model_types: model types
  540. :param provider_instance: provider instance
  541. :return:
  542. """
  543. provider_models = []
  544. credentials = None
  545. if self.custom_configuration.provider:
  546. credentials = self.custom_configuration.provider.credentials
  547. for model_type in model_types:
  548. if model_type not in self.provider.supported_model_types:
  549. continue
  550. models = provider_instance.models(model_type)
  551. for m in models:
  552. provider_models.append(
  553. ModelWithProviderEntity(
  554. model=m.model,
  555. label=m.label,
  556. model_type=m.model_type,
  557. features=m.features,
  558. fetch_from=m.fetch_from,
  559. model_properties=m.model_properties,
  560. deprecated=m.deprecated,
  561. provider=SimpleModelProviderEntity(self.provider),
  562. status=ModelStatus.ACTIVE if credentials else ModelStatus.NO_CONFIGURE
  563. )
  564. )
  565. # custom models
  566. for model_configuration in self.custom_configuration.models:
  567. if model_configuration.model_type not in model_types:
  568. continue
  569. try:
  570. custom_model_schema = (
  571. provider_instance.get_model_instance(model_configuration.model_type)
  572. .get_customizable_model_schema_from_credentials(
  573. model_configuration.model,
  574. model_configuration.credentials
  575. )
  576. )
  577. except Exception as ex:
  578. logger.warning(f'get custom model schema failed, {ex}')
  579. continue
  580. if not custom_model_schema:
  581. continue
  582. provider_models.append(
  583. ModelWithProviderEntity(
  584. model=custom_model_schema.model,
  585. label=custom_model_schema.label,
  586. model_type=custom_model_schema.model_type,
  587. features=custom_model_schema.features,
  588. fetch_from=custom_model_schema.fetch_from,
  589. model_properties=custom_model_schema.model_properties,
  590. deprecated=custom_model_schema.deprecated,
  591. provider=SimpleModelProviderEntity(self.provider),
  592. status=ModelStatus.ACTIVE
  593. )
  594. )
  595. return provider_models
  596. class ProviderConfigurations(BaseModel):
  597. """
  598. Model class for provider configuration dict.
  599. """
  600. tenant_id: str
  601. configurations: Dict[str, ProviderConfiguration] = {}
  602. def __init__(self, tenant_id: str):
  603. super().__init__(tenant_id=tenant_id)
  604. def get_models(self,
  605. provider: Optional[str] = None,
  606. model_type: Optional[ModelType] = None,
  607. only_active: bool = False) \
  608. -> list[ModelWithProviderEntity]:
  609. """
  610. Get available models.
  611. If preferred provider type is `system`:
  612. Get the current **system mode** if provider supported,
  613. if all system modes are not available (no quota), it is considered to be the **custom credential mode**.
  614. If there is no model configured in custom mode, it is treated as no_configure.
  615. system > custom > no_configure
  616. If preferred provider type is `custom`:
  617. If custom credentials are configured, it is treated as custom mode.
  618. Otherwise, get the current **system mode** if supported,
  619. If all system modes are not available (no quota), it is treated as no_configure.
  620. custom > system > no_configure
  621. If real mode is `system`, use system credentials to get models,
  622. paid quotas > provider free quotas > system free quotas
  623. include pre-defined models (exclude GPT-4, status marked as `no_permission`).
  624. If real mode is `custom`, use workspace custom credentials to get models,
  625. include pre-defined models, custom models(manual append).
  626. If real mode is `no_configure`, only return pre-defined models from `model runtime`.
  627. (model status marked as `no_configure` if preferred provider type is `custom` otherwise `quota_exceeded`)
  628. model status marked as `active` is available.
  629. :param provider: provider name
  630. :param model_type: model type
  631. :param only_active: only active models
  632. :return:
  633. """
  634. all_models = []
  635. for provider_configuration in self.values():
  636. if provider and provider_configuration.provider.provider != provider:
  637. continue
  638. all_models.extend(provider_configuration.get_provider_models(model_type, only_active))
  639. return all_models
  640. def to_list(self) -> List[ProviderConfiguration]:
  641. """
  642. Convert to list.
  643. :return:
  644. """
  645. return list(self.values())
  646. def __getitem__(self, key):
  647. return self.configurations[key]
  648. def __setitem__(self, key, value):
  649. self.configurations[key] = value
  650. def __iter__(self):
  651. return iter(self.configurations)
  652. def values(self) -> Iterator[ProviderConfiguration]:
  653. return self.configurations.values()
  654. def get(self, key, default=None):
  655. return self.configurations.get(key, default)
  656. class ProviderModelBundle(BaseModel):
  657. """
  658. Provider model bundle.
  659. """
  660. configuration: ProviderConfiguration
  661. provider_instance: ModelProvider
  662. model_type_instance: AIModel
  663. class Config:
  664. """Configuration for this pydantic object."""
  665. arbitrary_types_allowed = True