api_tool_provider.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. from typing import Any
  2. from core.tools.entities.common_entities import I18nObject
  3. from core.tools.entities.tool_bundle import ApiBasedToolBundle
  4. from core.tools.entities.tool_entities import (
  5. ApiProviderAuthType,
  6. ToolCredentialsOption,
  7. ToolProviderCredentials,
  8. ToolProviderType,
  9. )
  10. from core.tools.provider.tool_provider import ToolProviderController
  11. from core.tools.tool.api_tool import ApiTool
  12. from core.tools.tool.tool import Tool
  13. from extensions.ext_database import db
  14. from models.tools import ApiToolProvider
  15. class ApiBasedToolProviderController(ToolProviderController):
  16. @staticmethod
  17. def from_db(db_provider: ApiToolProvider, auth_type: ApiProviderAuthType) -> 'ApiBasedToolProviderController':
  18. credentials_schema = {
  19. 'auth_type': ToolProviderCredentials(
  20. name='auth_type',
  21. required=True,
  22. type=ToolProviderCredentials.CredentialsType.SELECT,
  23. options=[
  24. ToolCredentialsOption(value='none', label=I18nObject(en_US='None', zh_Hans='无')),
  25. ToolCredentialsOption(value='api_key', label=I18nObject(en_US='api_key', zh_Hans='api_key'))
  26. ],
  27. default='none',
  28. help=I18nObject(
  29. en_US='The auth type of the api provider',
  30. zh_Hans='api provider 的认证类型'
  31. )
  32. )
  33. }
  34. if auth_type == ApiProviderAuthType.API_KEY:
  35. credentials_schema = {
  36. **credentials_schema,
  37. 'api_key_header': ToolProviderCredentials(
  38. name='api_key_header',
  39. required=False,
  40. default='api_key',
  41. type=ToolProviderCredentials.CredentialsType.TEXT_INPUT,
  42. help=I18nObject(
  43. en_US='The header name of the api key',
  44. zh_Hans='携带 api key 的 header 名称'
  45. )
  46. ),
  47. 'api_key_value': ToolProviderCredentials(
  48. name='api_key_value',
  49. required=True,
  50. type=ToolProviderCredentials.CredentialsType.SECRET_INPUT,
  51. help=I18nObject(
  52. en_US='The api key',
  53. zh_Hans='api key的值'
  54. )
  55. )
  56. }
  57. elif auth_type == ApiProviderAuthType.NONE:
  58. pass
  59. else:
  60. raise ValueError(f'invalid auth type {auth_type}')
  61. return ApiBasedToolProviderController(**{
  62. 'identity': {
  63. 'author': db_provider.user.name if db_provider.user_id and db_provider.user else '',
  64. 'name': db_provider.name,
  65. 'label': {
  66. 'en_US': db_provider.name,
  67. 'zh_Hans': db_provider.name
  68. },
  69. 'description': {
  70. 'en_US': db_provider.description,
  71. 'zh_Hans': db_provider.description
  72. },
  73. 'icon': db_provider.icon
  74. },
  75. 'credentials_schema': credentials_schema
  76. })
  77. @property
  78. def app_type(self) -> ToolProviderType:
  79. return ToolProviderType.API_BASED
  80. def _validate_credentials(self, tool_name: str, credentials: dict[str, Any]) -> None:
  81. pass
  82. def validate_parameters(self, tool_name: str, tool_parameters: dict[str, Any]) -> None:
  83. pass
  84. def _parse_tool_bundle(self, tool_bundle: ApiBasedToolBundle) -> ApiTool:
  85. """
  86. parse tool bundle to tool
  87. :param tool_bundle: the tool bundle
  88. :return: the tool
  89. """
  90. return ApiTool(**{
  91. 'api_bundle': tool_bundle,
  92. 'identity' : {
  93. 'author': tool_bundle.author,
  94. 'name': tool_bundle.operation_id,
  95. 'label': {
  96. 'en_US': tool_bundle.operation_id,
  97. 'zh_Hans': tool_bundle.operation_id
  98. },
  99. 'icon': tool_bundle.icon if tool_bundle.icon else ''
  100. },
  101. 'description': {
  102. 'human': {
  103. 'en_US': tool_bundle.summary or '',
  104. 'zh_Hans': tool_bundle.summary or ''
  105. },
  106. 'llm': tool_bundle.summary or ''
  107. },
  108. 'parameters' : tool_bundle.parameters if tool_bundle.parameters else [],
  109. })
  110. def load_bundled_tools(self, tools: list[ApiBasedToolBundle]) -> list[ApiTool]:
  111. """
  112. load bundled tools
  113. :param tools: the bundled tools
  114. :return: the tools
  115. """
  116. self.tools = [self._parse_tool_bundle(tool) for tool in tools]
  117. return self.tools
  118. def get_tools(self, user_id: str, tenant_id: str) -> list[ApiTool]:
  119. """
  120. fetch tools from database
  121. :param user_id: the user id
  122. :param tenant_id: the tenant id
  123. :return: the tools
  124. """
  125. if self.tools is not None:
  126. return self.tools
  127. tools: list[Tool] = []
  128. # get tenant api providers
  129. db_providers: list[ApiToolProvider] = db.session.query(ApiToolProvider).filter(
  130. ApiToolProvider.tenant_id == tenant_id,
  131. ApiToolProvider.name == self.identity.name
  132. ).all()
  133. if db_providers and len(db_providers) != 0:
  134. for db_provider in db_providers:
  135. for tool in db_provider.tools:
  136. assistant_tool = self._parse_tool_bundle(tool)
  137. assistant_tool.is_team_authorization = True
  138. tools.append(assistant_tool)
  139. self.tools = tools
  140. return tools
  141. def get_tool(self, tool_name: str) -> ApiTool:
  142. """
  143. get tool by name
  144. :param tool_name: the name of the tool
  145. :return: the tool
  146. """
  147. if self.tools is None:
  148. self.get_tools()
  149. for tool in self.tools:
  150. if tool.identity.name == tool_name:
  151. return tool
  152. raise ValueError(f'tool {tool_name} not found')