builtin_tool_provider.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 in {ToolProviderType.API, 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(
  56. path.dirname(path.realpath(__file__)), "builtin", provider, "tools", f"{tool_name}.py"
  57. ),
  58. parent_type=BuiltinTool,
  59. )
  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, ProviderConfig]:
  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 get_tools(self) -> list[BuiltinTool]:
  73. """
  74. returns a list of tools that the provider can provide
  75. :return: list of tools
  76. """
  77. return self._get_builtin_tools()
  78. def get_tool(self, tool_name: str) -> BuiltinTool | None:
  79. """
  80. returns the tool that the provider can provide
  81. """
  82. return next(filter(lambda x: x.identity.name == tool_name, self.get_tools()), None)
  83. @property
  84. def need_credentials(self) -> bool:
  85. """
  86. returns whether the provider needs credentials
  87. :return: whether the provider needs credentials
  88. """
  89. return self.credentials_schema is not None and len(self.credentials_schema) != 0
  90. @property
  91. def provider_type(self) -> ToolProviderType:
  92. """
  93. returns the type of the provider
  94. :return: type of the provider
  95. """
  96. return ToolProviderType.BUILT_IN
  97. @property
  98. def tool_labels(self) -> list[str]:
  99. """
  100. returns the labels of the provider
  101. :return: labels of the provider
  102. """
  103. label_enums = self._get_tool_labels()
  104. return [default_tool_label_dict[label].name for label in label_enums]
  105. def _get_tool_labels(self) -> list[ToolLabelEnum]:
  106. """
  107. returns the labels of the provider
  108. """
  109. return self.identity.tags or []
  110. def validate_credentials(self, credentials: dict[str, Any]) -> None:
  111. """
  112. validate the credentials of the provider
  113. :param tool_name: the name of the tool, defined in `get_tools`
  114. :param credentials: the credentials of the tool
  115. """
  116. # validate credentials format
  117. self.validate_credentials_format(credentials)
  118. # validate credentials
  119. self._validate_credentials(credentials)
  120. @abstractmethod
  121. def _validate_credentials(self, credentials: dict[str, Any]) -> None:
  122. """
  123. validate the credentials of the provider
  124. :param tool_name: the name of the tool, defined in `get_tools`
  125. :param credentials: the credentials of the tool
  126. """
  127. pass