api_tool.py 14 KB

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