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 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 (
  10. CredentialType,
  11. OAuthSchema,
  12. ToolEntity,
  13. ToolProviderEntity,
  14. ToolProviderType,
  15. )
  16. from core.tools.entities.values import ToolLabelEnum, default_tool_label_dict
  17. from core.tools.errors import (
  18. ToolProviderNotFoundError,
  19. )
  20. from core.tools.utils.yaml_utils import load_yaml_file
  21. class BuiltinToolProviderController(ToolProviderController):
  22. tools: list[BuiltinTool]
  23. def __init__(self, **data: Any) -> None:
  24. self.tools = []
  25. # load provider yaml
  26. provider = self.__class__.__module__.split(".")[-1]
  27. yaml_path = path.join(path.dirname(path.realpath(__file__)), "providers", provider, f"{provider}.yaml")
  28. try:
  29. provider_yaml = load_yaml_file(yaml_path, ignore_error=False)
  30. except Exception as e:
  31. raise ToolProviderNotFoundError(f"can not load provider yaml for {provider}: {e}")
  32. if "credentials_for_provider" in provider_yaml and provider_yaml["credentials_for_provider"] is not None:
  33. # set credentials name
  34. for credential_name in provider_yaml["credentials_for_provider"]:
  35. provider_yaml["credentials_for_provider"][credential_name]["name"] = credential_name
  36. credentials_schema = []
  37. for credential in provider_yaml.get("credentials_for_provider", {}):
  38. credential_dict = provider_yaml.get("credentials_for_provider", {}).get(credential, {})
  39. credentials_schema.append(credential_dict)
  40. oauth_schema = None
  41. if provider_yaml.get("oauth_schema", None) is not None:
  42. oauth_schema = OAuthSchema(
  43. client_schema=provider_yaml.get("oauth_schema", {}).get("client_schema", []),
  44. credentials_schema=provider_yaml.get("oauth_schema", {}).get("credentials_schema", []),
  45. )
  46. super().__init__(
  47. entity=ToolProviderEntity(
  48. identity=provider_yaml["identity"],
  49. credentials_schema=credentials_schema,
  50. oauth_schema=oauth_schema,
  51. ),
  52. )
  53. self._load_tools()
  54. def _load_tools(self):
  55. provider = self.entity.identity.name
  56. tool_path = path.join(path.dirname(path.realpath(__file__)), "providers", provider, "tools")
  57. # get all the yaml files in the tool path
  58. tool_files = list(filter(lambda x: x.endswith(".yaml") and not x.startswith("__"), listdir(tool_path)))
  59. tools = []
  60. for tool_file in tool_files:
  61. # get tool name
  62. tool_name = tool_file.split(".")[0]
  63. tool = load_yaml_file(path.join(tool_path, tool_file), ignore_error=False)
  64. # get tool class, import the module
  65. assistant_tool_class: type = load_single_subclass_from_source(
  66. module_name=f"core.tools.builtin_tool.providers.{provider}.tools.{tool_name}",
  67. script_path=path.join(
  68. path.dirname(path.realpath(__file__)),
  69. "builtin_tool",
  70. "providers",
  71. provider,
  72. "tools",
  73. f"{tool_name}.py",
  74. ),
  75. parent_type=BuiltinTool,
  76. )
  77. tool["identity"]["provider"] = provider
  78. tools.append(
  79. assistant_tool_class(
  80. provider=provider,
  81. entity=ToolEntity(**tool),
  82. runtime=ToolRuntime(tenant_id=""),
  83. )
  84. )
  85. self.tools = tools
  86. def _get_builtin_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.tools
  92. def get_credentials_schema(self) -> list[ProviderConfig]:
  93. """
  94. returns the credentials schema of the provider
  95. :return: the credentials schema
  96. """
  97. return self.get_credentials_schema_by_type(CredentialType.API_KEY.value)
  98. def get_credentials_schema_by_type(self, credential_type: str) -> list[ProviderConfig]:
  99. """
  100. returns the credentials schema of the provider
  101. :param credential_type: the type of the credential
  102. :return: the credentials schema of the provider
  103. """
  104. if credential_type == CredentialType.OAUTH2.value:
  105. return self.entity.oauth_schema.credentials_schema.copy() if self.entity.oauth_schema else []
  106. if credential_type == CredentialType.API_KEY.value:
  107. return self.entity.credentials_schema.copy() if self.entity.credentials_schema else []
  108. raise ValueError(f"Invalid credential type: {credential_type}")
  109. def get_oauth_client_schema(self) -> list[ProviderConfig]:
  110. """
  111. returns the oauth client schema of the provider
  112. :return: the oauth client schema
  113. """
  114. return self.entity.oauth_schema.client_schema.copy() if self.entity.oauth_schema else []
  115. def get_supported_credential_types(self) -> list[str]:
  116. """
  117. returns the credential support type of the provider
  118. """
  119. types = []
  120. if self.entity.credentials_schema is not None and len(self.entity.credentials_schema) > 0:
  121. types.append(CredentialType.API_KEY.value)
  122. if self.entity.oauth_schema is not None and len(self.entity.oauth_schema.credentials_schema) > 0:
  123. types.append(CredentialType.OAUTH2.value)
  124. return types
  125. def get_tools(self) -> list[BuiltinTool]:
  126. """
  127. returns a list of tools that the provider can provide
  128. :return: list of tools
  129. """
  130. return self._get_builtin_tools()
  131. def get_tool(self, tool_name: str) -> BuiltinTool | None: # type: ignore
  132. """
  133. returns the tool that the provider can provide
  134. """
  135. return next(filter(lambda x: x.entity.identity.name == tool_name, self.get_tools()), None) # type: ignore
  136. @property
  137. def need_credentials(self) -> bool:
  138. """
  139. returns whether the provider needs credentials
  140. :return: whether the provider needs credentials
  141. """
  142. return (
  143. self.entity.credentials_schema is not None
  144. and len(self.entity.credentials_schema) != 0
  145. or (self.entity.oauth_schema is not None and len(self.entity.oauth_schema.credentials_schema) != 0)
  146. )
  147. @property
  148. def provider_type(self) -> ToolProviderType:
  149. """
  150. returns the type of the provider
  151. :return: type of the provider
  152. """
  153. return ToolProviderType.BUILT_IN
  154. @property
  155. def tool_labels(self) -> list[str]:
  156. """
  157. returns the labels of the provider
  158. :return: labels of the provider
  159. """
  160. label_enums = self._get_tool_labels()
  161. return [default_tool_label_dict[label].name for label in label_enums]
  162. def _get_tool_labels(self) -> list[ToolLabelEnum]:
  163. """
  164. returns the labels of the provider
  165. """
  166. return self.entity.identity.tags or []
  167. def validate_credentials(self, user_id: str, credentials: dict[str, Any]) -> None:
  168. """
  169. validate the credentials of the provider
  170. :param user_id: use id
  171. :param credentials: the credentials of the tool
  172. """
  173. # validate credentials format
  174. self.validate_credentials_format(credentials)
  175. # validate credentials
  176. self._validate_credentials(user_id, credentials)
  177. @abstractmethod
  178. def _validate_credentials(self, user_id: str, credentials: dict[str, Any]) -> None:
  179. """
  180. validate the credentials of the provider
  181. :param user_id: use id
  182. :param credentials: the credentials of the tool
  183. """
  184. pass