provider_configuration.py 31 KB

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