tool.py 14 KB

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