provider.py 5.9 KB

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