llm.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # coding=utf-8
  2. """
  3. @project: MaxKB
  4. @Author:虎
  5. @file: llm.py
  6. @date:2024/7/12 10:29
  7. @desc:
  8. """
  9. from typing import Dict
  10. from django.utils.translation import gettext_lazy as _, gettext
  11. from langchain_core.messages import HumanMessage
  12. from common import forms
  13. from common.exception.app_exception import AppApiException
  14. from common.forms import BaseForm, TooltipLabel
  15. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  16. from common.utils.logger import maxkb_logger
  17. class XunFeiLLMModelGeneralParams(BaseForm):
  18. temperature = forms.SliderField(TooltipLabel(_('Temperature'),
  19. _('Higher values make the output more random, while lower values make it more focused and deterministic')),
  20. required=True, default_value=0.5,
  21. _min=0.1,
  22. _max=1.0,
  23. _step=0.01,
  24. precision=2)
  25. max_tokens = forms.SliderField(
  26. TooltipLabel(_('Output the maximum Tokens'),
  27. _('Specify the maximum number of tokens that the model can generate')),
  28. required=True, default_value=4096,
  29. _min=1,
  30. _max=100000,
  31. _step=1,
  32. precision=0)
  33. class XunFeiLLMModelProParams(BaseForm):
  34. temperature = forms.SliderField(TooltipLabel(_('Temperature'),
  35. _('Higher values make the output more random, while lower values make it more focused and deterministic')),
  36. required=True, default_value=0.5,
  37. _min=0.1,
  38. _max=1.0,
  39. _step=0.01,
  40. precision=2)
  41. max_tokens = forms.SliderField(
  42. TooltipLabel(_('Output the maximum Tokens'),
  43. _('Specify the maximum number of tokens that the model can generate')),
  44. required=True, default_value=4096,
  45. _min=1,
  46. _max=100000,
  47. _step=1,
  48. precision=0)
  49. class XunFeiLLMModelCredential(BaseForm, BaseModelCredential):
  50. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  51. raise_exception=False):
  52. model_type_list = provider.get_model_type_list()
  53. if not any(list(filter(lambda mt: mt.get('value') == model_type, model_type_list))):
  54. raise AppApiException(ValidCode.valid_error.value,
  55. gettext('{model_type} Model type is not supported').format(model_type=model_type))
  56. for key in ['spark_api_url', 'spark_app_id', 'spark_api_key', 'spark_api_secret']:
  57. if key not in model_credential:
  58. if raise_exception:
  59. raise AppApiException(ValidCode.valid_error.value, gettext('{key} is required').format(key=key))
  60. else:
  61. return False
  62. try:
  63. model = provider.get_model(model_type, model_name, model_credential, **model_params)
  64. model.invoke([HumanMessage(content=gettext('Hello'))])
  65. except Exception as e:
  66. maxkb_logger.error(f'Exception: {e}', exc_info=True)
  67. if isinstance(e, AppApiException):
  68. raise e
  69. if raise_exception:
  70. raise AppApiException(ValidCode.valid_error.value,
  71. gettext(
  72. 'Verification failed, please check whether the parameters are correct: {error}').format(
  73. error=str(e)))
  74. else:
  75. return False
  76. return True
  77. def encryption_dict(self, model: Dict[str, object]):
  78. return {**model, 'spark_api_secret': super().encryption(model.get('spark_api_secret', ''))}
  79. spark_api_url = forms.TextInputField('API URL', required=True)
  80. spark_app_id = forms.TextInputField('APP ID', required=True)
  81. spark_api_key = forms.PasswordInputField("API Key", required=True)
  82. spark_api_secret = forms.PasswordInputField('API Secret', required=True)
  83. def get_model_params_setting_form(self, model_name):
  84. if model_name == 'general' or model_name == 'pro-128k':
  85. return XunFeiLLMModelGeneralParams()
  86. return XunFeiLLMModelProParams()