tool.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. """
  21. Api tool
  22. """
  23. def __init__(self, entity: ToolEntity, api_bundle: ApiToolBundle, runtime: ToolRuntime):
  24. super().__init__(entity, runtime)
  25. self.api_bundle = api_bundle
  26. def fork_tool_runtime(self, runtime: ToolRuntime):
  27. """
  28. fork a new tool with meta data
  29. :param meta: the meta data of a tool call processing, tenant_id is required
  30. :return: the new tool
  31. """
  32. return self.__class__(
  33. entity=self.entity,
  34. api_bundle=self.api_bundle.model_copy(),
  35. runtime=runtime,
  36. )
  37. def validate_credentials(
  38. self, credentials: dict[str, Any], parameters: dict[str, Any], format_only: bool = False
  39. ) -> str:
  40. """
  41. validate the credentials for Api tool
  42. """
  43. # assemble validate request and request parameters
  44. headers = self.assembling_request(parameters)
  45. if format_only:
  46. return ""
  47. response = self.do_http_request(self.api_bundle.server_url, self.api_bundle.method, headers, parameters)
  48. # validate response
  49. return self.validate_and_parse_response(response)
  50. def tool_provider_type(self) -> ToolProviderType:
  51. return ToolProviderType.API
  52. def assembling_request(self, parameters: dict[str, Any]) -> dict[str, Any]:
  53. if self.runtime == None:
  54. raise ToolProviderCredentialValidationError("runtime not initialized")
  55. headers = {}
  56. credentials = self.runtime.credentials or {}
  57. if "auth_type" not in credentials:
  58. raise ToolProviderCredentialValidationError("Missing auth_type")
  59. if credentials["auth_type"] == "api_key":
  60. api_key_header = "api_key"
  61. if "api_key_header" in credentials:
  62. api_key_header = credentials["api_key_header"]
  63. if "api_key_value" not in credentials:
  64. raise ToolProviderCredentialValidationError("Missing api_key_value")
  65. elif not isinstance(credentials["api_key_value"], str):
  66. raise ToolProviderCredentialValidationError("api_key_value must be a string")
  67. if "api_key_header_prefix" in credentials:
  68. api_key_header_prefix = credentials["api_key_header_prefix"]
  69. if api_key_header_prefix == "basic" and credentials["api_key_value"]:
  70. credentials["api_key_value"] = f'Basic {credentials["api_key_value"]}'
  71. elif api_key_header_prefix == "bearer" and credentials["api_key_value"]:
  72. credentials["api_key_value"] = f'Bearer {credentials["api_key_value"]}'
  73. elif api_key_header_prefix == "custom":
  74. pass
  75. headers[api_key_header] = credentials["api_key_value"]
  76. needed_parameters = [parameter for parameter in (self.api_bundle.parameters or []) if parameter.required]
  77. for parameter in needed_parameters:
  78. if parameter.required and parameter.name not in parameters:
  79. raise ToolParameterValidationError(f"Missing required parameter {parameter.name}")
  80. if parameter.default is not None and parameter.name not in parameters:
  81. parameters[parameter.name] = parameter.default
  82. return headers
  83. def validate_and_parse_response(self, response: httpx.Response) -> str:
  84. """
  85. validate the response
  86. """
  87. if isinstance(response, httpx.Response):
  88. if response.status_code >= 400:
  89. raise ToolInvokeError(f"Request failed with status code {response.status_code} and {response.text}")
  90. if not response.content:
  91. return "Empty response from the tool, please check your parameters and try again."
  92. try:
  93. response = response.json()
  94. try:
  95. return json.dumps(response, ensure_ascii=False)
  96. except Exception as e:
  97. return json.dumps(response)
  98. except Exception as e:
  99. return response.text
  100. else:
  101. raise ValueError(f"Invalid response type {type(response)}")
  102. @staticmethod
  103. def get_parameter_value(parameter, parameters):
  104. if parameter["name"] in parameters:
  105. return parameters[parameter["name"]]
  106. elif parameter.get("required", False):
  107. raise ToolParameterValidationError(f"Missing required parameter {parameter['name']}")
  108. else:
  109. return (parameter.get("schema", {}) or {}).get("default", "")
  110. def do_http_request(
  111. self, url: str, method: str, headers: dict[str, Any], parameters: dict[str, Any]
  112. ) -> httpx.Response:
  113. """
  114. do http request depending on api bundle
  115. """
  116. method = method.lower()
  117. params = {}
  118. path_params = {}
  119. body = {}
  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 {"get", "head", "post", "put", "delete", "patch"}:
  172. response = getattr(ssrf_proxy, method)(
  173. url,
  174. params=params,
  175. headers=headers,
  176. cookies=cookies,
  177. data=body,
  178. files=files,
  179. timeout=API_TOOL_DEFAULT_TIMEOUT,
  180. follow_redirects=True,
  181. )
  182. return response
  183. else:
  184. raise ValueError(f"Invalid http method {method}")
  185. def _convert_body_property_any_of(
  186. self, property: dict[str, Any], value: Any, any_of: list[dict[str, Any]], max_recursive=10
  187. ) -> Any:
  188. if max_recursive <= 0:
  189. raise Exception("Max recursion depth reached")
  190. for option in any_of or []:
  191. try:
  192. if "type" in option:
  193. # Attempt to convert the value based on the type.
  194. if option["type"] == "integer" or option["type"] == "int":
  195. return int(value)
  196. elif option["type"] == "number":
  197. if "." in str(value):
  198. return float(value)
  199. else:
  200. return int(value)
  201. elif option["type"] == "string":
  202. return str(value)
  203. elif option["type"] == "boolean":
  204. if str(value).lower() in {"true", "1"}:
  205. return True
  206. elif str(value).lower() in {"false", "0"}:
  207. return False
  208. else:
  209. continue # Not a boolean, try next option
  210. elif option["type"] == "null" and not value:
  211. return None
  212. else:
  213. continue # Unsupported type, try next option
  214. elif "anyOf" in option and isinstance(option["anyOf"], list):
  215. # Recursive call to handle nested anyOf
  216. return self._convert_body_property_any_of(property, value, option["anyOf"], max_recursive - 1)
  217. except ValueError:
  218. continue # Conversion failed, try next option
  219. # If no option succeeded, you might want to return the value as is or raise an error
  220. return value # or raise ValueError(f"Cannot convert value '{value}' to any specified type in anyOf")
  221. def _convert_body_property_type(self, property: dict[str, Any], value: Any) -> Any:
  222. try:
  223. if "type" in property:
  224. if property["type"] == "integer" or property["type"] == "int":
  225. return int(value)
  226. elif property["type"] == "number":
  227. # check if it is a float
  228. if "." in str(value):
  229. return float(value)
  230. else:
  231. return int(value)
  232. elif property["type"] == "string":
  233. return str(value)
  234. elif property["type"] == "boolean":
  235. return bool(value)
  236. elif property["type"] == "null":
  237. if value is None:
  238. return None
  239. elif property["type"] == "object" or property["type"] == "array":
  240. if isinstance(value, str):
  241. try:
  242. # an array str like '[1,2]' also can convert to list [1,2] through json.loads
  243. # json not support single quote, but we can support it
  244. value = value.replace("'", '"')
  245. return json.loads(value)
  246. except ValueError:
  247. return value
  248. elif isinstance(value, dict):
  249. return value
  250. else:
  251. return value
  252. else:
  253. raise ValueError(f"Invalid type {property['type']} for property {property}")
  254. elif "anyOf" in property and isinstance(property["anyOf"], list):
  255. return self._convert_body_property_any_of(property, value, property["anyOf"])
  256. except ValueError as e:
  257. return value
  258. def _invoke(
  259. self,
  260. user_id: str,
  261. tool_parameters: dict[str, Any],
  262. conversation_id: Optional[str] = None,
  263. app_id: Optional[str] = None,
  264. message_id: Optional[str] = None,
  265. ) -> Generator[ToolInvokeMessage, None, None]:
  266. """
  267. invoke http request
  268. """
  269. # assemble request
  270. headers = self.assembling_request(tool_parameters)
  271. # do http request
  272. response = self.do_http_request(self.api_bundle.server_url, self.api_bundle.method, headers, tool_parameters)
  273. # validate response
  274. response = self.validate_and_parse_response(response)
  275. # assemble invoke message
  276. yield self.create_text_message(response)