api_tool.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import json
  2. from os import getenv
  3. from typing import Any
  4. from urllib.parse import urlencode
  5. import httpx
  6. from core.helper import 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(
  34. self, credentials: dict[str, Any], parameters: dict[str, Any], format_only: bool = False
  35. ) -> 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(
  105. self, url: str, method: str, headers: dict[str, Any], parameters: dict[str, Any]
  106. ) -> httpx.Response:
  107. """
  108. do http request depending on api bundle
  109. """
  110. method = method.lower()
  111. params = {}
  112. path_params = {}
  113. body = {}
  114. cookies = {}
  115. # check parameters
  116. for parameter in self.api_bundle.openapi.get("parameters", []):
  117. value = self.get_parameter_value(parameter, parameters)
  118. if parameter["in"] == "path":
  119. path_params[parameter["name"]] = value
  120. elif parameter["in"] == "query":
  121. if value != "":
  122. params[parameter["name"]] = value
  123. elif parameter["in"] == "cookie":
  124. cookies[parameter["name"]] = value
  125. elif parameter["in"] == "header":
  126. headers[parameter["name"]] = value
  127. # check if there is a request body and handle it
  128. if "requestBody" in self.api_bundle.openapi and self.api_bundle.openapi["requestBody"] is not None:
  129. # handle json request body
  130. if "content" in self.api_bundle.openapi["requestBody"]:
  131. for content_type in self.api_bundle.openapi["requestBody"]["content"]:
  132. headers["Content-Type"] = content_type
  133. body_schema = self.api_bundle.openapi["requestBody"]["content"][content_type]["schema"]
  134. required = body_schema.get("required", [])
  135. properties = body_schema.get("properties", {})
  136. for name, property in properties.items():
  137. if name in parameters:
  138. # convert type
  139. body[name] = self._convert_body_property_type(property, parameters[name])
  140. elif name in required:
  141. raise ToolParameterValidationError(
  142. f"Missing required parameter {name} in operation {self.api_bundle.operation_id}"
  143. )
  144. elif "default" in property:
  145. body[name] = property["default"]
  146. else:
  147. body[name] = None
  148. break
  149. # replace path parameters
  150. for name, value in path_params.items():
  151. url = url.replace(f"{{{name}}}", f"{value}")
  152. # parse http body data if needed, for GET/HEAD/OPTIONS/TRACE, the body is ignored
  153. if "Content-Type" in headers:
  154. if headers["Content-Type"] == "application/json":
  155. body = json.dumps(body)
  156. elif headers["Content-Type"] == "application/x-www-form-urlencoded":
  157. body = urlencode(body)
  158. else:
  159. body = body
  160. if method in {"get", "head", "post", "put", "delete", "patch"}:
  161. response = getattr(ssrf_proxy, method)(
  162. url,
  163. params=params,
  164. headers=headers,
  165. cookies=cookies,
  166. data=body,
  167. timeout=API_TOOL_DEFAULT_TIMEOUT,
  168. follow_redirects=True,
  169. )
  170. return response
  171. else:
  172. raise ValueError(f"Invalid http method {self.method}")
  173. def _convert_body_property_any_of(
  174. self, property: dict[str, Any], value: Any, any_of: list[dict[str, Any]], max_recursive=10
  175. ) -> Any:
  176. if max_recursive <= 0:
  177. raise Exception("Max recursion depth reached")
  178. for option in any_of or []:
  179. try:
  180. if "type" in option:
  181. # Attempt to convert the value based on the type.
  182. if option["type"] == "integer" or option["type"] == "int":
  183. return int(value)
  184. elif option["type"] == "number":
  185. if "." in str(value):
  186. return float(value)
  187. else:
  188. return int(value)
  189. elif option["type"] == "string":
  190. return str(value)
  191. elif option["type"] == "boolean":
  192. if str(value).lower() in {"true", "1"}:
  193. return True
  194. elif str(value).lower() in {"false", "0"}:
  195. return False
  196. else:
  197. continue # Not a boolean, try next option
  198. elif option["type"] == "null" and not value:
  199. return None
  200. else:
  201. continue # Unsupported type, try next option
  202. elif "anyOf" in option and isinstance(option["anyOf"], list):
  203. # Recursive call to handle nested anyOf
  204. return self._convert_body_property_any_of(property, value, option["anyOf"], max_recursive - 1)
  205. except ValueError:
  206. continue # Conversion failed, try next option
  207. # If no option succeeded, you might want to return the value as is or raise an error
  208. return value # or raise ValueError(f"Cannot convert value '{value}' to any specified type in anyOf")
  209. def _convert_body_property_type(self, property: dict[str, Any], value: Any) -> Any:
  210. try:
  211. if "type" in property:
  212. if property["type"] == "integer" or property["type"] == "int":
  213. return int(value)
  214. elif property["type"] == "number":
  215. # check if it is a float
  216. if "." in str(value):
  217. return float(value)
  218. else:
  219. return int(value)
  220. elif property["type"] == "string":
  221. return str(value)
  222. elif property["type"] == "boolean":
  223. return bool(value)
  224. elif property["type"] == "null":
  225. if value is None:
  226. return None
  227. elif property["type"] == "object" or property["type"] == "array":
  228. if isinstance(value, str):
  229. try:
  230. # an array str like '[1,2]' also can convert to list [1,2] through json.loads
  231. # json not support single quote, but we can support it
  232. value = value.replace("'", '"')
  233. return json.loads(value)
  234. except ValueError:
  235. return value
  236. elif isinstance(value, dict):
  237. return value
  238. else:
  239. return value
  240. else:
  241. raise ValueError(f"Invalid type {property['type']} for property {property}")
  242. elif "anyOf" in property and isinstance(property["anyOf"], list):
  243. return self._convert_body_property_any_of(property, value, property["anyOf"])
  244. except ValueError as e:
  245. return value
  246. def _invoke(self, user_id: str, tool_parameters: dict[str, Any]) -> ToolInvokeMessage | list[ToolInvokeMessage]:
  247. """
  248. invoke http request
  249. """
  250. # assemble request
  251. headers = self.assembling_request(tool_parameters)
  252. # do http request
  253. response = self.do_http_request(self.api_bundle.server_url, self.api_bundle.method, headers, tool_parameters)
  254. # validate response
  255. response = self.validate_and_parse_response(response)
  256. # assemble invoke message
  257. return self.create_text_message(response)