parser.py 15 KB

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