image.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # coding=utf-8
  2. import base64
  3. import os
  4. from typing import Dict
  5. from langchain_core.messages import HumanMessage
  6. from common import forms
  7. from common.exception.app_exception import AppApiException
  8. from common.forms import BaseForm, TooltipLabel
  9. from common.utils.logger import maxkb_logger
  10. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  11. from django.utils.translation import gettext_lazy as _, gettext
  12. class AzureOpenAIImageModelParams(BaseForm):
  13. temperature = forms.SliderField(TooltipLabel(_('Temperature'),
  14. _('Higher values make the output more random, while lower values make it more focused and deterministic')),
  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(_('Output the maximum Tokens'),
  22. _('Specify the maximum number of tokens that the model can generate')),
  23. required=True, default_value=800,
  24. _min=1,
  25. _max=100000,
  26. _step=1,
  27. precision=0)
  28. class AzureOpenAIImageModelCredential(BaseForm, BaseModelCredential):
  29. api_version = forms.TextInputField("API Version", required=True)
  30. api_base = forms.TextInputField('Azure Endpoint', required=True)
  31. api_key = forms.PasswordInputField("API Key", required=True)
  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. for key in ['api_base', 'api_key', 'api_version']:
  39. if key not in model_credential:
  40. if raise_exception:
  41. raise AppApiException(ValidCode.valid_error.value, gettext('{key} is required').format(key=key))
  42. else:
  43. return False
  44. try:
  45. model = provider.get_model(model_type, model_name, model_credential, **model_params)
  46. res = model.stream([HumanMessage(content=[{"type": "text", "text": gettext('Hello')}])])
  47. for chunk in res:
  48. maxkb_logger.info(chunk)
  49. except Exception as e:
  50. maxkb_logger.error(f'Exception: {e}', exc_info=True)
  51. if isinstance(e, AppApiException):
  52. raise e
  53. if raise_exception:
  54. raise AppApiException(ValidCode.valid_error.value,
  55. gettext(
  56. 'Verification failed, please check whether the parameters are correct: {error}').format(
  57. error=str(e)))
  58. else:
  59. return False
  60. return True
  61. def encryption_dict(self, model: Dict[str, object]):
  62. return {**model, 'api_key': super().encryption(model.get('api_key', ''))}
  63. def get_model_params_setting_form(self, model_name):
  64. return AzureOpenAIImageModelParams()