reranker.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # coding=utf-8
  2. """
  3. @project: MaxKB
  4. @Author:虎
  5. @file: reranker.py
  6. @date:2024/9/10 9:46
  7. @desc:
  8. """
  9. from typing import Dict
  10. from django.utils.translation import gettext as _
  11. from langchain_core.documents import Document
  12. from common import forms
  13. from common.exception.app_exception import AppApiException
  14. from common.forms import BaseForm
  15. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  16. class XInferenceRerankerModelCredential(BaseForm, BaseModelCredential):
  17. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  18. raise_exception=True):
  19. if not model_type == 'RERANKER':
  20. raise AppApiException(ValidCode.valid_error.value,
  21. _('{model_type} Model type is not supported').format(model_type=model_type))
  22. for key in ['server_url']:
  23. if key not in model_credential:
  24. if raise_exception:
  25. raise AppApiException(ValidCode.valid_error.value, _('{key} is required').format(key=key))
  26. else:
  27. return False
  28. try:
  29. model = provider.get_model(model_type, model_name, model_credential)
  30. model.compress_documents([Document(page_content=_('Hello'))], _('Hello'))
  31. except Exception as e:
  32. if isinstance(e, AppApiException):
  33. raise e
  34. if raise_exception:
  35. raise AppApiException(ValidCode.valid_error.value,
  36. _('Verification failed, please check whether the parameters are correct: {error}').format(
  37. error=str(e)))
  38. else:
  39. return False
  40. return True
  41. def encryption_dict(self, model_info: Dict[str, object]):
  42. return model_info
  43. server_url = forms.TextInputField('API URL', required=True)
  44. api_key = forms.PasswordInputField('API Key', required=False)