builtin_tool_provider.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. from abc import abstractmethod
  2. from os import listdir, path
  3. from typing import Any
  4. from pydantic import Field
  5. from core.entities.provider_entities import ProviderConfig
  6. from core.helper.module_import_helper import load_single_subclass_from_source
  7. from core.tools.entities.tool_entities import ToolProviderType
  8. from core.tools.entities.values import ToolLabelEnum, default_tool_label_dict
  9. from core.tools.errors import (
  10. ToolProviderNotFoundError,
  11. )
  12. from core.tools.provider.tool_provider import ToolProviderController
  13. from core.tools.tool.builtin_tool import BuiltinTool
  14. from core.tools.utils.yaml_utils import load_yaml_file
  15. class BuiltinToolProviderController(ToolProviderController):
  16. tools: list[BuiltinTool] = Field(default_factory=list)
  17. def __init__(self, **data: Any) -> None:
  18. if self.provider_type == ToolProviderType.API or self.provider_type == ToolProviderType.APP:
  19. super().__init__(**data)
  20. return
  21. # load provider yaml
  22. provider = self.__class__.__module__.split('.')[-1]
  23. yaml_path = path.join(path.dirname(path.realpath(__file__)), 'builtin', provider, f'{provider}.yaml')
  24. try:
  25. provider_yaml = load_yaml_file(yaml_path, ignore_error=False)
  26. except Exception as e:
  27. raise ToolProviderNotFoundError(f'can not load provider yaml for {provider}: {e}')
  28. if 'credentials_for_provider' in provider_yaml and provider_yaml['credentials_for_provider'] is not None:
  29. # set credentials name
  30. for credential_name in provider_yaml['credentials_for_provider']:
  31. provider_yaml['credentials_for_provider'][credential_name]['name'] = credential_name
  32. super().__init__(**{
  33. 'identity': provider_yaml['identity'],
  34. 'credentials_schema': provider_yaml.get('credentials_for_provider', {}) or {},
  35. })
  36. def _get_builtin_tools(self) -> list[BuiltinTool]:
  37. """
  38. returns a list of tools that the provider can provide
  39. :return: list of tools
  40. """
  41. if self.tools:
  42. return self.tools
  43. provider = self.identity.name
  44. tool_path = path.join(path.dirname(path.realpath(__file__)), "builtin", provider, "tools")
  45. # get all the yaml files in the tool path
  46. tool_files = list(filter(lambda x: x.endswith(".yaml") and not x.startswith("__"), listdir(tool_path)))
  47. tools = []
  48. for tool_file in tool_files:
  49. # get tool name
  50. tool_name = tool_file.split(".")[0]
  51. tool = load_yaml_file(path.join(tool_path, tool_file), ignore_error=False)
  52. # get tool class, import the module
  53. assistant_tool_class = load_single_subclass_from_source(
  54. module_name=f'core.tools.provider.builtin.{provider}.tools.{tool_name}',
  55. script_path=path.join(path.dirname(path.realpath(__file__)),
  56. 'builtin', provider, 'tools', f'{tool_name}.py'),
  57. parent_type=BuiltinTool)
  58. tool["identity"]["provider"] = provider
  59. tools.append(assistant_tool_class(**tool))
  60. self.tools = tools
  61. return tools
  62. def get_credentials_schema(self) -> dict[str, ProviderConfig]:
  63. """
  64. returns the credentials schema of the provider
  65. :return: the credentials schema
  66. """
  67. if not self.credentials_schema:
  68. return {}
  69. return self.credentials_schema.copy()
  70. def get_tools(self) -> list[BuiltinTool]:
  71. """
  72. returns a list of tools that the provider can provide
  73. :return: list of tools
  74. """
  75. return self._get_builtin_tools()
  76. def get_tool(self, tool_name: str) -> BuiltinTool | None:
  77. """
  78. returns the tool that the provider can provide
  79. """
  80. return next(filter(lambda x: x.identity.name == tool_name, self.get_tools()), None)
  81. @property
  82. def need_credentials(self) -> bool:
  83. """
  84. returns whether the provider needs credentials
  85. :return: whether the provider needs credentials
  86. """
  87. return self.credentials_schema is not None and \
  88. len(self.credentials_schema) != 0
  89. @property
  90. def provider_type(self) -> ToolProviderType:
  91. """
  92. returns the type of the provider
  93. :return: type of the provider
  94. """
  95. return ToolProviderType.BUILT_IN
  96. @property
  97. def tool_labels(self) -> list[str]:
  98. """
  99. returns the labels of the provider
  100. :return: labels of the provider
  101. """
  102. label_enums = self._get_tool_labels()
  103. return [default_tool_label_dict[label].name for label in label_enums]
  104. def _get_tool_labels(self) -> list[ToolLabelEnum]:
  105. """
  106. returns the labels of the provider
  107. """
  108. return self.identity.tags or []
  109. def validate_credentials(self, credentials: dict[str, Any]) -> None:
  110. """
  111. validate the credentials of the provider
  112. :param tool_name: the name of the tool, defined in `get_tools`
  113. :param credentials: the credentials of the tool
  114. """
  115. # validate credentials format
  116. self.validate_credentials_format(credentials)
  117. # validate credentials
  118. self._validate_credentials(credentials)
  119. @abstractmethod
  120. def _validate_credentials(self, credentials: dict[str, Any]) -> None:
  121. """
  122. validate the credentials of the provider
  123. :param tool_name: the name of the tool, defined in `get_tools`
  124. :param credentials: the credentials of the tool
  125. """
  126. pass