image.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # coding=utf-8
  2. from typing import Dict
  3. from django.utils.translation import gettext_lazy as _, gettext
  4. from langchain_core.messages import HumanMessage
  5. from common import forms
  6. from common.exception.app_exception import AppApiException
  7. from common.forms import BaseForm, TooltipLabel
  8. from common.utils.logger import maxkb_logger
  9. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  10. class XinferenceImageModelParams(BaseForm):
  11. temperature = forms.SliderField(TooltipLabel(_('Temperature'),
  12. _('Higher values make the output more random, while lower values make it more focused and deterministic')),
  13. required=True, default_value=0.7,
  14. _min=0.1,
  15. _max=1.0,
  16. _step=0.01,
  17. precision=2)
  18. max_tokens = forms.SliderField(
  19. TooltipLabel(_('Output the maximum Tokens'),
  20. _('Specify the maximum number of tokens that the model can generate')),
  21. required=True, default_value=800,
  22. _min=1,
  23. _max=100000,
  24. _step=1,
  25. precision=0)
  26. class XinferenceImageModelCredential(BaseForm, BaseModelCredential):
  27. api_base = forms.TextInputField('API URL', required=True)
  28. api_key = forms.PasswordInputField('API Key', required=True)
  29. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  30. raise_exception=False):
  31. model_type_list = provider.get_model_type_list()
  32. if not any(list(filter(lambda mt: mt.get('value') == model_type, model_type_list))):
  33. raise AppApiException(ValidCode.valid_error.value,
  34. gettext('{model_type} Model type is not supported').format(model_type=model_type))
  35. for key in ['api_base', 'api_key']:
  36. if key not in model_credential:
  37. if raise_exception:
  38. raise AppApiException(ValidCode.valid_error.value, gettext('{key} is required').format(key=key))
  39. else:
  40. return False
  41. try:
  42. model = provider.get_model(model_type, model_name, model_credential, **model_params)
  43. res = model.stream([HumanMessage(content=[{"type": "text", "text": gettext('Hello')}])])
  44. for chunk in res:
  45. maxkb_logger.info(chunk)
  46. except Exception as e:
  47. if isinstance(e, AppApiException):
  48. raise e
  49. if raise_exception:
  50. raise AppApiException(ValidCode.valid_error.value,
  51. gettext(
  52. 'Verification failed, please check whether the parameters are correct: {error}').format(
  53. error=str(e)))
  54. else:
  55. return False
  56. return True
  57. def encryption_dict(self, model: Dict[str, object]):
  58. return {**model, 'api_key': super().encryption(model.get('api_key', ''))}
  59. def get_model_params_setting_form(self, model_name):
  60. return XinferenceImageModelParams()