builtin_tool_provider.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. from abc import abstractmethod
  2. from os import listdir, path
  3. from typing import Any
  4. from core.tools.entities.api_entities import UserToolProviderCredentials
  5. from core.tools.entities.tool_entities import ToolParameter, ToolProviderCredentials, ToolProviderType
  6. from core.tools.entities.values import ToolLabelEnum, default_tool_label_dict
  7. from core.tools.errors import (
  8. ToolNotFoundError,
  9. ToolParameterValidationError,
  10. ToolProviderCredentialValidationError,
  11. ToolProviderNotFoundError,
  12. )
  13. from core.tools.provider.tool_provider import ToolProviderController
  14. from core.tools.tool.builtin_tool import BuiltinTool
  15. from core.tools.tool.tool import Tool
  16. from core.tools.utils.yaml_utils import load_yaml_file
  17. from core.utils.module_import_helper import load_single_subclass_from_source
  18. class BuiltinToolProviderController(ToolProviderController):
  19. def __init__(self, **data: Any) -> None:
  20. if self.provider_type == ToolProviderType.API or self.provider_type == ToolProviderType.APP:
  21. super().__init__(**data)
  22. return
  23. # load provider yaml
  24. provider = self.__class__.__module__.split('.')[-1]
  25. yaml_path = path.join(path.dirname(path.realpath(__file__)), 'builtin', provider, f'{provider}.yaml')
  26. try:
  27. provider_yaml = load_yaml_file(yaml_path)
  28. except Exception as e:
  29. raise ToolProviderNotFoundError(f'can not load provider yaml for {provider}: {e}')
  30. if 'credentials_for_provider' in provider_yaml and provider_yaml['credentials_for_provider'] is not None:
  31. # set credentials name
  32. for credential_name in provider_yaml['credentials_for_provider']:
  33. provider_yaml['credentials_for_provider'][credential_name]['name'] = credential_name
  34. super().__init__(**{
  35. 'identity': provider_yaml['identity'],
  36. 'credentials_schema': provider_yaml['credentials_for_provider'] if 'credentials_for_provider' in provider_yaml else None,
  37. })
  38. def _get_builtin_tools(self) -> list[Tool]:
  39. """
  40. returns a list of tools that the provider can provide
  41. :return: list of tools
  42. """
  43. if self.tools:
  44. return self.tools
  45. provider = self.identity.name
  46. tool_path = path.join(path.dirname(path.realpath(__file__)), "builtin", provider, "tools")
  47. # get all the yaml files in the tool path
  48. tool_files = list(filter(lambda x: x.endswith(".yaml") and not x.startswith("__"), listdir(tool_path)))
  49. tools = []
  50. for tool_file in tool_files:
  51. # get tool name
  52. tool_name = tool_file.split(".")[0]
  53. tool = load_yaml_file(path.join(tool_path, tool_file))
  54. # get tool class, import the module
  55. assistant_tool_class = load_single_subclass_from_source(
  56. module_name=f'core.tools.provider.builtin.{provider}.tools.{tool_name}',
  57. script_path=path.join(path.dirname(path.realpath(__file__)),
  58. 'builtin', provider, 'tools', f'{tool_name}.py'),
  59. parent_type=BuiltinTool)
  60. tool["identity"]["provider"] = provider
  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 \
  107. len(self.credentials_schema) != 0
  108. @property
  109. def provider_type(self) -> ToolProviderType:
  110. """
  111. returns the type of the provider
  112. :return: type of the provider
  113. """
  114. return ToolProviderType.BUILT_IN
  115. @property
  116. def tool_labels(self) -> list[str]:
  117. """
  118. returns the labels of the provider
  119. :return: labels of the provider
  120. """
  121. label_enums = self._get_tool_labels()
  122. return [default_tool_label_dict[label].name for label in label_enums]
  123. def _get_tool_labels(self) -> list[ToolLabelEnum]:
  124. """
  125. returns the labels of the provider
  126. """
  127. return self.identity.tags or []
  128. def validate_parameters(self, tool_id: int, tool_name: str, tool_parameters: dict[str, Any]) -> None:
  129. """
  130. validate the parameters of the tool and set the default value if needed
  131. :param tool_name: the name of the tool, defined in `get_tools`
  132. :param tool_parameters: the parameters of the tool
  133. """
  134. tool_parameters_schema = self.get_parameters(tool_name)
  135. tool_parameters_need_to_validate: dict[str, ToolParameter] = {}
  136. for parameter in tool_parameters_schema:
  137. tool_parameters_need_to_validate[parameter.name] = parameter
  138. for parameter in tool_parameters:
  139. if parameter not in tool_parameters_need_to_validate:
  140. raise ToolParameterValidationError(f'parameter {parameter} not found in tool {tool_name}')
  141. # check type
  142. parameter_schema = tool_parameters_need_to_validate[parameter]
  143. if parameter_schema.type == ToolParameter.ToolParameterType.STRING:
  144. if not isinstance(tool_parameters[parameter], str):
  145. raise ToolParameterValidationError(f'parameter {parameter} should be string')
  146. elif parameter_schema.type == ToolParameter.ToolParameterType.NUMBER:
  147. if not isinstance(tool_parameters[parameter], int | float):
  148. raise ToolParameterValidationError(f'parameter {parameter} should be number')
  149. if parameter_schema.min is not None and tool_parameters[parameter] < parameter_schema.min:
  150. raise ToolParameterValidationError(f'parameter {parameter} should be greater than {parameter_schema.min}')
  151. if parameter_schema.max is not None and tool_parameters[parameter] > parameter_schema.max:
  152. raise ToolParameterValidationError(f'parameter {parameter} should be less than {parameter_schema.max}')
  153. elif parameter_schema.type == ToolParameter.ToolParameterType.BOOLEAN:
  154. if not isinstance(tool_parameters[parameter], bool):
  155. raise ToolParameterValidationError(f'parameter {parameter} should be boolean')
  156. elif parameter_schema.type == ToolParameter.ToolParameterType.SELECT:
  157. if not isinstance(tool_parameters[parameter], str):
  158. raise ToolParameterValidationError(f'parameter {parameter} should be string')
  159. options = parameter_schema.options
  160. if not isinstance(options, list):
  161. raise ToolParameterValidationError(f'parameter {parameter} options should be list')
  162. if tool_parameters[parameter] not in [x.value for x in options]:
  163. raise ToolParameterValidationError(f'parameter {parameter} should be one of {options}')
  164. tool_parameters_need_to_validate.pop(parameter)
  165. for parameter in tool_parameters_need_to_validate:
  166. parameter_schema = tool_parameters_need_to_validate[parameter]
  167. if parameter_schema.required:
  168. raise ToolParameterValidationError(f'parameter {parameter} is required')
  169. # the parameter is not set currently, set the default value if needed
  170. if parameter_schema.default is not None:
  171. default_value = parameter_schema.default
  172. # parse default value into the correct type
  173. if parameter_schema.type == ToolParameter.ToolParameterType.STRING or \
  174. parameter_schema.type == ToolParameter.ToolParameterType.SELECT:
  175. default_value = str(default_value)
  176. elif parameter_schema.type == ToolParameter.ToolParameterType.NUMBER:
  177. default_value = float(default_value)
  178. elif parameter_schema.type == ToolParameter.ToolParameterType.BOOLEAN:
  179. default_value = bool(default_value)
  180. tool_parameters[parameter] = default_value
  181. def validate_credentials_format(self, credentials: dict[str, Any]) -> None:
  182. """
  183. validate the format of the credentials of the provider and set the default value if needed
  184. :param credentials: the credentials of the tool
  185. """
  186. credentials_schema = self.credentials_schema
  187. if credentials_schema is None:
  188. return
  189. credentials_need_to_validate: dict[str, ToolProviderCredentials] = {}
  190. for credential_name in credentials_schema:
  191. credentials_need_to_validate[credential_name] = credentials_schema[credential_name]
  192. for credential_name in credentials:
  193. if credential_name not in credentials_need_to_validate:
  194. raise ToolProviderCredentialValidationError(f'credential {credential_name} not found in provider {self.identity.name}')
  195. # check type
  196. credential_schema = credentials_need_to_validate[credential_name]
  197. if credential_schema == ToolProviderCredentials.CredentialsType.SECRET_INPUT or \
  198. credential_schema == ToolProviderCredentials.CredentialsType.TEXT_INPUT:
  199. if not isinstance(credentials[credential_name], str):
  200. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be string')
  201. elif credential_schema.type == ToolProviderCredentials.CredentialsType.SELECT:
  202. if not isinstance(credentials[credential_name], str):
  203. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be string')
  204. options = credential_schema.options
  205. if not isinstance(options, list):
  206. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} options should be list')
  207. if credentials[credential_name] not in [x.value for x in options]:
  208. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be one of {options}')
  209. elif credential_schema.type == ToolProviderCredentials.CredentialsType.BOOLEAN:
  210. if isinstance(credentials[credential_name], bool):
  211. pass
  212. elif isinstance(credentials[credential_name], str):
  213. if credentials[credential_name].lower() == 'true':
  214. credentials[credential_name] = True
  215. elif credentials[credential_name].lower() == 'false':
  216. credentials[credential_name] = False
  217. else:
  218. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be boolean')
  219. elif isinstance(credentials[credential_name], int):
  220. if credentials[credential_name] == 1:
  221. credentials[credential_name] = True
  222. elif credentials[credential_name] == 0:
  223. credentials[credential_name] = False
  224. else:
  225. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be boolean')
  226. else:
  227. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} should be boolean')
  228. if credentials[credential_name] or credentials[credential_name] == False:
  229. credentials_need_to_validate.pop(credential_name)
  230. for credential_name in credentials_need_to_validate:
  231. credential_schema = credentials_need_to_validate[credential_name]
  232. if credential_schema.required:
  233. raise ToolProviderCredentialValidationError(f'credential {credential_schema.label.en_US} is required')
  234. # the credential is not set currently, set the default value if needed
  235. if credential_schema.default is not None:
  236. default_value = credential_schema.default
  237. # parse default value into the correct type
  238. if credential_schema.type == ToolProviderCredentials.CredentialsType.SECRET_INPUT or \
  239. credential_schema.type == ToolProviderCredentials.CredentialsType.TEXT_INPUT or \
  240. credential_schema.type == ToolProviderCredentials.CredentialsType.SELECT:
  241. default_value = str(default_value)
  242. credentials[credential_name] = default_value
  243. def validate_credentials(self, credentials: dict[str, Any]) -> None:
  244. """
  245. validate the credentials of the provider
  246. :param tool_name: the name of the tool, defined in `get_tools`
  247. :param credentials: the credentials of the tool
  248. """
  249. # validate credentials format
  250. self.validate_credentials_format(credentials)
  251. # validate credentials
  252. self._validate_credentials(credentials)
  253. @abstractmethod
  254. def _validate_credentials(self, credentials: dict[str, Any]) -> None:
  255. """
  256. validate the credentials of the provider
  257. :param tool_name: the name of the tool, defined in `get_tools`
  258. :param credentials: the credentials of the tool
  259. """
  260. pass