anthropic_provider.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import json
  2. import logging
  3. from json import JSONDecodeError
  4. from typing import Type, Optional
  5. import anthropic
  6. from flask import current_app
  7. from langchain.schema import HumanMessage
  8. from core.helper import encrypter
  9. from core.model_providers.models.base import BaseProviderModel
  10. from core.model_providers.models.entity.model_params import ModelKwargsRules, KwargRule, ModelMode
  11. from core.model_providers.models.entity.provider import ModelFeature
  12. from core.model_providers.models.llm.anthropic_model import AnthropicModel
  13. from core.model_providers.models.llm.base import ModelType
  14. from core.model_providers.providers.base import BaseModelProvider, CredentialsValidateFailedError
  15. from core.model_providers.providers.hosted import hosted_model_providers
  16. from core.third_party.langchain.llms.anthropic_llm import AnthropicLLM
  17. from models.provider import ProviderType
  18. class AnthropicProvider(BaseModelProvider):
  19. @property
  20. def provider_name(self):
  21. """
  22. Returns the name of a provider.
  23. """
  24. return 'anthropic'
  25. def _get_fixed_model_list(self, model_type: ModelType) -> list[dict]:
  26. if model_type == ModelType.TEXT_GENERATION:
  27. return [
  28. {
  29. 'id': 'claude-2.1',
  30. 'name': 'claude-2.1',
  31. 'mode': ModelMode.CHAT.value,
  32. 'features': [
  33. ModelFeature.AGENT_THOUGHT.value
  34. ]
  35. },
  36. {
  37. 'id': 'claude-2',
  38. 'name': 'claude-2',
  39. 'mode': ModelMode.CHAT.value,
  40. 'features': [
  41. ModelFeature.AGENT_THOUGHT.value
  42. ]
  43. },
  44. {
  45. 'id': 'claude-instant-1',
  46. 'name': 'claude-instant-1',
  47. 'mode': ModelMode.CHAT.value,
  48. },
  49. ]
  50. else:
  51. return []
  52. def _get_text_generation_model_mode(self, model_name) -> str:
  53. return ModelMode.CHAT.value
  54. def get_model_class(self, model_type: ModelType) -> Type[BaseProviderModel]:
  55. """
  56. Returns the model class.
  57. :param model_type:
  58. :return:
  59. """
  60. if model_type == ModelType.TEXT_GENERATION:
  61. model_class = AnthropicModel
  62. else:
  63. raise NotImplementedError
  64. return model_class
  65. def get_model_parameter_rules(self, model_name: str, model_type: ModelType) -> ModelKwargsRules:
  66. """
  67. get model parameter rules.
  68. :param model_name:
  69. :param model_type:
  70. :return:
  71. """
  72. model_max_tokens = {
  73. 'claude-instant-1': 100000,
  74. 'claude-2': 100000,
  75. 'claude-2.1': 200000,
  76. }
  77. return ModelKwargsRules(
  78. temperature=KwargRule[float](min=0, max=1, default=1, precision=2),
  79. top_p=KwargRule[float](min=0, max=1, default=0.7, precision=2),
  80. presence_penalty=KwargRule[float](enabled=False),
  81. frequency_penalty=KwargRule[float](enabled=False),
  82. max_tokens=KwargRule[int](alias="max_tokens_to_sample", min=10, max=model_max_tokens.get(model_name, 100000), default=256, precision=0),
  83. )
  84. @classmethod
  85. def is_provider_credentials_valid_or_raise(cls, credentials: dict):
  86. """
  87. Validates the given credentials.
  88. """
  89. if 'anthropic_api_key' not in credentials:
  90. raise CredentialsValidateFailedError('Anthropic API Key must be provided.')
  91. try:
  92. credential_kwargs = {
  93. 'anthropic_api_key': credentials['anthropic_api_key']
  94. }
  95. if 'anthropic_api_url' in credentials:
  96. credential_kwargs['anthropic_api_url'] = credentials['anthropic_api_url']
  97. chat_llm = AnthropicLLM(
  98. model='claude-instant-1',
  99. max_tokens_to_sample=10,
  100. temperature=0,
  101. default_request_timeout=60,
  102. **credential_kwargs
  103. )
  104. messages = [
  105. HumanMessage(
  106. content="ping"
  107. )
  108. ]
  109. chat_llm(messages)
  110. except anthropic.APIConnectionError as ex:
  111. raise CredentialsValidateFailedError(str(ex))
  112. except (anthropic.APIStatusError, anthropic.RateLimitError) as ex:
  113. raise CredentialsValidateFailedError(str(ex))
  114. except Exception as ex:
  115. logging.exception('Anthropic config validation failed')
  116. raise ex
  117. @classmethod
  118. def encrypt_provider_credentials(cls, tenant_id: str, credentials: dict) -> dict:
  119. credentials['anthropic_api_key'] = encrypter.encrypt_token(tenant_id, credentials['anthropic_api_key'])
  120. return credentials
  121. def get_provider_credentials(self, obfuscated: bool = False) -> dict:
  122. if self.provider.provider_type == ProviderType.CUSTOM.value:
  123. try:
  124. credentials = json.loads(self.provider.encrypted_config)
  125. except JSONDecodeError:
  126. credentials = {
  127. 'anthropic_api_url': None,
  128. 'anthropic_api_key': None
  129. }
  130. if credentials['anthropic_api_key']:
  131. credentials['anthropic_api_key'] = encrypter.decrypt_token(
  132. self.provider.tenant_id,
  133. credentials['anthropic_api_key']
  134. )
  135. if obfuscated:
  136. credentials['anthropic_api_key'] = encrypter.obfuscated_token(credentials['anthropic_api_key'])
  137. if 'anthropic_api_url' not in credentials:
  138. credentials['anthropic_api_url'] = None
  139. return credentials
  140. else:
  141. if hosted_model_providers.anthropic:
  142. return {
  143. 'anthropic_api_url': hosted_model_providers.anthropic.api_base,
  144. 'anthropic_api_key': hosted_model_providers.anthropic.api_key,
  145. }
  146. else:
  147. return {
  148. 'anthropic_api_url': None,
  149. 'anthropic_api_key': None
  150. }
  151. @classmethod
  152. def is_provider_type_system_supported(cls) -> bool:
  153. if current_app.config['EDITION'] != 'CLOUD':
  154. return False
  155. if hosted_model_providers.anthropic:
  156. return True
  157. return False
  158. def should_deduct_quota(self):
  159. if hosted_model_providers.anthropic and \
  160. hosted_model_providers.anthropic.quota_limit and hosted_model_providers.anthropic.quota_limit > -1:
  161. return True
  162. return False
  163. @classmethod
  164. def is_model_credentials_valid_or_raise(cls, model_name: str, model_type: ModelType, credentials: dict):
  165. """
  166. check model credentials valid.
  167. :param model_name:
  168. :param model_type:
  169. :param credentials:
  170. """
  171. return
  172. @classmethod
  173. def encrypt_model_credentials(cls, tenant_id: str, model_name: str, model_type: ModelType,
  174. credentials: dict) -> dict:
  175. """
  176. encrypt model credentials for save.
  177. :param tenant_id:
  178. :param model_name:
  179. :param model_type:
  180. :param credentials:
  181. :return:
  182. """
  183. return {}
  184. def get_model_credentials(self, model_name: str, model_type: ModelType, obfuscated: bool = False) -> dict:
  185. """
  186. get credentials for llm use.
  187. :param model_name:
  188. :param model_type:
  189. :param obfuscated:
  190. :return:
  191. """
  192. return self.get_provider_credentials(obfuscated)