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

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