tool_provider.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from abc import ABC, abstractmethod
  2. from typing import Any, Optional
  3. from pydantic import BaseModel
  4. from core.tools.entities.tool_entities import (
  5. ToolParameter,
  6. ToolProviderCredentials,
  7. ToolProviderIdentity,
  8. ToolProviderType,
  9. )
  10. from core.tools.errors import ToolNotFoundError, ToolParameterValidationError, ToolProviderCredentialValidationError
  11. from core.tools.tool.tool import Tool
  12. from core.tools.utils.tool_parameter_converter import ToolParameterConverter
  13. class ToolProviderController(BaseModel, ABC):
  14. identity: Optional[ToolProviderIdentity] = None
  15. tools: Optional[list[Tool]] = None
  16. credentials_schema: Optional[dict[str, ToolProviderCredentials]] = None
  17. def get_credentials_schema(self) -> dict[str, ToolProviderCredentials]:
  18. """
  19. returns the credentials schema of the provider
  20. :return: the credentials schema
  21. """
  22. return self.credentials_schema.copy()
  23. @abstractmethod
  24. def get_tools(self) -> list[Tool]:
  25. """
  26. returns a list of tools that the provider can provide
  27. :return: list of tools
  28. """
  29. pass
  30. @abstractmethod
  31. def get_tool(self, tool_name: str) -> Tool:
  32. """
  33. returns a tool that the provider can provide
  34. :return: tool
  35. """
  36. pass
  37. def get_parameters(self, tool_name: str) -> list[ToolParameter]:
  38. """
  39. returns the parameters of the tool
  40. :param tool_name: the name of the tool, defined in `get_tools`
  41. :return: list of parameters
  42. """
  43. tool = next(filter(lambda x: x.identity.name == tool_name, self.get_tools()), None)
  44. if tool is None:
  45. raise ToolNotFoundError(f"tool {tool_name} not found")
  46. return tool.parameters
  47. @property
  48. def provider_type(self) -> ToolProviderType:
  49. """
  50. returns the type of the provider
  51. :return: type of the provider
  52. """
  53. return ToolProviderType.BUILT_IN
  54. def validate_parameters(self, tool_id: int, tool_name: str, tool_parameters: dict[str, Any]) -> None:
  55. """
  56. validate the parameters of the tool and set the default value if needed
  57. :param tool_name: the name of the tool, defined in `get_tools`
  58. :param tool_parameters: the parameters of the tool
  59. """
  60. tool_parameters_schema = self.get_parameters(tool_name)
  61. tool_parameters_need_to_validate: dict[str, ToolParameter] = {}
  62. for parameter in tool_parameters_schema:
  63. tool_parameters_need_to_validate[parameter.name] = parameter
  64. for parameter in tool_parameters:
  65. if parameter not in tool_parameters_need_to_validate:
  66. raise ToolParameterValidationError(f"parameter {parameter} not found in tool {tool_name}")
  67. # check type
  68. parameter_schema = tool_parameters_need_to_validate[parameter]
  69. if parameter_schema.type == ToolParameter.ToolParameterType.STRING:
  70. if not isinstance(tool_parameters[parameter], str):
  71. raise ToolParameterValidationError(f"parameter {parameter} should be string")
  72. elif parameter_schema.type == ToolParameter.ToolParameterType.NUMBER:
  73. if not isinstance(tool_parameters[parameter], int | float):
  74. raise ToolParameterValidationError(f"parameter {parameter} should be number")
  75. if parameter_schema.min is not None and tool_parameters[parameter] < parameter_schema.min:
  76. raise ToolParameterValidationError(
  77. f"parameter {parameter} should be greater than {parameter_schema.min}"
  78. )
  79. if parameter_schema.max is not None and tool_parameters[parameter] > parameter_schema.max:
  80. raise ToolParameterValidationError(
  81. f"parameter {parameter} should be less than {parameter_schema.max}"
  82. )
  83. elif parameter_schema.type == ToolParameter.ToolParameterType.BOOLEAN:
  84. if not isinstance(tool_parameters[parameter], bool):
  85. raise ToolParameterValidationError(f"parameter {parameter} should be boolean")
  86. elif parameter_schema.type == ToolParameter.ToolParameterType.SELECT:
  87. if not isinstance(tool_parameters[parameter], str):
  88. raise ToolParameterValidationError(f"parameter {parameter} should be string")
  89. options = parameter_schema.options
  90. if not isinstance(options, list):
  91. raise ToolParameterValidationError(f"parameter {parameter} options should be list")
  92. if tool_parameters[parameter] not in [x.value for x in options]:
  93. raise ToolParameterValidationError(f"parameter {parameter} should be one of {options}")
  94. tool_parameters_need_to_validate.pop(parameter)
  95. for parameter in tool_parameters_need_to_validate:
  96. parameter_schema = tool_parameters_need_to_validate[parameter]
  97. if parameter_schema.required:
  98. raise ToolParameterValidationError(f"parameter {parameter} is required")
  99. # the parameter is not set currently, set the default value if needed
  100. if parameter_schema.default is not None:
  101. tool_parameters[parameter] = ToolParameterConverter.cast_parameter_by_type(
  102. parameter_schema.default, parameter_schema.type
  103. )
  104. def validate_credentials_format(self, credentials: dict[str, Any]) -> None:
  105. """
  106. validate the format of the credentials of the provider and set the default value if needed
  107. :param credentials: the credentials of the tool
  108. """
  109. credentials_schema = self.credentials_schema
  110. if credentials_schema is None:
  111. return
  112. credentials_need_to_validate: dict[str, ToolProviderCredentials] = {}
  113. for credential_name in credentials_schema:
  114. credentials_need_to_validate[credential_name] = credentials_schema[credential_name]
  115. for credential_name in credentials:
  116. if credential_name not in credentials_need_to_validate:
  117. raise ToolProviderCredentialValidationError(
  118. f"credential {credential_name} not found in provider {self.identity.name}"
  119. )
  120. # check type
  121. credential_schema = credentials_need_to_validate[credential_name]
  122. if credential_schema.type in {
  123. ToolProviderCredentials.CredentialsType.SECRET_INPUT,
  124. ToolProviderCredentials.CredentialsType.TEXT_INPUT,
  125. }:
  126. if not isinstance(credentials[credential_name], str):
  127. raise ToolProviderCredentialValidationError(f"credential {credential_name} should be string")
  128. elif credential_schema.type == ToolProviderCredentials.CredentialsType.SELECT:
  129. if not isinstance(credentials[credential_name], str):
  130. raise ToolProviderCredentialValidationError(f"credential {credential_name} should be string")
  131. options = credential_schema.options
  132. if not isinstance(options, list):
  133. raise ToolProviderCredentialValidationError(f"credential {credential_name} options should be list")
  134. if credentials[credential_name] not in [x.value for x in options]:
  135. raise ToolProviderCredentialValidationError(
  136. f"credential {credential_name} should be one of {options}"
  137. )
  138. credentials_need_to_validate.pop(credential_name)
  139. for credential_name in credentials_need_to_validate:
  140. credential_schema = credentials_need_to_validate[credential_name]
  141. if credential_schema.required:
  142. raise ToolProviderCredentialValidationError(f"credential {credential_name} is required")
  143. # the credential is not set currently, set the default value if needed
  144. if credential_schema.default is not None:
  145. default_value = credential_schema.default
  146. # parse default value into the correct type
  147. if credential_schema.type in {
  148. ToolProviderCredentials.CredentialsType.SECRET_INPUT,
  149. ToolProviderCredentials.CredentialsType.TEXT_INPUT,
  150. ToolProviderCredentials.CredentialsType.SELECT,
  151. }:
  152. default_value = str(default_value)
  153. credentials[credential_name] = default_value