spark_provider.py 6.1 KB

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