Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# coding=utf-8
"""
@project: MaxKB
@Author:虎
@file: __init__.py
@date:2024/9/9 17:42
@desc:
@project: MaxKB
@Author:虎
@file: __init__.py
@date:2024/9/9 17:42
@desc:
"""
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# coding=utf-8
"""
@project: MaxKB
@Author:虎
@file: embedding.py
@date:2024/10/16 17:01
@desc:
@project: MaxKB
@Author:虎
@file: embedding.py
@date:2024/10/16 17:01
@desc:
"""

from typing import Dict, Any

from django.utils.translation import gettext as _
Expand All @@ -20,63 +21,53 @@

class BaiLianEmbeddingModelParams(BaseForm):
dimensions = forms.SingleSelect(
TooltipLabel(
_('Dimensions'),
_('')
),
TooltipLabel(_("Dimensions"), _("")),
required=True,
default_value=1024,
value_field='value',
text_field='label',
value_field="value",
text_field="label",
option_list=[
{'label': '1024', 'value': '1024'},
{'label': '768', 'value': '768'},
{'label': '512', 'value': '512'},
]
{"label": "1024", "value": "1024"},
{"label": "768", "value": "768"},
{"label": "512", "value": "512"},
],
)


class AliyunBaiLianEmbeddingCredential(BaseForm, BaseModelCredential):

def is_valid(
self,
model_type: str,
model_name: str,
model_credential: Dict[str, Any],
model_params: Dict[str, Any],
provider: Any,
raise_exception: bool = False
self,
model_type: str,
model_name: str,
model_credential: Dict[str, Any],
model_params: Dict[str, Any],
provider: Any,
raise_exception: bool = False,
) -> bool:
"""
验证模型凭据是否有效
"""
model_type_list = provider.get_model_type_list()
if not any(mt.get('value') == model_type for mt in model_type_list):
raise AppApiException(
ValidCode.valid_error.value,
f"{model_type} Model type is not supported"
)
required_keys = ['dashscope_api_key', 'api_base']
if not any(mt.get("value") == model_type for mt in model_type_list):
raise AppApiException(ValidCode.valid_error.value, f"{model_type} Model type is not supported")
required_keys = ["dashscope_api_key", "api_base"]
missing_keys = [key for key in required_keys if key not in model_credential]
if missing_keys:
if raise_exception:
raise AppApiException(
ValidCode.valid_error.value,
f"{', '.join(missing_keys)} is required"
)
raise AppApiException(ValidCode.valid_error.value, f"{', '.join(missing_keys)} is required")
return False

try:
model: AliyunBaiLianEmbedding = provider.get_model(model_type, model_name, model_credential)
model.embed_query(_("Hello"))
except Exception as e:
maxkb_logger.error(f'Exception: {e}', exc_info=True)
maxkb_logger.error(f"Exception: {e}", exc_info=True)
if isinstance(e, AppApiException):
raise e
if raise_exception:
raise AppApiException(
ValidCode.valid_error.value,
f"Verification failed, please check whether the parameters are correct: {e}"
f"Verification failed, please check whether the parameters are correct: {e}",
)
return False

Expand All @@ -86,12 +77,13 @@ def encryption_dict(self, model: Dict[str, Any]) -> Dict[str, Any]:
"""
加密敏感信息
"""
api_key = model.get('dashscope_api_key', '')
return {**model, 'dashscope_api_key': super().encryption(api_key)}
api_key = model.get("dashscope_api_key", "")
return {**model, "dashscope_api_key": super().encryption(api_key)}

def get_model_params_setting_form(self, model_name):
return BaiLianEmbeddingModelParams()

api_base = forms.TextInputField(_('API URL'), required=True,
default_value='https://dashscope.aliyuncs.com/compatible-mode/v1')
dashscope_api_key = forms.PasswordInputField('API Key', required=True)
api_base = forms.TextInputField(
_("API URL"), required=True, default_value="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
dashscope_api_key = forms.PasswordInputField("API Key", required=True)
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# coding=utf-8
"""
@project: MaxKB
@Author:虎
@file: llm.py
@date:2024/7/11 18:41
@desc:
@project: MaxKB
@Author:虎
@file: llm.py
@date:2024/7/11 18:41
@desc:
"""

from typing import Dict

from django.utils.translation import gettext_lazy as _, gettext
Expand All @@ -18,74 +19,80 @@


class QwenModelParams(BaseForm):
temperature = forms.SliderField(TooltipLabel(_('Temperature'),
_('Higher values make the output more random, while lower values make it more focused and deterministic')),
required=True, default_value=1.0,
_min=0.1,
_max=1.9,
_step=0.01,
precision=2)
temperature = forms.SliderField(
TooltipLabel(
_("Temperature"),
_("Higher values make the output more random, while lower values make it more focused and deterministic"),
),
required=True,
default_value=1.0,
_min=0.1,
_max=1.9,
_step=0.01,
precision=2,
)

max_tokens = forms.SliderField(
TooltipLabel(_('Output the maximum Tokens'),
_('Specify the maximum number of tokens that the model can generate')),
required=True, default_value=800,
TooltipLabel(
_("Output the maximum Tokens"), _("Specify the maximum number of tokens that the model can generate")
),
required=True,
default_value=800,
_min=1,
_max=100000,
_step=1,
precision=0)
precision=0,
)


class QwenVLModelCredential(BaseForm, BaseModelCredential):

def is_valid(
self,
model_type: str,
model_name: str,
model_credential: Dict[str, object],
model_params: dict,
provider,
raise_exception: bool = False
self,
model_type: str,
model_name: str,
model_credential: Dict[str, object],
model_params: dict,
provider,
raise_exception: bool = False,
) -> bool:
model_type_list = provider.get_model_type_list()
if not any(mt.get('value') == model_type for mt in model_type_list):
if not any(mt.get("value") == model_type for mt in model_type_list):
raise AppApiException(
ValidCode.valid_error.value,
gettext('{model_type} Model type is not supported').format(model_type=model_type)
gettext("{model_type} Model type is not supported").format(model_type=model_type),
)
required_keys = ['api_key', 'api_base']
required_keys = ["api_key", "api_base"]
for key in required_keys:
if key not in model_credential:
if raise_exception:
raise AppApiException(
ValidCode.valid_error.value,
gettext('{key} is required').format(key=key)
)
raise AppApiException(ValidCode.valid_error.value, gettext("{key} is required").format(key=key))
return False

try:
model = provider.get_model(model_type, model_name, model_credential, **model_params)
model.check_auth(model_credential.get('api_key'))
model.check_auth(model_credential.get("api_key"))
except Exception as e:
maxkb_logger.error(f'Exception: {e}', exc_info=True)
maxkb_logger.error(f"Exception: {e}", exc_info=True)
if isinstance(e, AppApiException):
raise e
if raise_exception:
raise AppApiException(
ValidCode.valid_error.value,
gettext('Verification failed, please check whether the parameters are correct: {error}').format(
gettext("Verification failed, please check whether the parameters are correct: {error}").format(
error=str(e)
)
),
)
return False

return True

def encryption_dict(self, model: Dict[str, object]) -> Dict[str, object]:
return {**model, 'api_key': super().encryption(model.get('api_key', ''))}
return {**model, "api_key": super().encryption(model.get("api_key", ""))}

api_base = forms.TextInputField(_('API URL'), required=True, default_value='https://dashscope.aliyuncs.com/compatible-mode/v1')
api_key = forms.PasswordInputField('API Key', required=True)
api_base = forms.TextInputField(
_("API URL"), required=True, default_value="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
api_key = forms.PasswordInputField("API Key", required=True)

def get_model_params_setting_form(self, model_name):
return QwenModelParams()
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,33 @@

from common import forms
from common.exception.app_exception import AppApiException
from common.forms import BaseForm, PasswordInputField, SingleSelect, SliderField, TooltipLabel
from common.forms import BaseForm, PasswordInputField, SingleSelect, TooltipLabel
from common.forms.switch_field import SwitchField
from models_provider.base_model_provider import BaseModelCredential, ValidCode
from common.utils.logger import maxkb_logger


class QwenModelParams(BaseForm):
"""
Parameters class for the Qwen Image-to-Video model.
Defines fields such as Video size, number of Videos, and style.
"""

resolution = SingleSelect(
TooltipLabel(_('Resolution'), ''),
TooltipLabel(_("Resolution"), ""),
required=True,
default_value='480P',
default_value="480P",
option_list=[
{'value': '480P', 'label': '480P'},
{'value': '720P', 'label': '720P'},
{'value': '1080P', 'label': '1080P'},
{"value": "480P", "label": "480P"},
{"value": "720P", "label": "720P"},
{"value": "1080P", "label": "1080P"},
],
text_field='label',
value_field='value'
text_field="label",
value_field="value",
)

watermark = SwitchField(
TooltipLabel(_('Watermark'), _('Whether to add watermark')),
TooltipLabel(_("Watermark"), _("Whether to add watermark")),
attrs={"active-value": True, "inactive-value": False},
default_value=False,
)
Expand All @@ -41,17 +43,18 @@ class ImageToVideoModelCredential(BaseForm, BaseModelCredential):
Credential class for the Qwen Image-to-Video model.
Provides validation and encryption for the model credentials.
"""
api_base = forms.TextInputField(_('API URL'), required=True, default_value='https://dashscope.aliyuncs.com/api/v1')
api_key = PasswordInputField('API Key', required=True)

api_base = forms.TextInputField(_("API URL"), required=True, default_value="https://dashscope.aliyuncs.com/api/v1")
api_key = PasswordInputField("API Key", required=True)

def is_valid(
self,
model_type: str,
model_name: str,
model_credential: Dict[str, Any],
model_params: Dict[str, Any],
provider,
raise_exception: bool = False
self,
model_type: str,
model_name: str,
model_credential: Dict[str, Any],
model_params: Dict[str, Any],
provider,
raise_exception: bool = False,
) -> bool:
"""
Validate the model credentials.
Expand All @@ -65,35 +68,32 @@ def is_valid(
:return: Boolean indicating whether the credentials are valid.
"""
model_type_list = provider.get_model_type_list()
if not any(mt.get('value') == model_type for mt in model_type_list):
if not any(mt.get("value") == model_type for mt in model_type_list):
raise AppApiException(
ValidCode.valid_error.value,
gettext('{model_type} Model type is not supported').format(model_type=model_type)
gettext("{model_type} Model type is not supported").format(model_type=model_type),
)

required_keys = ['api_key', 'api_base']
required_keys = ["api_key", "api_base"]
for key in required_keys:
if key not in model_credential:
if raise_exception:
raise AppApiException(
ValidCode.valid_error.value,
gettext('{key} is required').format(key=key)
)
raise AppApiException(ValidCode.valid_error.value, gettext("{key} is required").format(key=key))
return False

try:
model = provider.get_model(model_type, model_name, model_credential, **model_params)
res = model.check_auth()
except Exception as e:
maxkb_logger.error(f'Exception: {e}', exc_info=True)
maxkb_logger.error(f"Exception: {e}", exc_info=True)
if isinstance(e, AppApiException):
raise e
if raise_exception:
raise AppApiException(
ValidCode.valid_error.value,
gettext(
'Verification failed, please check whether the parameters are correct: {error}'
).format(error=str(e))
gettext("Verification failed, please check whether the parameters are correct: {error}").format(
error=str(e)
),
)
return False

Expand All @@ -106,10 +106,7 @@ def encryption_dict(self, model: Dict[str, object]) -> Dict[str, object]:
:param model: Dictionary containing model details.
:return: Dictionary with encrypted sensitive fields.
"""
return {
**model,
'api_key': super().encryption(model.get('api_key', ''))
}
return {**model, "api_key": super().encryption(model.get("api_key", ""))}

def get_model_params_setting_form(self, model_name: str):
"""
Expand Down
Loading
Loading