api_tool.py 13 KB

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