builtin_tool_provider.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import importlib
  2. from abc import abstractmethod
  3. from os import listdir, path
  4. from typing import Any, Dict, List
  5. from core.tools.entities.tool_entities import ToolParameter, ToolProviderCredentials, ToolProviderType
  6. from core.tools.entities.user_entities import UserToolProviderCredentials
  7. from core.tools.errors import (ToolNotFoundError, ToolParameterValidationError, ToolProviderCredentialValidationError,
  8. ToolProviderNotFoundError)
  9. from core.tools.provider.tool_provider import ToolProviderController
  10. from core.tools.tool.builtin_tool import BuiltinTool
  11. from core.tools.tool.tool import Tool
  12. from yaml import FullLoader, load
  13. class BuiltinToolProviderController(ToolProviderController):
  14. def __init__(self, **data: Any) -> None:
  15. if self.app_type == ToolProviderType.API_BASED or self.app_type == ToolProviderType.APP_BASED:
  16. super().__init__(**data)
  17. return
  18. # load provider yaml
  19. provider = self.__class__.__module__.split('.')[-1]
  20. yaml_path = path.join(path.dirname(path.realpath(__file__)), 'builtin', provider, f'{provider}.yaml')
  21. try:
  22. with open(yaml_path, 'r') as f:
  23. provider_yaml = load(f.read(), FullLoader)
  24. except:
  25. raise ToolProviderNotFoundError(f'can not load provider yaml for {provider}')
  26. if 'credentials_for_provider' in provider_yaml and provider_yaml['credentials_for_provider'] is not None:
  27. # set credentials name
  28. for credential_name in provider_yaml['credentials_for_provider']:
  29. provider_yaml['credentials_for_provider'][credential_name]['name'] = credential_name
  30. super().__init__(**{
  31. 'identity': provider_yaml['identity'],
  32. 'credentials_schema': provider_yaml['credentials_for_provider'] if 'credentials_for_provider' in provider_yaml else None,
  33. })
  34. def _get_builtin_tools(self) -> List[Tool]:
  35. """
  36. returns a list of tools that the provider can provide
  37. :return: list of tools
  38. """
  39. if self.tools:
  40. return self.tools
  41. provider = self.identity.name
  42. tool_path = path.join(path.dirname(path.realpath(__file__)), "builtin", provider, "tools")
  43. # get all the yaml files in the tool path
  44. tool_files = list(filter(lambda x: x.endswith(".yaml") and not x.startswith("__"), listdir(tool_path)))
  45. tools = []
  46. for tool_file in tool_files:
  47. with open(path.join(tool_path, tool_file), "r") as f:
  48. # get tool name
  49. tool_name = tool_file.split(".")[0]
  50. tool = load(f.read(), FullLoader)
  51. # get tool class, import the module
  52. py_path = path.join(path.dirname(path.realpath(__file__)), 'builtin', provider, 'tools', f'{tool_name}.py')
  53. spec = importlib.util.spec_from_file_location(f'core.tools.provider.builtin.{provider}.tools.{tool_name}', py_path)
  54. mod = importlib.util.module_from_spec(spec)
  55. spec.loader.exec_module(mod)
  56. # get all the classes in the module
  57. classes = [x for _, x in vars(mod).items()
  58. if isinstance(x, type) and x not in [BuiltinTool, Tool] and issubclass(x, BuiltinTool)
  59. ]
  60. assistant_tool_class = classes[0]
  61. tools.append(assistant_tool_class(**tool))
  62. self.tools = tools
  63. return tools
  64. def get_credentials_schema(self) -> Dict[str, ToolProviderCredentials]:
  65. """
  66. returns the credentials schema of the provider
  67. :return: the credentials schema
  68. """
  69. if not self.credentials_schema:
  70. return {}
  71. return self.credentials_schema.copy()
  72. def user_get_credentials_schema(self) -> UserToolProviderCredentials:
  73. """
  74. returns the credentials schema of the provider, this method is used for user
  75. :return: the credentials schema
  76. """
  77. credentials = self.credentials_schema.copy()
  78. return UserToolProviderCredentials(credentials=credentials)
  79. def get_tools(self) -> List[Tool]:
  80. """
  81. returns a list of tools that the provider can provide
  82. :return: list of tools
  83. """
  84. return self._get_builtin_tools()
  85. def get_tool(self, tool_name: str) -> Tool:
  86. """
  87. returns the tool that the provider can provide
  88. """
  89. return next(filter(lambda x: x.identity.name == tool_name, self.get_tools()), None)
  90. def get_parameters(self, tool_name: str) -> List[ToolParameter]:
  91. """
  92. returns the parameters of the tool
  93. :param tool_name: the name of the tool, defined in `get_tools`
  94. :return: list of parameters
  95. """
  96. tool = next(filter(lambda x: x.identity.name == tool_name, self.get_tools()), None)
  97. if tool is None:
  98. raise ToolNotFoundError(f'tool {tool_name} not found')
  99. return tool.parameters
  100. @property
  101. def need_credentials(self) -> bool:
  102. """
  103. returns whether the provider needs credentials
  104. :return: whether the provider needs credentials
  105. """
  106. return self.credentials_schema is not None and len(self.credentials_schema) != 0
  107. @property
  108. def app_type(self) -> ToolProviderType:
  109. """
  110. returns the type of the provider
  111. :return: type of the provider
  112. """
  113. return ToolProviderType.BUILT_IN
  114. def validate_parameters(self, tool_id: int, tool_name: str, tool_parameters: Dict[str, Any]) -> None:
  115. """
  116. validate the parameters of the tool and set the default value if needed
  117. :param tool_name: the name of the tool, defined in `get_tools`
  118. :param tool_parameters: the parameters of the tool
  119. """
  120. tool_parameters_schema = self.get_parameters(tool_name)
  121. tool_parameters_need_to_validate: Dict[str, ToolParameter] = {}
  122. for parameter in tool_parameters_schema:
  123. tool_parameters_need_to_validate[parameter.name] = parameter
  124. for parameter in tool_parameters:
  125. if parameter not in tool_parameters_need_to_validate:
  126. raise ToolParameterValidationError(f'parameter {parameter} not found in tool {tool_name}')
  127. # check type
  128. parameter_schema = tool_parameters_need_to_validate[parameter]
  129. if parameter_schema.type == ToolParameter.ToolParameterType.STRING:
  130. if not isinstance(tool_parameters[parameter], str):
  131. raise ToolParameterValidationError(f'parameter {parameter} should be string')
  132. elif parameter_schema.type == ToolParameter.ToolParameterType.NUMBER:
  133. if not isinstance(tool_parameters[parameter], (int, float)):
  134. raise ToolParameterValidationError(f'parameter {parameter} should be number')
  135. if parameter_schema.min is not None and tool_parameters[parameter] < parameter_schema.min:
  136. raise ToolParameterValidationError(f'parameter {parameter} should be greater than {parameter_schema.min}')
  137. if parameter_schema.max is not None and tool_parameters[parameter] > parameter_schema.max:
  138. raise ToolParameterValidationError(f'parameter {parameter} should be less than {parameter_schema.max}')
  139. elif parameter_schema.type == ToolParameter.ToolParameterType.BOOLEAN:
  140. if not isinstance(tool_parameters[parameter], bool):
  141. raise ToolParameterValidationError(f'parameter {parameter} should be boolean')
  142. elif parameter_schema.type == ToolParameter.ToolParameterType.SELECT:
  143. if not isinstance(tool_parameters[parameter], str):
  144. raise ToolParameterValidationError(f'parameter {parameter} should be string')
  145. options = parameter_schema.options
  146. if not isinstance(options, list):
  147. raise ToolParameterValidationError(f'parameter {parameter} options should be list')
  148. if tool_parameters[parameter] not in [x.value for x in options]:
  149. raise ToolParameterValidationError(f'parameter {parameter} should be one of {options}')
  150. tool_parameters_need_to_validate.pop(parameter)
  151. for parameter in tool_parameters_need_to_validate:
  152. parameter_schema = tool_parameters_need_to_validate[parameter]
  153. if parameter_schema.required:
  154. raise ToolParameterValidationError(f'parameter {parameter} is required')
  155. # the parameter is not set currently, set the default value if needed
  156. if parameter_schema.default is not None:
  157. default_value = parameter_schema.default
  158. # parse default value into the correct type
  159. if parameter_schema.type == ToolParameter.ToolParameterType.STRING or \
  160. parameter_schema.type == ToolParameter.ToolParameterType.SELECT:
  161. default_value = str(default_value)
  162. elif parameter_schema.type == ToolParameter.ToolParameterType.NUMBER:
  163. default_value = float(default_value)
  164. elif parameter_schema.type == ToolParameter.ToolParameterType.BOOLEAN:
  165. default_value = bool(default_value)
  166. tool_parameters[parameter] = default_value
  167. def validate_credentials_format(self, credentials: Dict[str, Any]) -> None:
  168. """
  169. validate the format of the credentials of the provider and set the default value if needed
  170. :param credentials: the credentials of the tool
  171. """
  172. credentials_schema = self.credentials_schema
  173. if credentials_schema is None:
  174. return
  175. credentials_need_to_validate: Dict[str, ToolProviderCredentials] = {}
  176. for credential_name in credentials_schema:
  177. credentials_need_to_validate[credential_name] = credentials_schema[credential_name]
  178. for credential_name in credentials:
  179. if credential_name not in credentials_need_to_validate:
  180. raise ToolProviderCredentialValidationError(f'credential {credential_name} not found in provider {self.identity.name}')
  181. # check type
  182. credential_schema = credentials_need_to_validate[credential_name]
  183. if credential_schema == ToolProviderCredentials.CredentialsType.SECRET_INPUT or \
  184. credential_schema == ToolProviderCredentials.CredentialsType.TEXT_INPUT:
  185. if not isinstance(credentials[credential_name], str):
  186. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be string')
  187. elif credential_schema.type == ToolProviderCredentials.CredentialsType.SELECT:
  188. if not isinstance(credentials[credential_name], str):
  189. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be string')
  190. options = credential_schema.options
  191. if not isinstance(options, list):
  192. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} options should be list')
  193. if credentials[credential_name] not in [x.value for x in options]:
  194. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be one of {options}')
  195. if credentials[credential_name]:
  196. credentials_need_to_validate.pop(credential_name)
  197. for credential_name in credentials_need_to_validate:
  198. credential_schema = credentials_need_to_validate[credential_name]
  199. if credential_schema.required:
  200. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} is required')
  201. # the credential is not set currently, set the default value if needed
  202. if credential_schema.default is not None:
  203. default_value = credential_schema.default
  204. # parse default value into the correct type
  205. if credential_schema.type == ToolProviderCredentials.CredentialsType.SECRET_INPUT or \
  206. credential_schema.type == ToolProviderCredentials.CredentialsType.TEXT_INPUT or \
  207. credential_schema.type == ToolProviderCredentials.CredentialsType.SELECT:
  208. default_value = str(default_value)
  209. credentials[credential_name] = default_value
  210. def validate_credentials(self, credentials: Dict[str, Any]) -> None:
  211. """
  212. validate the credentials of the provider
  213. :param tool_name: the name of the tool, defined in `get_tools`
  214. :param credentials: the credentials of the tool
  215. """
  216. # validate credentials format
  217. self.validate_credentials_format(credentials)
  218. # validate credentials
  219. self._validate_credentials(credentials)
  220. @abstractmethod
  221. def _validate_credentials(self, credentials: Dict[str, Any]) -> None:
  222. """
  223. validate the credentials of the provider
  224. :param tool_name: the name of the tool, defined in `get_tools`
  225. :param credentials: the credentials of the tool
  226. """
  227. pass