zhipuai_provider.py 5.6 KB

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