api_tool.py 13 KB

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