parser.py 15 KB

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