configuration.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import os
  2. from typing import Any, Union
  3. from pydantic import BaseModel
  4. from yaml import FullLoader, load
  5. from core.helper import encrypter
  6. from core.helper.tool_provider_cache import ToolProviderCredentialsCache, ToolProviderCredentialsCacheType
  7. from core.tools.entities.tool_entities import (
  8. ModelToolConfiguration,
  9. ModelToolProviderConfiguration,
  10. ToolProviderCredentials,
  11. )
  12. from core.tools.provider.tool_provider import ToolProviderController
  13. class ToolConfiguration(BaseModel):
  14. tenant_id: str
  15. provider_controller: ToolProviderController
  16. def _deep_copy(self, credentials: dict[str, str]) -> dict[str, str]:
  17. """
  18. deep copy credentials
  19. """
  20. return {key: value for key, value in credentials.items()}
  21. def encrypt_tool_credentials(self, credentials: dict[str, str]) -> dict[str, str]:
  22. """
  23. encrypt tool credentials with tenant id
  24. return a deep copy of credentials with encrypted values
  25. """
  26. credentials = self._deep_copy(credentials)
  27. # get fields need to be decrypted
  28. fields = self.provider_controller.get_credentials_schema()
  29. for field_name, field in fields.items():
  30. if field.type == ToolProviderCredentials.CredentialsType.SECRET_INPUT:
  31. if field_name in credentials:
  32. encrypted = encrypter.encrypt_token(self.tenant_id, credentials[field_name])
  33. credentials[field_name] = encrypted
  34. return credentials
  35. def mask_tool_credentials(self, credentials: dict[str, Any]) -> dict[str, Any]:
  36. """
  37. mask tool credentials
  38. return a deep copy of credentials with masked values
  39. """
  40. credentials = self._deep_copy(credentials)
  41. # get fields need to be decrypted
  42. fields = self.provider_controller.get_credentials_schema()
  43. for field_name, field in fields.items():
  44. if field.type == ToolProviderCredentials.CredentialsType.SECRET_INPUT:
  45. if field_name in credentials:
  46. if len(credentials[field_name]) > 6:
  47. credentials[field_name] = \
  48. credentials[field_name][:2] + \
  49. '*' * (len(credentials[field_name]) - 4) +\
  50. credentials[field_name][-2:]
  51. else:
  52. credentials[field_name] = '*' * len(credentials[field_name])
  53. return credentials
  54. def decrypt_tool_credentials(self, credentials: dict[str, str]) -> dict[str, str]:
  55. """
  56. decrypt tool credentials with tenant id
  57. return a deep copy of credentials with decrypted values
  58. """
  59. cache = ToolProviderCredentialsCache(
  60. tenant_id=self.tenant_id,
  61. identity_id=f'{self.provider_controller.app_type.value}.{self.provider_controller.identity.name}',
  62. cache_type=ToolProviderCredentialsCacheType.PROVIDER
  63. )
  64. cached_credentials = cache.get()
  65. if cached_credentials:
  66. return cached_credentials
  67. credentials = self._deep_copy(credentials)
  68. # get fields need to be decrypted
  69. fields = self.provider_controller.get_credentials_schema()
  70. for field_name, field in fields.items():
  71. if field.type == ToolProviderCredentials.CredentialsType.SECRET_INPUT:
  72. if field_name in credentials:
  73. try:
  74. credentials[field_name] = encrypter.decrypt_token(self.tenant_id, credentials[field_name])
  75. except:
  76. pass
  77. cache.set(credentials)
  78. return credentials
  79. def delete_tool_credentials_cache(self):
  80. cache = ToolProviderCredentialsCache(
  81. tenant_id=self.tenant_id,
  82. identity_id=f'{self.provider_controller.app_type.value}.{self.provider_controller.identity.name}',
  83. cache_type=ToolProviderCredentialsCacheType.PROVIDER
  84. )
  85. cache.delete()
  86. class ModelToolConfigurationManager:
  87. """
  88. Model as tool configuration
  89. """
  90. _configurations: dict[str, ModelToolProviderConfiguration] = {}
  91. _model_configurations: dict[str, ModelToolConfiguration] = {}
  92. _inited = False
  93. @classmethod
  94. def _init_configuration(cls):
  95. """
  96. init configuration
  97. """
  98. absolute_path = os.path.abspath(os.path.dirname(__file__))
  99. model_tools_path = os.path.join(absolute_path, '..', 'model_tools')
  100. # get all .yaml file
  101. files = [f for f in os.listdir(model_tools_path) if f.endswith('.yaml')]
  102. for file in files:
  103. provider = file.split('.')[0]
  104. with open(os.path.join(model_tools_path, file), encoding='utf-8') as f:
  105. configurations = ModelToolProviderConfiguration(**load(f, Loader=FullLoader))
  106. models = configurations.models or []
  107. for model in models:
  108. model_key = f'{provider}.{model.model}'
  109. cls._model_configurations[model_key] = model
  110. cls._configurations[provider] = configurations
  111. cls._inited = True
  112. @classmethod
  113. def get_configuration(cls, provider: str) -> Union[ModelToolProviderConfiguration, None]:
  114. """
  115. get configuration by provider
  116. """
  117. if not cls._inited:
  118. cls._init_configuration()
  119. return cls._configurations.get(provider, None)
  120. @classmethod
  121. def get_all_configuration(cls) -> dict[str, ModelToolProviderConfiguration]:
  122. """
  123. get all configurations
  124. """
  125. if not cls._inited:
  126. cls._init_configuration()
  127. return cls._configurations
  128. @classmethod
  129. def get_model_configuration(cls, provider: str, model: str) -> Union[ModelToolConfiguration, None]:
  130. """
  131. get model configuration
  132. """
  133. key = f'{provider}.{model}'
  134. if not cls._inited:
  135. cls._init_configuration()
  136. return cls._model_configurations.get(key, None)