llm.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # coding=utf-8
  2. """
  3. @project: MaxKB
  4. @Author:虎
  5. @file: llm.py
  6. @date:2024/7/11 18:19
  7. @desc:
  8. """
  9. from typing import Dict
  10. from django.utils.translation import gettext_lazy as _, gettext
  11. from common import forms
  12. from common.exception.app_exception import AppApiException
  13. from common.forms import BaseForm, TooltipLabel
  14. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  15. class OllamaLLMModelParams(BaseForm):
  16. temperature = forms.SliderField(TooltipLabel(_('Temperature'),
  17. _('Higher values make the output more random, while lower values make it more focused and deterministic')),
  18. required=True, default_value=0.3,
  19. _min=0.1,
  20. _max=1.0,
  21. _step=0.01,
  22. precision=2)
  23. num_predict = forms.SliderField(
  24. TooltipLabel(_('Output the maximum Tokens'),
  25. _('Specify the maximum number of tokens that the model can generate')),
  26. required=True, default_value=1024,
  27. _min=1,
  28. _max=100000,
  29. _step=1,
  30. precision=0)
  31. class OllamaLLMModelCredential(BaseForm, BaseModelCredential):
  32. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  33. raise_exception=False):
  34. model_type_list = provider.get_model_type_list()
  35. if not any(list(filter(lambda mt: mt.get('value') == model_type, model_type_list))):
  36. raise AppApiException(ValidCode.valid_error.value,
  37. gettext('{model_type} Model type is not supported').format(model_type=model_type))
  38. try:
  39. model_list = provider.get_base_model_list(model_credential.get('api_base'))
  40. except Exception as e:
  41. raise AppApiException(ValidCode.valid_error.value, gettext('API domain name is invalid'))
  42. exist = [model for model in (model_list.get('models') if model_list.get('models') is not None else []) if
  43. model.get('model') == model_name or model.get('model').replace(":latest", "") == model_name]
  44. if len(exist) == 0:
  45. raise AppApiException(ValidCode.model_not_fount,
  46. gettext('The model does not exist, please download the model first'))
  47. return True
  48. def encryption_dict(self, model_info: Dict[str, object]):
  49. return {**model_info, 'api_key': super().encryption(model_info.get('api_key', ''))}
  50. def build_model(self, model_info: Dict[str, object]):
  51. for key in ['api_key', 'model']:
  52. if key not in model_info:
  53. raise AppApiException(500, gettext('{key} is required').format(key=key))
  54. self.api_key = model_info.get('api_key')
  55. return self
  56. api_base = forms.TextInputField('API URL', required=True)
  57. api_key = forms.PasswordInputField('API Key', required=True)
  58. def get_model_params_setting_form(self, model_name):
  59. return OllamaLLMModelParams()