provider.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. from abc import abstractmethod
  2. from os import listdir, path
  3. from typing import Any
  4. from core.entities.provider_entities import ProviderConfig
  5. from core.helper.module_import_helper import load_single_subclass_from_source
  6. from core.tools.__base.tool_provider import ToolProviderController
  7. from core.tools.__base.tool_runtime import ToolRuntime
  8. from core.tools.builtin_tool.tool import BuiltinTool
  9. from core.tools.entities.tool_entities import ToolEntity, ToolProviderEntity, ToolProviderType
  10. from core.tools.entities.values import ToolLabelEnum, default_tool_label_dict
  11. from core.tools.errors import (
  12. ToolProviderNotFoundError,
  13. )
  14. from core.tools.utils.yaml_utils import load_yaml_file
  15. class BuiltinToolProviderController(ToolProviderController):
  16. tools: list[BuiltinTool]
  17. def __init__(self, **data: Any) -> None:
  18. self.tools = []
  19. # load provider yaml
  20. provider = self.__class__.__module__.split(".")[-1]
  21. yaml_path = path.join(path.dirname(path.realpath(__file__)), "providers", provider, f"{provider}.yaml")
  22. try:
  23. provider_yaml = load_yaml_file(yaml_path, ignore_error=False)
  24. except Exception as e:
  25. raise ToolProviderNotFoundError(f"can not load provider yaml for {provider}: {e}")
  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. credentials_schema = []
  31. for credential in provider_yaml.get("credentials_for_provider", {}):
  32. credentials_schema.append(credential)
  33. super().__init__(
  34. entity=ToolProviderEntity(
  35. identity=provider_yaml["identity"],
  36. credentials_schema=credentials_schema,
  37. ),
  38. )
  39. self._load_tools()
  40. def _load_tools(self):
  41. provider = self.entity.identity.name
  42. tool_path = path.join(path.dirname(path.realpath(__file__)), "providers", 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. # get tool name
  48. tool_name = tool_file.split(".")[0]
  49. tool = load_yaml_file(path.join(tool_path, tool_file), ignore_error=False)
  50. # get tool class, import the module
  51. assistant_tool_class: type[BuiltinTool] = load_single_subclass_from_source(
  52. module_name=f"core.tools.builtin_tool.providers.{provider}.tools.{tool_name}",
  53. script_path=path.join(
  54. path.dirname(path.realpath(__file__)),
  55. "builtin_tool",
  56. "providers",
  57. provider,
  58. "tools",
  59. f"{tool_name}.py",
  60. ),
  61. parent_type=BuiltinTool,
  62. )
  63. tool["identity"]["provider"] = provider
  64. tools.append(
  65. assistant_tool_class(
  66. provider=provider,
  67. entity=ToolEntity(**tool),
  68. runtime=ToolRuntime(tenant_id=""),
  69. )
  70. )
  71. self.tools = tools
  72. def _get_builtin_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.tools
  78. def get_credentials_schema(self) -> list[ProviderConfig]:
  79. """
  80. returns the credentials schema of the provider
  81. :return: the credentials schema
  82. """
  83. if not self.entity.credentials_schema:
  84. return []
  85. return self.entity.credentials_schema.copy()
  86. def get_tools(self) -> list[BuiltinTool]:
  87. """
  88. returns a list of tools that the provider can provide
  89. :return: list of tools
  90. """
  91. return self._get_builtin_tools()
  92. def get_tool(self, tool_name: str) -> BuiltinTool | None: # type: ignore
  93. """
  94. returns the tool that the provider can provide
  95. """
  96. return next(filter(lambda x: x.entity.identity.name == tool_name, self.get_tools()), None) # type: ignore
  97. @property
  98. def need_credentials(self) -> bool:
  99. """
  100. returns whether the provider needs credentials
  101. :return: whether the provider needs credentials
  102. """
  103. return self.entity.credentials_schema is not None and len(self.entity.credentials_schema) != 0
  104. @property
  105. def provider_type(self) -> ToolProviderType:
  106. """
  107. returns the type of the provider
  108. :return: type of the provider
  109. """
  110. return ToolProviderType.BUILT_IN
  111. @property
  112. def tool_labels(self) -> list[str]:
  113. """
  114. returns the labels of the provider
  115. :return: labels of the provider
  116. """
  117. label_enums = self._get_tool_labels()
  118. return [default_tool_label_dict[label].name for label in label_enums]
  119. def _get_tool_labels(self) -> list[ToolLabelEnum]:
  120. """
  121. returns the labels of the provider
  122. """
  123. return self.entity.identity.tags or []
  124. def validate_credentials(self, user_id: str, credentials: dict[str, Any]) -> None:
  125. """
  126. validate the credentials of the provider
  127. :param tool_name: the name of the tool, defined in `get_tools`
  128. :param credentials: the credentials of the tool
  129. """
  130. # validate credentials format
  131. self.validate_credentials_format(credentials)
  132. # validate credentials
  133. self._validate_credentials(user_id, credentials)
  134. @abstractmethod
  135. def _validate_credentials(self, user_id: str, credentials: dict[str, Any]) -> None:
  136. """
  137. validate the credentials of the provider
  138. :param tool_name: the name of the tool, defined in `get_tools`
  139. :param credentials: the credentials of the tool
  140. """
  141. pass