provider.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. super().__init__(
  31. entity=ToolProviderEntity(
  32. identity=provider_yaml["identity"],
  33. credentials_schema=provider_yaml.get("credentials_for_provider", {}) or {},
  34. ),
  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.entity.identity.name
  44. tool_path = path.join(path.dirname(path.realpath(__file__)), "providers", 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: type[BuiltinTool] = load_single_subclass_from_source(
  54. module_name=f"core.tools.builtin_tool.providers.{provider}.tools.{tool_name}",
  55. script_path=path.join(
  56. path.dirname(path.realpath(__file__)),
  57. "builtin_tool",
  58. "providers",
  59. provider,
  60. "tools",
  61. f"{tool_name}.py",
  62. ),
  63. parent_type=BuiltinTool,
  64. )
  65. tool["identity"]["provider"] = provider
  66. tools.append(
  67. assistant_tool_class(
  68. entity=ToolEntity(**tool),
  69. runtime=ToolRuntime(tenant_id=""),
  70. )
  71. )
  72. self.tools = tools
  73. return tools
  74. def get_credentials_schema(self) -> dict[str, ProviderConfig]:
  75. """
  76. returns the credentials schema of the provider
  77. :return: the credentials schema
  78. """
  79. if not self.entity.credentials_schema:
  80. return {}
  81. return self.entity.credentials_schema.copy()
  82. def get_tools(self) -> list[BuiltinTool]:
  83. """
  84. returns a list of tools that the provider can provide
  85. :return: list of tools
  86. """
  87. return self._get_builtin_tools()
  88. def get_tool(self, tool_name: str) -> BuiltinTool | None:
  89. """
  90. returns the tool that the provider can provide
  91. """
  92. return next(filter(lambda x: x.entity.identity.name == tool_name, self.get_tools()), None)
  93. @property
  94. def need_credentials(self) -> bool:
  95. """
  96. returns whether the provider needs credentials
  97. :return: whether the provider needs credentials
  98. """
  99. return self.entity.credentials_schema is not None and len(self.entity.credentials_schema) != 0
  100. @property
  101. def provider_type(self) -> ToolProviderType:
  102. """
  103. returns the type of the provider
  104. :return: type of the provider
  105. """
  106. return ToolProviderType.BUILT_IN
  107. @property
  108. def tool_labels(self) -> list[str]:
  109. """
  110. returns the labels of the provider
  111. :return: labels of the provider
  112. """
  113. label_enums = self._get_tool_labels()
  114. return [default_tool_label_dict[label].name for label in label_enums]
  115. def _get_tool_labels(self) -> list[ToolLabelEnum]:
  116. """
  117. returns the labels of the provider
  118. """
  119. return self.entity.identity.tags or []
  120. def validate_credentials(self, user_id: str, 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. # validate credentials format
  127. self.validate_credentials_format(credentials)
  128. # validate credentials
  129. self._validate_credentials(user_id, credentials)
  130. @abstractmethod
  131. def _validate_credentials(self, user_id: str, credentials: dict[str, Any]) -> None:
  132. """
  133. validate the credentials of the provider
  134. :param tool_name: the name of the tool, defined in `get_tools`
  135. :param credentials: the credentials of the tool
  136. """
  137. pass