您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import re
  2. import uuid
  3. from json import dumps as json_dumps
  4. from json import loads as json_loads
  5. from json.decoder import JSONDecodeError
  6. from typing import Optional
  7. from flask import request
  8. from requests import get
  9. from yaml import YAMLError, safe_load # type: ignore
  10. from core.tools.entities.common_entities import I18nObject
  11. from core.tools.entities.tool_bundle import ApiToolBundle
  12. from core.tools.entities.tool_entities import ApiProviderSchemaType, ToolParameter
  13. from core.tools.errors import ToolApiSchemaError, ToolNotSupportedError, ToolProviderNotFoundError
  14. class ApiBasedToolSchemaParser:
  15. @staticmethod
  16. def parse_openapi_to_tool_bundle(
  17. openapi: dict, extra_info: dict | None = None, warning: dict | None = None
  18. ) -> list[ApiToolBundle]:
  19. warning = warning if warning is not None else {}
  20. extra_info = extra_info if extra_info is not None else {}
  21. # set description to extra_info
  22. extra_info["description"] = openapi["info"].get("description", "")
  23. if len(openapi["servers"]) == 0:
  24. raise ToolProviderNotFoundError("No server found in the openapi yaml.")
  25. server_url = openapi["servers"][0]["url"]
  26. request_env = request.headers.get("X-Request-Env")
  27. if request_env:
  28. matched_servers = [server["url"] for server in openapi["servers"] if server["env"] == request_env]
  29. server_url = matched_servers[0] if matched_servers else server_url
  30. # list all interfaces
  31. interfaces = []
  32. for path, path_item in openapi["paths"].items():
  33. methods = ["get", "post", "put", "delete", "patch", "head", "options", "trace"]
  34. for method in methods:
  35. if method in path_item:
  36. interfaces.append(
  37. {
  38. "path": path,
  39. "method": method,
  40. "operation": path_item[method],
  41. }
  42. )
  43. # get all parameters
  44. bundles = []
  45. for interface in interfaces:
  46. # convert parameters
  47. parameters = []
  48. if "parameters" in interface["operation"]:
  49. for i, parameter in enumerate(interface["operation"]["parameters"]):
  50. if "$ref" in parameter:
  51. root = openapi
  52. reference = parameter["$ref"].split("/")[1:]
  53. for ref in reference:
  54. root = root[ref]
  55. interface["operation"]["parameters"][i] = root
  56. for parameter in interface["operation"]["parameters"]:
  57. tool_parameter = ToolParameter(
  58. name=parameter["name"],
  59. label=I18nObject(en_US=parameter["name"], zh_Hans=parameter["name"]),
  60. human_description=I18nObject(
  61. en_US=parameter.get("description", ""), zh_Hans=parameter.get("description", "")
  62. ),
  63. type=ToolParameter.ToolParameterType.STRING,
  64. required=parameter.get("required", False),
  65. form=ToolParameter.ToolParameterForm.LLM,
  66. llm_description=parameter.get("description"),
  67. default=parameter["schema"]["default"]
  68. if "schema" in parameter and "default" in parameter["schema"]
  69. else None,
  70. placeholder=I18nObject(
  71. en_US=parameter.get("description", ""), zh_Hans=parameter.get("description", "")
  72. ),
  73. )
  74. # check if there is a type
  75. typ = ApiBasedToolSchemaParser._get_tool_parameter_type(parameter)
  76. if typ:
  77. tool_parameter.type = typ
  78. parameters.append(tool_parameter)
  79. # create tool bundle
  80. # check if there is a request body
  81. if "requestBody" in interface["operation"]:
  82. request_body = interface["operation"]["requestBody"]
  83. if "content" in request_body:
  84. for content_type, content in request_body["content"].items():
  85. # if there is a reference, get the reference and overwrite the content
  86. if "schema" not in content:
  87. continue
  88. if "$ref" in content["schema"]:
  89. # get the reference
  90. root = openapi
  91. reference = content["schema"]["$ref"].split("/")[1:]
  92. for ref in reference:
  93. root = root[ref]
  94. # overwrite the content
  95. interface["operation"]["requestBody"]["content"][content_type]["schema"] = root
  96. # parse body parameters
  97. if "schema" in interface["operation"]["requestBody"]["content"][content_type]:
  98. body_schema = interface["operation"]["requestBody"]["content"][content_type]["schema"]
  99. required = body_schema.get("required", [])
  100. properties = body_schema.get("properties", {})
  101. for name, property in properties.items():
  102. tool = ToolParameter(
  103. name=name,
  104. label=I18nObject(en_US=name, zh_Hans=name),
  105. human_description=I18nObject(
  106. en_US=property.get("description", ""), zh_Hans=property.get("description", "")
  107. ),
  108. type=ToolParameter.ToolParameterType.STRING,
  109. required=name in required,
  110. form=ToolParameter.ToolParameterForm.LLM,
  111. llm_description=property.get("description", ""),
  112. default=property.get("default", None),
  113. placeholder=I18nObject(
  114. en_US=property.get("description", ""), zh_Hans=property.get("description", "")
  115. ),
  116. )
  117. # check if there is a type
  118. typ = ApiBasedToolSchemaParser._get_tool_parameter_type(property)
  119. if typ:
  120. tool.type = typ
  121. parameters.append(tool)
  122. # check if parameters is duplicated
  123. parameters_count = {}
  124. for parameter in parameters:
  125. if parameter.name not in parameters_count:
  126. parameters_count[parameter.name] = 0
  127. parameters_count[parameter.name] += 1
  128. for name, count in parameters_count.items():
  129. if count > 1:
  130. warning["duplicated_parameter"] = f"Parameter {name} is duplicated."
  131. # check if there is a operation id, use $path_$method as operation id if not
  132. if "operationId" not in interface["operation"]:
  133. # remove special characters like / to ensure the operation id is valid ^[a-zA-Z0-9_-]{1,64}$
  134. path = interface["path"]
  135. if interface["path"].startswith("/"):
  136. path = interface["path"][1:]
  137. # remove special characters like / to ensure the operation id is valid ^[a-zA-Z0-9_-]{1,64}$
  138. path = re.sub(r"[^a-zA-Z0-9_-]", "", path)
  139. if not path:
  140. path = str(uuid.uuid4())
  141. interface["operation"]["operationId"] = f"{path}_{interface['method']}"
  142. bundles.append(
  143. ApiToolBundle(
  144. server_url=server_url + interface["path"],
  145. method=interface["method"],
  146. summary=interface["operation"]["description"]
  147. if "description" in interface["operation"]
  148. else interface["operation"].get("summary", None),
  149. operation_id=interface["operation"]["operationId"],
  150. parameters=parameters,
  151. author="",
  152. icon=None,
  153. openapi=interface["operation"],
  154. )
  155. )
  156. return bundles
  157. @staticmethod
  158. def _get_tool_parameter_type(parameter: dict) -> Optional[ToolParameter.ToolParameterType]:
  159. parameter = parameter or {}
  160. typ: Optional[str] = None
  161. if parameter.get("format") == "binary":
  162. return ToolParameter.ToolParameterType.FILE
  163. if "type" in parameter:
  164. typ = parameter["type"]
  165. elif "schema" in parameter and "type" in parameter["schema"]:
  166. typ = parameter["schema"]["type"]
  167. if typ in {"integer", "number"}:
  168. return ToolParameter.ToolParameterType.NUMBER
  169. elif typ == "boolean":
  170. return ToolParameter.ToolParameterType.BOOLEAN
  171. elif typ == "string":
  172. return ToolParameter.ToolParameterType.STRING
  173. elif typ == "array":
  174. items = parameter.get("items") or parameter.get("schema", {}).get("items")
  175. return ToolParameter.ToolParameterType.FILES if items and items.get("format") == "binary" else None
  176. else:
  177. return None
  178. @staticmethod
  179. def parse_openapi_yaml_to_tool_bundle(
  180. yaml: str, extra_info: dict | None = None, warning: dict | None = None
  181. ) -> list[ApiToolBundle]:
  182. """
  183. parse openapi yaml to tool bundle
  184. :param yaml: the yaml string
  185. :param extra_info: the extra info
  186. :param warning: the warning message
  187. :return: the tool bundle
  188. """
  189. warning = warning if warning is not None else {}
  190. extra_info = extra_info if extra_info is not None else {}
  191. openapi: dict = safe_load(yaml)
  192. if openapi is None:
  193. raise ToolApiSchemaError("Invalid openapi yaml.")
  194. return ApiBasedToolSchemaParser.parse_openapi_to_tool_bundle(openapi, extra_info=extra_info, warning=warning)
  195. @staticmethod
  196. def parse_swagger_to_openapi(swagger: dict, extra_info: dict | None = None, warning: dict | None = None) -> dict:
  197. warning = warning or {}
  198. """
  199. parse swagger to openapi
  200. :param swagger: the swagger dict
  201. :return: the openapi dict
  202. """
  203. # convert swagger to openapi
  204. info = swagger.get("info", {"title": "Swagger", "description": "Swagger", "version": "1.0.0"})
  205. servers = swagger.get("servers", [])
  206. if len(servers) == 0:
  207. raise ToolApiSchemaError("No server found in the swagger yaml.")
  208. openapi = {
  209. "openapi": "3.0.0",
  210. "info": {
  211. "title": info.get("title", "Swagger"),
  212. "description": info.get("description", "Swagger"),
  213. "version": info.get("version", "1.0.0"),
  214. },
  215. "servers": swagger["servers"],
  216. "paths": {},
  217. "components": {"schemas": {}},
  218. }
  219. # check paths
  220. if "paths" not in swagger or len(swagger["paths"]) == 0:
  221. raise ToolApiSchemaError("No paths found in the swagger yaml.")
  222. # convert paths
  223. for path, path_item in swagger["paths"].items():
  224. openapi["paths"][path] = {}
  225. for method, operation in path_item.items():
  226. if "operationId" not in operation:
  227. raise ToolApiSchemaError(f"No operationId found in operation {method} {path}.")
  228. if ("summary" not in operation or len(operation["summary"]) == 0) and (
  229. "description" not in operation or len(operation["description"]) == 0
  230. ):
  231. if warning is not None:
  232. warning["missing_summary"] = f"No summary or description found in operation {method} {path}."
  233. openapi["paths"][path][method] = {
  234. "operationId": operation["operationId"],
  235. "summary": operation.get("summary", ""),
  236. "description": operation.get("description", ""),
  237. "parameters": operation.get("parameters", []),
  238. "responses": operation.get("responses", {}),
  239. }
  240. if "requestBody" in operation:
  241. openapi["paths"][path][method]["requestBody"] = operation["requestBody"]
  242. # convert definitions
  243. for name, definition in swagger["definitions"].items():
  244. openapi["components"]["schemas"][name] = definition
  245. return openapi
  246. @staticmethod
  247. def parse_openai_plugin_json_to_tool_bundle(
  248. json: str, extra_info: dict | None = None, warning: dict | None = None
  249. ) -> list[ApiToolBundle]:
  250. """
  251. parse openapi plugin yaml to tool bundle
  252. :param json: the json string
  253. :param extra_info: the extra info
  254. :param warning: the warning message
  255. :return: the tool bundle
  256. """
  257. warning = warning if warning is not None else {}
  258. extra_info = extra_info if extra_info is not None else {}
  259. try:
  260. openai_plugin = json_loads(json)
  261. api = openai_plugin["api"]
  262. api_url = api["url"]
  263. api_type = api["type"]
  264. except JSONDecodeError:
  265. raise ToolProviderNotFoundError("Invalid openai plugin json.")
  266. if api_type != "openapi":
  267. raise ToolNotSupportedError("Only openapi is supported now.")
  268. # get openapi yaml
  269. response = get(api_url, headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "}, timeout=5)
  270. if response.status_code != 200:
  271. raise ToolProviderNotFoundError("cannot get openapi yaml from url.")
  272. return ApiBasedToolSchemaParser.parse_openapi_yaml_to_tool_bundle(
  273. response.text, extra_info=extra_info, warning=warning
  274. )
  275. @staticmethod
  276. def auto_parse_to_tool_bundle(
  277. content: str, extra_info: dict | None = None, warning: dict | None = None
  278. ) -> tuple[list[ApiToolBundle], str]:
  279. """
  280. auto parse to tool bundle
  281. :param content: the content
  282. :param extra_info: the extra info
  283. :param warning: the warning message
  284. :return: tools bundle, schema_type
  285. """
  286. warning = warning if warning is not None else {}
  287. extra_info = extra_info if extra_info is not None else {}
  288. content = content.strip()
  289. loaded_content = None
  290. json_error = None
  291. yaml_error = None
  292. try:
  293. loaded_content = json_loads(content)
  294. except JSONDecodeError as e:
  295. json_error = e
  296. if loaded_content is None:
  297. try:
  298. loaded_content = safe_load(content)
  299. except YAMLError as e:
  300. yaml_error = e
  301. if loaded_content is None:
  302. raise ToolApiSchemaError(
  303. f"Invalid api schema, schema is neither json nor yaml. json error: {str(json_error)},"
  304. f" yaml error: {str(yaml_error)}"
  305. )
  306. swagger_error = None
  307. openapi_error = None
  308. openapi_plugin_error = None
  309. schema_type = None
  310. try:
  311. openapi = ApiBasedToolSchemaParser.parse_openapi_to_tool_bundle(
  312. loaded_content, extra_info=extra_info, warning=warning
  313. )
  314. schema_type = ApiProviderSchemaType.OPENAPI.value
  315. return openapi, schema_type
  316. except ToolApiSchemaError as e:
  317. openapi_error = e
  318. # openai parse error, fallback to swagger
  319. try:
  320. converted_swagger = ApiBasedToolSchemaParser.parse_swagger_to_openapi(
  321. loaded_content, extra_info=extra_info, warning=warning
  322. )
  323. schema_type = ApiProviderSchemaType.SWAGGER.value
  324. return ApiBasedToolSchemaParser.parse_openapi_to_tool_bundle(
  325. converted_swagger, extra_info=extra_info, warning=warning
  326. ), schema_type
  327. except ToolApiSchemaError as e:
  328. swagger_error = e
  329. # swagger parse error, fallback to openai plugin
  330. try:
  331. openapi_plugin = ApiBasedToolSchemaParser.parse_openai_plugin_json_to_tool_bundle(
  332. json_dumps(loaded_content), extra_info=extra_info, warning=warning
  333. )
  334. return openapi_plugin, ApiProviderSchemaType.OPENAI_PLUGIN.value
  335. except ToolNotSupportedError as e:
  336. # maybe it's not plugin at all
  337. openapi_plugin_error = e
  338. raise ToolApiSchemaError(
  339. f"Invalid api schema, openapi error: {str(openapi_error)}, swagger error: {str(swagger_error)},"
  340. f" openapi plugin error: {str(openapi_plugin_error)}"
  341. )