minimax_provider.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import json
  2. from json import JSONDecodeError
  3. from typing import Type
  4. from langchain.schema import HumanMessage
  5. from core.helper import encrypter
  6. from core.model_providers.models.base import BaseProviderModel
  7. from core.model_providers.models.embedding.minimax_embedding import MinimaxEmbedding
  8. from core.model_providers.models.entity.model_params import ModelKwargsRules, KwargRule, ModelType, ModelMode
  9. from core.model_providers.models.llm.minimax_model import MinimaxModel
  10. from core.model_providers.providers.base import BaseModelProvider, CredentialsValidateFailedError
  11. from core.third_party.langchain.llms.minimax_llm import MinimaxChatLLM
  12. from models.provider import ProviderType, ProviderQuotaType
  13. class MinimaxProvider(BaseModelProvider):
  14. @property
  15. def provider_name(self):
  16. """
  17. Returns the name of a provider.
  18. """
  19. return 'minimax'
  20. def _get_fixed_model_list(self, model_type: ModelType) -> list[dict]:
  21. if model_type == ModelType.TEXT_GENERATION:
  22. return [
  23. {
  24. 'id': 'abab5.5-chat',
  25. 'name': 'abab5.5-chat',
  26. 'mode': ModelMode.COMPLETION.value,
  27. },
  28. {
  29. 'id': 'abab5-chat',
  30. 'name': 'abab5-chat',
  31. 'mode': ModelMode.COMPLETION.value,
  32. }
  33. ]
  34. elif model_type == ModelType.EMBEDDINGS:
  35. return [
  36. {
  37. 'id': 'embo-01',
  38. 'name': 'embo-01',
  39. }
  40. ]
  41. else:
  42. return []
  43. def _get_text_generation_model_mode(self, model_name) -> str:
  44. return ModelMode.COMPLETION.value
  45. def get_model_class(self, model_type: ModelType) -> Type[BaseProviderModel]:
  46. """
  47. Returns the model class.
  48. :param model_type:
  49. :return:
  50. """
  51. if model_type == ModelType.TEXT_GENERATION:
  52. model_class = MinimaxModel
  53. elif model_type == ModelType.EMBEDDINGS:
  54. model_class = MinimaxEmbedding
  55. else:
  56. raise NotImplementedError
  57. return model_class
  58. def get_model_parameter_rules(self, model_name: str, model_type: ModelType) -> ModelKwargsRules:
  59. """
  60. get model parameter rules.
  61. :param model_name:
  62. :param model_type:
  63. :return:
  64. """
  65. model_max_tokens = {
  66. 'abab5.5-chat': 16384,
  67. 'abab5-chat': 6144,
  68. }
  69. return ModelKwargsRules(
  70. temperature=KwargRule[float](min=0.01, max=1, default=0.9, precision=2),
  71. top_p=KwargRule[float](min=0, max=1, default=0.95, precision=2),
  72. presence_penalty=KwargRule[float](enabled=False),
  73. frequency_penalty=KwargRule[float](enabled=False),
  74. max_tokens=KwargRule[int](min=10, max=model_max_tokens.get(model_name, 6144), default=1024, precision=0),
  75. )
  76. @classmethod
  77. def is_provider_credentials_valid_or_raise(cls, credentials: dict):
  78. """
  79. Validates the given credentials.
  80. """
  81. if 'minimax_group_id' not in credentials:
  82. raise CredentialsValidateFailedError('MiniMax Group ID must be provided.')
  83. if 'minimax_api_key' not in credentials:
  84. raise CredentialsValidateFailedError('MiniMax API Key must be provided.')
  85. try:
  86. credential_kwargs = {
  87. 'minimax_group_id': credentials['minimax_group_id'],
  88. 'minimax_api_key': credentials['minimax_api_key'],
  89. }
  90. llm = MinimaxChatLLM(
  91. model='abab5.5-chat',
  92. max_tokens=10,
  93. temperature=0.01,
  94. **credential_kwargs
  95. )
  96. llm([HumanMessage(content='ping')])
  97. except Exception as ex:
  98. raise CredentialsValidateFailedError(str(ex))
  99. @classmethod
  100. def encrypt_provider_credentials(cls, tenant_id: str, credentials: dict) -> dict:
  101. credentials['minimax_api_key'] = encrypter.encrypt_token(tenant_id, credentials['minimax_api_key'])
  102. return credentials
  103. def get_provider_credentials(self, obfuscated: bool = False) -> dict:
  104. if self.provider.provider_type == ProviderType.CUSTOM.value \
  105. or (self.provider.provider_type == ProviderType.SYSTEM.value
  106. and self.provider.quota_type == ProviderQuotaType.FREE.value):
  107. try:
  108. credentials = json.loads(self.provider.encrypted_config)
  109. except JSONDecodeError:
  110. credentials = {
  111. 'minimax_group_id': None,
  112. 'minimax_api_key': None,
  113. }
  114. if credentials['minimax_api_key']:
  115. credentials['minimax_api_key'] = encrypter.decrypt_token(
  116. self.provider.tenant_id,
  117. credentials['minimax_api_key']
  118. )
  119. if obfuscated:
  120. credentials['minimax_api_key'] = encrypter.obfuscated_token(credentials['minimax_api_key'])
  121. return credentials
  122. return {}
  123. def should_deduct_quota(self):
  124. return True
  125. @classmethod
  126. def is_model_credentials_valid_or_raise(cls, model_name: str, model_type: ModelType, credentials: dict):
  127. """
  128. check model credentials valid.
  129. :param model_name:
  130. :param model_type:
  131. :param credentials:
  132. """
  133. return
  134. @classmethod
  135. def encrypt_model_credentials(cls, tenant_id: str, model_name: str, model_type: ModelType,
  136. credentials: dict) -> dict:
  137. """
  138. encrypt model credentials for save.
  139. :param tenant_id:
  140. :param model_name:
  141. :param model_type:
  142. :param credentials:
  143. :return:
  144. """
  145. return {}
  146. def get_model_credentials(self, model_name: str, model_type: ModelType, obfuscated: bool = False) -> dict:
  147. """
  148. get credentials for llm use.
  149. :param model_name:
  150. :param model_type:
  151. :param obfuscated:
  152. :return:
  153. """
  154. return self.get_provider_credentials(obfuscated)