parser.py 15 KB

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