api_tool.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import json
  2. from collections.abc import Generator
  3. from os import getenv
  4. from typing import Any
  5. from urllib.parse import urlencode
  6. import httpx
  7. import core.helper.ssrf_proxy as ssrf_proxy
  8. from core.tools.entities.tool_bundle import ApiToolBundle
  9. from core.tools.entities.tool_entities import ToolInvokeMessage, ToolProviderType
  10. from core.tools.errors import ToolInvokeError, ToolParameterValidationError, ToolProviderCredentialValidationError
  11. from core.tools.tool.tool import Tool
  12. API_TOOL_DEFAULT_TIMEOUT = (
  13. int(getenv('API_TOOL_DEFAULT_CONNECT_TIMEOUT', '10')),
  14. int(getenv('API_TOOL_DEFAULT_READ_TIMEOUT', '60'))
  15. )
  16. class ApiTool(Tool):
  17. api_bundle: ApiToolBundle
  18. """
  19. Api tool
  20. """
  21. def fork_tool_runtime(self, runtime: dict[str, Any]) -> 'Tool':
  22. """
  23. fork a new tool with meta data
  24. :param meta: the meta data of a tool call processing, tenant_id is required
  25. :return: the new tool
  26. """
  27. return self.__class__(
  28. identity=self.identity.model_copy() if self.identity else None,
  29. parameters=self.parameters.copy() if self.parameters else None,
  30. description=self.description.model_copy() if self.description else None,
  31. api_bundle=self.api_bundle.model_copy() if self.api_bundle else None,
  32. runtime=Tool.Runtime(**runtime)
  33. )
  34. def validate_credentials(self, credentials: dict[str, Any], parameters: dict[str, Any],
  35. format_only: bool = False) -> str:
  36. """
  37. validate the credentials for Api tool
  38. """
  39. # assemble validate request and request parameters
  40. headers = self.assembling_request(parameters)
  41. if format_only:
  42. return ''
  43. response = self.do_http_request(self.api_bundle.server_url, self.api_bundle.method, headers, parameters)
  44. # validate response
  45. return self.validate_and_parse_response(response)
  46. def tool_provider_type(self) -> ToolProviderType:
  47. return ToolProviderType.API
  48. def assembling_request(self, parameters: dict[str, Any]) -> dict[str, Any]:
  49. headers = {}
  50. credentials = self.runtime.credentials or {}
  51. if 'auth_type' not in credentials:
  52. raise ToolProviderCredentialValidationError('Missing auth_type')
  53. if credentials['auth_type'] == 'api_key':
  54. api_key_header = 'api_key'
  55. if 'api_key_header' in credentials:
  56. api_key_header = credentials['api_key_header']
  57. if 'api_key_value' not in credentials:
  58. raise ToolProviderCredentialValidationError('Missing api_key_value')
  59. elif not isinstance(credentials['api_key_value'], str):
  60. raise ToolProviderCredentialValidationError('api_key_value must be a string')
  61. if 'api_key_header_prefix' in credentials:
  62. api_key_header_prefix = credentials['api_key_header_prefix']
  63. if api_key_header_prefix == 'basic' and credentials['api_key_value']:
  64. credentials['api_key_value'] = f'Basic {credentials["api_key_value"]}'
  65. elif api_key_header_prefix == 'bearer' and credentials['api_key_value']:
  66. credentials['api_key_value'] = f'Bearer {credentials["api_key_value"]}'
  67. elif api_key_header_prefix == 'custom':
  68. pass
  69. headers[api_key_header] = credentials['api_key_value']
  70. needed_parameters = [parameter for parameter in self.api_bundle.parameters if parameter.required]
  71. for parameter in needed_parameters:
  72. if parameter.required and parameter.name not in parameters:
  73. raise ToolParameterValidationError(f"Missing required parameter {parameter.name}")
  74. if parameter.default is not None and parameter.name not in parameters:
  75. parameters[parameter.name] = parameter.default
  76. return headers
  77. def validate_and_parse_response(self, response: httpx.Response) -> str:
  78. """
  79. validate the response
  80. """
  81. if isinstance(response, httpx.Response):
  82. if response.status_code >= 400:
  83. raise ToolInvokeError(f"Request failed with status code {response.status_code} and {response.text}")
  84. if not response.content:
  85. return 'Empty response from the tool, please check your parameters and try again.'
  86. try:
  87. response = response.json()
  88. try:
  89. return json.dumps(response, ensure_ascii=False)
  90. except Exception as e:
  91. return json.dumps(response)
  92. except Exception as e:
  93. return response.text
  94. else:
  95. raise ValueError(f'Invalid response type {type(response)}')
  96. @staticmethod
  97. def get_parameter_value(parameter, parameters):
  98. if parameter['name'] in parameters:
  99. return parameters[parameter['name']]
  100. elif parameter.get('required', False):
  101. raise ToolParameterValidationError(f"Missing required parameter {parameter['name']}")
  102. else:
  103. return (parameter.get('schema', {}) or {}).get('default', '')
  104. def do_http_request(self, url: str, method: str, headers: dict[str, Any],
  105. parameters: dict[str, Any]) -> httpx.Response:
  106. """
  107. do http request depending on api bundle
  108. """
  109. method = method.lower()
  110. params = {}
  111. path_params = {}
  112. body = {}
  113. cookies = {}
  114. # check parameters
  115. for parameter in self.api_bundle.openapi.get('parameters', []):
  116. value = self.get_parameter_value(parameter, parameters)
  117. if parameter['in'] == 'path':
  118. path_params[parameter['name']] = value
  119. elif parameter['in'] == 'query':
  120. params[parameter['name']] = value
  121. elif parameter['in'] == 'cookie':
  122. cookies[parameter['name']] = value
  123. elif parameter['in'] == 'header':
  124. headers[parameter['name']] = value
  125. # check if there is a request body and handle it
  126. if 'requestBody' in self.api_bundle.openapi and self.api_bundle.openapi['requestBody'] is not None:
  127. # handle json request body
  128. if 'content' in self.api_bundle.openapi['requestBody']:
  129. for content_type in self.api_bundle.openapi['requestBody']['content']:
  130. headers['Content-Type'] = content_type
  131. body_schema = self.api_bundle.openapi['requestBody']['content'][content_type]['schema']
  132. required = body_schema.get('required', [])
  133. properties = body_schema.get('properties', {})
  134. for name, property in properties.items():
  135. if name in parameters:
  136. # convert type
  137. body[name] = self._convert_body_property_type(property, parameters[name])
  138. elif name in required:
  139. raise ToolParameterValidationError(
  140. f"Missing required parameter {name} in operation {self.api_bundle.operation_id}"
  141. )
  142. elif 'default' in property:
  143. body[name] = property['default']
  144. else:
  145. body[name] = None
  146. break
  147. # replace path parameters
  148. for name, value in path_params.items():
  149. url = url.replace(f'{{{name}}}', f'{value}')
  150. # parse http body data if needed, for GET/HEAD/OPTIONS/TRACE, the body is ignored
  151. if 'Content-Type' in headers:
  152. if headers['Content-Type'] == 'application/json':
  153. body = json.dumps(body)
  154. elif headers['Content-Type'] == 'application/x-www-form-urlencoded':
  155. body = urlencode(body)
  156. else:
  157. body = body
  158. if method in ('get', 'head', 'post', 'put', 'delete', 'patch'):
  159. response = getattr(ssrf_proxy, method)(url, params=params, headers=headers, cookies=cookies, data=body,
  160. timeout=API_TOOL_DEFAULT_TIMEOUT, follow_redirects=True)
  161. return response
  162. else:
  163. raise ValueError(f'Invalid http method {self.method}')
  164. def _convert_body_property_any_of(self, property: dict[str, Any], value: Any, any_of: list[dict[str, Any]],
  165. max_recursive=10) -> Any:
  166. if max_recursive <= 0:
  167. raise Exception("Max recursion depth reached")
  168. for option in any_of or []:
  169. try:
  170. if 'type' in option:
  171. # Attempt to convert the value based on the type.
  172. if option['type'] == 'integer' or option['type'] == 'int':
  173. return int(value)
  174. elif option['type'] == 'number':
  175. if '.' in str(value):
  176. return float(value)
  177. else:
  178. return int(value)
  179. elif option['type'] == 'string':
  180. return str(value)
  181. elif option['type'] == 'boolean':
  182. if str(value).lower() in ['true', '1']:
  183. return True
  184. elif str(value).lower() in ['false', '0']:
  185. return False
  186. else:
  187. continue # Not a boolean, try next option
  188. elif option['type'] == 'null' and not value:
  189. return None
  190. else:
  191. continue # Unsupported type, try next option
  192. elif 'anyOf' in option and isinstance(option['anyOf'], list):
  193. # Recursive call to handle nested anyOf
  194. return self._convert_body_property_any_of(property, value, option['anyOf'], max_recursive - 1)
  195. except ValueError:
  196. continue # Conversion failed, try next option
  197. # If no option succeeded, you might want to return the value as is or raise an error
  198. return value # or raise ValueError(f"Cannot convert value '{value}' to any specified type in anyOf")
  199. def _convert_body_property_type(self, property: dict[str, Any], value: Any) -> Any:
  200. try:
  201. if 'type' in property:
  202. if property['type'] == 'integer' or property['type'] == 'int':
  203. return int(value)
  204. elif property['type'] == 'number':
  205. # check if it is a float
  206. if '.' in value:
  207. return float(value)
  208. else:
  209. return int(value)
  210. elif property['type'] == 'string':
  211. return str(value)
  212. elif property['type'] == 'boolean':
  213. return bool(value)
  214. elif property['type'] == 'null':
  215. if value is None:
  216. return None
  217. elif property['type'] == 'object' or property['type'] == 'array':
  218. if isinstance(value, str):
  219. try:
  220. # an array str like '[1,2]' also can convert to list [1,2] through json.loads
  221. # json not support single quote, but we can support it
  222. value = value.replace("'", '"')
  223. return json.loads(value)
  224. except ValueError:
  225. return value
  226. elif isinstance(value, dict):
  227. return value
  228. else:
  229. return value
  230. else:
  231. raise ValueError(f"Invalid type {property['type']} for property {property}")
  232. elif 'anyOf' in property and isinstance(property['anyOf'], list):
  233. return self._convert_body_property_any_of(property, value, property['anyOf'])
  234. except ValueError as e:
  235. return value
  236. def _invoke(self, user_id: str, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]:
  237. """
  238. invoke http request
  239. """
  240. # assemble request
  241. headers = self.assembling_request(tool_parameters)
  242. # do http request
  243. response = self.do_http_request(self.api_bundle.server_url, self.api_bundle.method, headers, tool_parameters)
  244. # validate response
  245. response = self.validate_and_parse_response(response)
  246. # assemble invoke message
  247. yield self.create_text_message(response)