tool_provider.py 8.4 KB

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