embedding.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from typing import Dict
  2. from django.utils.translation import gettext as _
  3. from common import forms
  4. from common.exception.app_exception import AppApiException
  5. from common.forms import BaseForm
  6. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  7. from common.utils.logger import maxkb_logger
  8. class TencentEmbeddingCredential(BaseForm, BaseModelCredential):
  9. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  10. raise_exception=True) -> bool:
  11. model_type_list = provider.get_model_type_list()
  12. if not any(list(filter(lambda mt: mt.get('value') == model_type, model_type_list))):
  13. raise AppApiException(ValidCode.valid_error.value,
  14. _('{model_type} Model type is not supported').format(model_type=model_type))
  15. self.valid_form(model_credential)
  16. try:
  17. model = provider.get_model(model_type, model_name, model_credential)
  18. model.embed_query(_('Hello'))
  19. except Exception as e:
  20. maxkb_logger.error(f'Exception: {e}', exc_info=True)
  21. if isinstance(e, AppApiException):
  22. raise e
  23. if raise_exception:
  24. raise AppApiException(ValidCode.valid_error.value,
  25. _('Verification failed, please check whether the parameters are correct: {error}').format(
  26. error=str(e)))
  27. else:
  28. return False
  29. return True
  30. def encryption_dict(self, model: Dict[str, object]) -> Dict[str, object]:
  31. encrypted_secret_key = super().encryption(model.get('SecretKey', ''))
  32. return {**model, 'SecretKey': encrypted_secret_key}
  33. SecretId = forms.PasswordInputField('SecretId', required=True)
  34. SecretKey = forms.PasswordInputField('SecretKey', required=True)