llm.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # coding=utf-8
  2. """
  3. OpenAI 兼容私域模型凭证
  4. 用于添加自定义 OpenAI 兼容 API 的私域模型
  5. """
  6. from typing import Dict
  7. from django.utils.translation import gettext_lazy as _, gettext
  8. from common import forms
  9. from common.exception.app_exception import AppApiException
  10. from common.forms import BaseForm, TooltipLabel
  11. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  12. class OpenAICompatibleLLMModelParams(BaseForm):
  13. temperature = forms.SliderField(TooltipLabel(_('Temperature'),
  14. _('Higher values make the output more random, while lower makes it more focused')),
  15. required=True, default_value=0.7,
  16. _min=0.1,
  17. _max=1.0,
  18. _step=0.01,
  19. precision=2)
  20. max_tokens = forms.SliderField(
  21. TooltipLabel(_('Max Tokens'),
  22. _('Maximum number of tokens to generate')),
  23. required=True, default_value=2048,
  24. _min=1,
  25. _max=128000,
  26. _step=1,
  27. precision=0)
  28. class OpenAICompatibleLLMModelCredential(BaseForm, BaseModelCredential):
  29. """
  30. OpenAI 兼容 API 凭证
  31. 用户只需填写 API URL 和 API Key 即可添加私域模型
  32. """
  33. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  34. raise_exception=False):
  35. for key in ['api_base', 'api_key']:
  36. if key not in model_credential or not model_credential.get(key):
  37. if raise_exception:
  38. raise AppApiException(ValidCode.valid_error.value,
  39. gettext('{key} is required').format(key=key))
  40. else:
  41. return False
  42. return True
  43. def encryption_dict(self, model_info: Dict[str, object]):
  44. return {**model_info, 'api_key': super().encryption(model_info.get('api_key', ''))}
  45. api_base = forms.TextInputField('API URL', required=True)
  46. api_key = forms.PasswordInputField('API Key', required=True)
  47. def get_model_params_setting_form(self, model_name):
  48. return OpenAICompatibleLLMModelParams()