reranker.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from typing import Dict
  2. from langchain_core.documents import Document
  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 django.utils.translation import gettext_lazy as _
  8. from models_provider.impl.vllm_model_provider.model.reranker import VllmBgeReranker
  9. from common.utils.logger import maxkb_logger
  10. class VllmRerankerCredential(BaseForm, BaseModelCredential):
  11. api_url = forms.TextInputField('API URL', required=True)
  12. api_key = forms.PasswordInputField('API Key', required=True)
  13. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  14. raise_exception=True):
  15. model_type_list = provider.get_model_type_list()
  16. if not any(list(filter(lambda mt: mt.get('value') == model_type, model_type_list))):
  17. raise AppApiException(ValidCode.valid_error.value,
  18. _('{model_type} Model type is not supported').format(model_type=model_type))
  19. for key in ['api_url', 'api_key']:
  20. if key not in model_credential:
  21. if raise_exception:
  22. raise AppApiException(ValidCode.valid_error.value, _('{key} is required').format(key=key))
  23. else:
  24. return False
  25. try:
  26. model: VllmBgeReranker = provider.get_model(model_type, model_name, model_credential)
  27. test_text = str(_('Hello'))
  28. model.compress_documents([Document(page_content=test_text)], test_text)
  29. except Exception as e:
  30. maxkb_logger.error(f'Exception: {e}', exc_info=True)
  31. if isinstance(e, AppApiException):
  32. raise e
  33. if raise_exception:
  34. raise AppApiException(
  35. ValidCode.valid_error.value,
  36. _('Verification failed, please check whether the parameters are correct: {error}').format(
  37. error=str(e))
  38. )
  39. return False
  40. return True
  41. def encryption_dict(self, model_info: Dict[str, object]):
  42. return {**model_info, 'api_key': super().encryption(model_info.get('api_key', ''))}