parser.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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, warning: dict = 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, warning: dict = 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, warning: dict = None) -> dict:
  166. """
  167. parse swagger to openapi
  168. :param swagger: the swagger dict
  169. :return: the openapi dict
  170. """
  171. # convert swagger to openapi
  172. info = swagger.get('info', {
  173. 'title': 'Swagger',
  174. 'description': 'Swagger',
  175. 'version': '1.0.0'
  176. })
  177. servers = swagger.get('servers', [])
  178. if len(servers) == 0:
  179. raise ToolApiSchemaError('No server found in the swagger yaml.')
  180. openapi = {
  181. 'openapi': '3.0.0',
  182. 'info': {
  183. 'title': info.get('title', 'Swagger'),
  184. 'description': info.get('description', 'Swagger'),
  185. 'version': info.get('version', '1.0.0')
  186. },
  187. 'servers': swagger['servers'],
  188. 'paths': {},
  189. 'components': {
  190. 'schemas': {}
  191. }
  192. }
  193. # check paths
  194. if 'paths' not in swagger or len(swagger['paths']) == 0:
  195. raise ToolApiSchemaError('No paths found in the swagger yaml.')
  196. # convert paths
  197. for path, path_item in swagger['paths'].items():
  198. openapi['paths'][path] = {}
  199. for method, operation in path_item.items():
  200. if 'operationId' not in operation:
  201. raise ToolApiSchemaError(f'No operationId found in operation {method} {path}.')
  202. if ('summary' not in operation or len(operation['summary']) == 0) and \
  203. ('description' not in operation or len(operation['description']) == 0):
  204. warning['missing_summary'] = f'No summary or description found in operation {method} {path}.'
  205. openapi['paths'][path][method] = {
  206. 'operationId': operation['operationId'],
  207. 'summary': operation.get('summary', ''),
  208. 'description': operation.get('description', ''),
  209. 'parameters': operation.get('parameters', []),
  210. 'responses': operation.get('responses', {}),
  211. }
  212. if 'requestBody' in operation:
  213. openapi['paths'][path][method]['requestBody'] = operation['requestBody']
  214. # convert definitions
  215. for name, definition in swagger['definitions'].items():
  216. openapi['components']['schemas'][name] = definition
  217. return openapi
  218. @staticmethod
  219. def parse_openai_plugin_json_to_tool_bundle(json: str, extra_info: dict = None, warning: dict = None) -> list[ApiToolBundle]:
  220. """
  221. parse openapi plugin yaml to tool bundle
  222. :param json: the json string
  223. :return: the tool bundle
  224. """
  225. warning = warning if warning is not None else {}
  226. extra_info = extra_info if extra_info is not None else {}
  227. try:
  228. openai_plugin = json_loads(json)
  229. api = openai_plugin['api']
  230. api_url = api['url']
  231. api_type = api['type']
  232. except:
  233. raise ToolProviderNotFoundError('Invalid openai plugin json.')
  234. if api_type != 'openapi':
  235. raise ToolNotSupportedError('Only openapi is supported now.')
  236. # get openapi yaml
  237. response = get(api_url, headers={
  238. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) '
  239. }, timeout=5)
  240. if response.status_code != 200:
  241. raise ToolProviderNotFoundError('cannot get openapi yaml from url.')
  242. return ApiBasedToolSchemaParser.parse_openapi_yaml_to_tool_bundle(response.text, extra_info=extra_info, warning=warning)
  243. @staticmethod
  244. def auto_parse_to_tool_bundle(content: str, extra_info: dict = None, warning: dict = None) -> tuple[list[ApiToolBundle], str]:
  245. """
  246. auto parse to tool bundle
  247. :param content: the content
  248. :return: tools bundle, schema_type
  249. """
  250. warning = warning if warning is not None else {}
  251. extra_info = extra_info if extra_info is not None else {}
  252. content = content.strip()
  253. loaded_content = None
  254. json_error = None
  255. yaml_error = None
  256. try:
  257. loaded_content = json_loads(content)
  258. except JSONDecodeError as e:
  259. json_error = e
  260. if loaded_content is None:
  261. try:
  262. loaded_content = safe_load(content)
  263. except YAMLError as e:
  264. yaml_error = e
  265. if loaded_content is None:
  266. raise ToolApiSchemaError(f'Invalid api schema, schema is neither json nor yaml. json error: {str(json_error)}, yaml error: {str(yaml_error)}')
  267. swagger_error = None
  268. openapi_error = None
  269. openapi_plugin_error = None
  270. schema_type = None
  271. try:
  272. openapi = ApiBasedToolSchemaParser.parse_openapi_to_tool_bundle(loaded_content, extra_info=extra_info, warning=warning)
  273. schema_type = ApiProviderSchemaType.OPENAPI.value
  274. return openapi, schema_type
  275. except ToolApiSchemaError as e:
  276. openapi_error = e
  277. # openai parse error, fallback to swagger
  278. try:
  279. converted_swagger = ApiBasedToolSchemaParser.parse_swagger_to_openapi(loaded_content, extra_info=extra_info, warning=warning)
  280. schema_type = ApiProviderSchemaType.SWAGGER.value
  281. return ApiBasedToolSchemaParser.parse_openapi_to_tool_bundle(converted_swagger, extra_info=extra_info, warning=warning), schema_type
  282. except ToolApiSchemaError as e:
  283. swagger_error = e
  284. # swagger parse error, fallback to openai plugin
  285. try:
  286. openapi_plugin = ApiBasedToolSchemaParser.parse_openai_plugin_json_to_tool_bundle(json_dumps(loaded_content), extra_info=extra_info, warning=warning)
  287. return openapi_plugin, ApiProviderSchemaType.OPENAI_PLUGIN.value
  288. except ToolNotSupportedError as e:
  289. # maybe it's not plugin at all
  290. openapi_plugin_error = e
  291. raise ToolApiSchemaError(f'Invalid api schema, openapi error: {str(openapi_error)}, swagger error: {str(swagger_error)}, openapi plugin error: {str(openapi_plugin_error)}')