You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

provider.py 6.0KB

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