You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import json
  2. from collections.abc import Generator
  3. from os import getenv
  4. from typing import Any, Optional
  5. from urllib.parse import urlencode
  6. import httpx
  7. from core.file.file_manager import download
  8. from core.helper import ssrf_proxy
  9. from core.tools.__base.tool import Tool
  10. from core.tools.__base.tool_runtime import ToolRuntime
  11. from core.tools.entities.tool_bundle import ApiToolBundle
  12. from core.tools.entities.tool_entities import ToolEntity, ToolInvokeMessage, ToolProviderType
  13. from core.tools.errors import ToolInvokeError, ToolParameterValidationError, ToolProviderCredentialValidationError
  14. API_TOOL_DEFAULT_TIMEOUT = (
  15. int(getenv("API_TOOL_DEFAULT_CONNECT_TIMEOUT", "10")),
  16. int(getenv("API_TOOL_DEFAULT_READ_TIMEOUT", "60")),
  17. )
  18. class ApiTool(Tool):
  19. """
  20. Api tool
  21. """
  22. def __init__(self, entity: ToolEntity, api_bundle: ApiToolBundle, runtime: ToolRuntime, provider_id: str):
  23. super().__init__(entity, runtime)
  24. self.api_bundle = api_bundle
  25. self.provider_id = provider_id
  26. def fork_tool_runtime(self, runtime: ToolRuntime):
  27. """
  28. fork a new tool with metadata
  29. :return: the new tool
  30. """
  31. if self.api_bundle is None:
  32. raise ValueError("api_bundle is required")
  33. return self.__class__(
  34. entity=self.entity,
  35. api_bundle=self.api_bundle.model_copy(),
  36. runtime=runtime,
  37. provider_id=self.provider_id,
  38. )
  39. def validate_credentials(
  40. self, credentials: dict[str, Any], parameters: dict[str, Any], format_only: bool = False
  41. ) -> str:
  42. """
  43. validate the credentials for Api tool
  44. """
  45. # assemble validate request and request parameters
  46. headers = self.assembling_request(parameters)
  47. if format_only:
  48. return ""
  49. response = self.do_http_request(self.api_bundle.server_url, self.api_bundle.method, headers, parameters)
  50. # validate response
  51. return self.validate_and_parse_response(response)
  52. def tool_provider_type(self) -> ToolProviderType:
  53. return ToolProviderType.API
  54. def assembling_request(self, parameters: dict[str, Any]) -> dict[str, Any]:
  55. if self.runtime is None:
  56. raise ToolProviderCredentialValidationError("runtime not initialized")
  57. headers = {}
  58. if self.runtime is None:
  59. raise ValueError("runtime is required")
  60. credentials = self.runtime.credentials or {}
  61. if "auth_type" not in credentials:
  62. raise ToolProviderCredentialValidationError("Missing auth_type")
  63. if credentials["auth_type"] in ("api_key_header", "api_key"): # backward compatibility:
  64. api_key_header = "Authorization"
  65. if "api_key_header" in credentials:
  66. api_key_header = credentials["api_key_header"]
  67. if "api_key_value" not in credentials:
  68. raise ToolProviderCredentialValidationError("Missing api_key_value")
  69. elif not isinstance(credentials["api_key_value"], str):
  70. raise ToolProviderCredentialValidationError("api_key_value must be a string")
  71. if "api_key_header_prefix" in credentials:
  72. api_key_header_prefix = credentials["api_key_header_prefix"]
  73. if api_key_header_prefix == "basic" and credentials["api_key_value"]:
  74. credentials["api_key_value"] = f"Basic {credentials['api_key_value']}"
  75. elif api_key_header_prefix == "bearer" and credentials["api_key_value"]:
  76. credentials["api_key_value"] = f"Bearer {credentials['api_key_value']}"
  77. elif api_key_header_prefix == "custom":
  78. pass
  79. headers[api_key_header] = credentials["api_key_value"]
  80. elif credentials["auth_type"] == "api_key_query":
  81. # For query parameter authentication, we don't add anything to headers
  82. # The query parameter will be added in do_http_request method
  83. pass
  84. needed_parameters = [parameter for parameter in (self.api_bundle.parameters or []) if parameter.required]
  85. for parameter in needed_parameters:
  86. if parameter.required and parameter.name not in parameters:
  87. if parameter.default is not None:
  88. parameters[parameter.name] = parameter.default
  89. else:
  90. raise ToolParameterValidationError(f"Missing required parameter {parameter.name}")
  91. return headers
  92. def validate_and_parse_response(self, response: httpx.Response) -> str:
  93. """
  94. validate the response
  95. """
  96. if isinstance(response, httpx.Response):
  97. if response.status_code >= 400:
  98. raise ToolInvokeError(f"Request failed with status code {response.status_code} and {response.text}")
  99. if not response.content:
  100. return "Empty response from the tool, please check your parameters and try again."
  101. try:
  102. response = response.json()
  103. try:
  104. return json.dumps(response, ensure_ascii=False)
  105. except Exception:
  106. return json.dumps(response)
  107. except Exception:
  108. return response.text
  109. else:
  110. raise ValueError(f"Invalid response type {type(response)}")
  111. @staticmethod
  112. def get_parameter_value(parameter, parameters):
  113. if parameter["name"] in parameters:
  114. return parameters[parameter["name"]]
  115. elif parameter.get("required", False):
  116. raise ToolParameterValidationError(f"Missing required parameter {parameter['name']}")
  117. else:
  118. return (parameter.get("schema", {}) or {}).get("default", "")
  119. def do_http_request(
  120. self, url: str, method: str, headers: dict[str, Any], parameters: dict[str, Any]
  121. ) -> httpx.Response:
  122. """
  123. do http request depending on api bundle
  124. """
  125. method = method.lower()
  126. params = {}
  127. path_params = {}
  128. # FIXME: body should be a dict[str, Any] but it changed a lot in this function
  129. body: Any = {}
  130. cookies = {}
  131. files = []
  132. # Add API key to query parameters if auth_type is api_key_query
  133. if self.runtime and self.runtime.credentials:
  134. credentials = self.runtime.credentials
  135. if credentials.get("auth_type") == "api_key_query":
  136. api_key_query_param = credentials.get("api_key_query_param", "key")
  137. api_key_value = credentials.get("api_key_value")
  138. if api_key_value:
  139. params[api_key_query_param] = api_key_value
  140. # check parameters
  141. for parameter in self.api_bundle.openapi.get("parameters", []):
  142. value = self.get_parameter_value(parameter, parameters)
  143. if parameter["in"] == "path":
  144. path_params[parameter["name"]] = value
  145. elif parameter["in"] == "query":
  146. if value != "":
  147. params[parameter["name"]] = value
  148. elif parameter["in"] == "cookie":
  149. cookies[parameter["name"]] = value
  150. elif parameter["in"] == "header":
  151. headers[parameter["name"]] = str(value)
  152. # check if there is a request body and handle it
  153. if "requestBody" in self.api_bundle.openapi and self.api_bundle.openapi["requestBody"] is not None:
  154. # handle json request body
  155. if "content" in self.api_bundle.openapi["requestBody"]:
  156. for content_type in self.api_bundle.openapi["requestBody"]["content"]:
  157. headers["Content-Type"] = content_type
  158. body_schema = self.api_bundle.openapi["requestBody"]["content"][content_type]["schema"]
  159. # handle ref schema
  160. if "$ref" in body_schema:
  161. ref_path = body_schema["$ref"].split("/")
  162. ref_name = ref_path[-1]
  163. if (
  164. "components" in self.api_bundle.openapi
  165. and "schemas" in self.api_bundle.openapi["components"]
  166. ):
  167. if ref_name in self.api_bundle.openapi["components"]["schemas"]:
  168. body_schema = self.api_bundle.openapi["components"]["schemas"][ref_name]
  169. required = body_schema.get("required", [])
  170. properties = body_schema.get("properties", {})
  171. for name, property in properties.items():
  172. if name in parameters:
  173. # multiple file upload: if the type is array and the items have format as binary
  174. if property.get("type") == "array" and property.get("items", {}).get("format") == "binary":
  175. # parameters[name] should be a list of file objects.
  176. for f in parameters[name]:
  177. files.append((name, (f.filename, download(f), f.mime_type)))
  178. elif property.get("format") == "binary":
  179. f = parameters[name]
  180. files.append((name, (f.filename, download(f), f.mime_type)))
  181. elif "$ref" in property:
  182. body[name] = parameters[name]
  183. else:
  184. # convert type
  185. body[name] = self._convert_body_property_type(property, parameters[name])
  186. elif name in required:
  187. raise ToolParameterValidationError(
  188. f"Missing required parameter {name} in operation {self.api_bundle.operation_id}"
  189. )
  190. elif "default" in property:
  191. body[name] = property["default"]
  192. else:
  193. # omit optional parameters that weren't provided, instead of setting them to None
  194. pass
  195. break
  196. # replace path parameters
  197. for name, value in path_params.items():
  198. url = url.replace(f"{{{name}}}", f"{value}")
  199. # parse http body data if needed
  200. if "Content-Type" in headers:
  201. if headers["Content-Type"] == "application/json":
  202. body = json.dumps(body)
  203. elif headers["Content-Type"] == "application/x-www-form-urlencoded":
  204. body = urlencode(body)
  205. else:
  206. body = body
  207. # if there is a file upload, remove the Content-Type header
  208. # so that httpx can automatically generate the boundary header required for multipart/form-data.
  209. # issue: https://github.com/langgenius/dify/issues/13684
  210. # reference: https://stackoverflow.com/questions/39280438/fetch-missing-boundary-in-multipart-form-data-post
  211. if files:
  212. headers.pop("Content-Type", None)
  213. if method in {
  214. "get",
  215. "head",
  216. "post",
  217. "put",
  218. "delete",
  219. "patch",
  220. "options",
  221. "GET",
  222. "POST",
  223. "PUT",
  224. "PATCH",
  225. "DELETE",
  226. "HEAD",
  227. "OPTIONS",
  228. }:
  229. response: httpx.Response = getattr(ssrf_proxy, method.lower())(
  230. url,
  231. params=params,
  232. headers=headers,
  233. cookies=cookies,
  234. data=body,
  235. files=files,
  236. timeout=API_TOOL_DEFAULT_TIMEOUT,
  237. follow_redirects=True,
  238. )
  239. return response
  240. else:
  241. raise ValueError(f"Invalid http method {method}")
  242. def _convert_body_property_any_of(
  243. self, property: dict[str, Any], value: Any, any_of: list[dict[str, Any]], max_recursive=10
  244. ) -> Any:
  245. if max_recursive <= 0:
  246. raise Exception("Max recursion depth reached")
  247. for option in any_of or []:
  248. try:
  249. if "type" in option:
  250. # Attempt to convert the value based on the type.
  251. if option["type"] == "integer" or option["type"] == "int":
  252. return int(value)
  253. elif option["type"] == "number":
  254. if "." in str(value):
  255. return float(value)
  256. else:
  257. return int(value)
  258. elif option["type"] == "string":
  259. return str(value)
  260. elif option["type"] == "boolean":
  261. if str(value).lower() in {"true", "1"}:
  262. return True
  263. elif str(value).lower() in {"false", "0"}:
  264. return False
  265. else:
  266. continue # Not a boolean, try next option
  267. elif option["type"] == "null" and not value:
  268. return None
  269. else:
  270. continue # Unsupported type, try next option
  271. elif "anyOf" in option and isinstance(option["anyOf"], list):
  272. # Recursive call to handle nested anyOf
  273. return self._convert_body_property_any_of(property, value, option["anyOf"], max_recursive - 1)
  274. except ValueError:
  275. continue # Conversion failed, try next option
  276. # If no option succeeded, you might want to return the value as is or raise an error
  277. return value # or raise ValueError(f"Cannot convert value '{value}' to any specified type in anyOf")
  278. def _convert_body_property_type(self, property: dict[str, Any], value: Any) -> Any:
  279. try:
  280. if "type" in property:
  281. if property["type"] == "integer" or property["type"] == "int":
  282. return int(value)
  283. elif property["type"] == "number":
  284. # check if it is a float
  285. if "." in str(value):
  286. return float(value)
  287. else:
  288. return int(value)
  289. elif property["type"] == "string":
  290. return str(value)
  291. elif property["type"] == "boolean":
  292. return bool(value)
  293. elif property["type"] == "null":
  294. if value is None:
  295. return None
  296. elif property["type"] == "object" or property["type"] == "array":
  297. if isinstance(value, str):
  298. try:
  299. return json.loads(value)
  300. except ValueError:
  301. return value
  302. elif isinstance(value, dict):
  303. return value
  304. else:
  305. return value
  306. else:
  307. raise ValueError(f"Invalid type {property['type']} for property {property}")
  308. elif "anyOf" in property and isinstance(property["anyOf"], list):
  309. return self._convert_body_property_any_of(property, value, property["anyOf"])
  310. except ValueError:
  311. return value
  312. def _invoke(
  313. self,
  314. user_id: str,
  315. tool_parameters: dict[str, Any],
  316. conversation_id: Optional[str] = None,
  317. app_id: Optional[str] = None,
  318. message_id: Optional[str] = None,
  319. ) -> Generator[ToolInvokeMessage, None, None]:
  320. """
  321. invoke http request
  322. """
  323. response: httpx.Response | str = ""
  324. # assemble request
  325. headers = self.assembling_request(tool_parameters)
  326. # do http request
  327. response = self.do_http_request(self.api_bundle.server_url, self.api_bundle.method, headers, tool_parameters)
  328. # validate response
  329. response = self.validate_and_parse_response(response)
  330. # assemble invoke message
  331. yield self.create_text_message(response)