#!/usr/bin/env python3 """从 OpenAPI 文档生成供 AI Agent 使用的接口索引。 默认优先读取 JSON(标准库即可解析);读取 YAML 时需要安装 PyYAML。 导出脚本会优先传入 /v3/api-docs 的 JSON,避免额外依赖。 """ from __future__ import annotations import argparse import json import re import sys from pathlib import Path from typing import Any HTTP_METHODS = ("get", "head", "post", "put", "patch", "delete", "options", "trace") REQUEST_MEDIA = ("application/json", "multipart/form-data", "application/x-www-form-urlencoded", "*/*") RESPONSE_MEDIA = ("application/json", "*/*", "text/event-stream", "application/octet-stream") def load_spec(path: Path) -> dict[str, Any]: text = path.read_text(encoding="utf-8") try: data = json.loads(text) except json.JSONDecodeError: try: import yaml except ImportError as exc: raise SystemExit( "无法解析 YAML:请安装 PyYAML(pip install pyyaml)," "或改用 /v3/api-docs 的 JSON 输出。" ) from exc data = yaml.safe_load(text) if not isinstance(data, dict): raise SystemExit("OpenAPI 文档格式不正确:根节点必须是对象") return data def resolve(spec: dict[str, Any], value: Any) -> Any: """解析本地 $ref,最多跟随 32 层,避免循环引用。""" for _ in range(32): if not isinstance(value, dict) or "$ref" not in value: return value ref = value["$ref"] if not isinstance(ref, str) or not ref.startswith("#/"): return value current: Any = spec for part in ref[2:].split("/"): part = part.replace("~1", "/").replace("~0", "~") if not isinstance(current, dict) or part not in current: return value current = current[part] value = current return value def ref_name(ref: str) -> str: return ref.rsplit("/", 1)[-1].replace("~1", "/").replace("~0", "~") def schema_label(spec: dict[str, Any], schema: Any, depth: int = 0) -> str: if not isinstance(schema, dict) or depth > 4: return "-" if "$ref" in schema: return ref_name(str(schema["$ref"])) schema_type = schema.get("type") if isinstance(schema_type, list): schema_type = "/".join(str(item) for item in schema_type) if schema_type == "array": return f"Array<{schema_label(spec, schema.get('items'), depth + 1)}>" if schema_type == "object" or "properties" in schema: additional = schema.get("additionalProperties") if isinstance(additional, dict): return f"Map" if additional is True: return "Map" properties = schema.get("properties") if isinstance(properties, dict) and properties: names = list(properties) if len(names) > 8: names = names[:8] + ["..."] return "object{" + ", ".join(names) + "}" return "object" for keyword in ("oneOf", "anyOf", "allOf"): items = schema.get(keyword) if isinstance(items, list) and items: joiner = " | " if keyword == "oneOf" else " & " return "(" + joiner.join(schema_label(spec, item, depth + 1) for item in items) + ")" if schema_type == "string" and schema.get("format") in ("binary", "byte"): return "binary" if schema_type: return str(schema_type) return "-" def pick_media(content: Any, preferred: tuple[str, ...]) -> tuple[str | None, Any]: if not isinstance(content, dict) or not content: return None, None for media in preferred: if media in content: return media, content[media] media = next(iter(content)) return media, content[media] def request_label(spec: dict[str, Any], operation: dict[str, Any]) -> str: body = resolve(spec, operation.get("requestBody")) if not isinstance(body, dict): return "-" media, entry = pick_media(body.get("content"), REQUEST_MEDIA) if media is None: return "-" schema = entry.get("schema") if isinstance(entry, dict) else None label = schema_label(spec, schema) if label == "-": return media if media in ("application/json", "*/*"): return label return f"{label} ({media})" def response_label(spec: dict[str, Any], operation: dict[str, Any]) -> str: responses = operation.get("responses") if not isinstance(responses, dict) or not responses: return "-" response = None for code in ("200", "201", "202", "204"): if code in responses: response = responses[code] break if response is None: for code, candidate in responses.items(): if str(code).startswith("2"): response = candidate break if response is None and "default" in responses: response = responses["default"] response = resolve(spec, response) if not isinstance(response, dict): return "-" media, entry = pick_media(response.get("content"), RESPONSE_MEDIA) if media is None: return "-" if media == "text/event-stream": return "SSE" schema = entry.get("schema") if isinstance(entry, dict) else None label = schema_label(spec, schema) if label == "-": return media if media in ("application/json", "*/*"): return label return f"{label} ({media})" def parameter_label(spec: dict[str, Any], path_item: dict[str, Any], operation: dict[str, Any]) -> str: merged: dict[tuple[str, str], dict[str, Any]] = {} for source in (path_item.get("parameters"), operation.get("parameters")): if not isinstance(source, list): continue for raw in source: parameter = resolve(spec, raw) if not isinstance(parameter, dict): continue name = parameter.get("name") location = parameter.get("in") if name and location: merged[(str(name), str(location))] = parameter if not merged: return "-" parts = [] for (name, location), parameter in merged.items(): prefix = "" if location in ("header", "cookie"): prefix = f"{location}:" suffix = "*" if parameter.get("required") else "" parts.append(f"{prefix}{name}{suffix}") return ", ".join(parts) def cell(value: Any) -> str: text = "" if value is None else str(value) text = re.sub(r"\s+", " ", text).strip() text = text.replace("|", "\\|") return text or "-" def module_key(path: str) -> str: segments = [segment for segment in path.split("/") if segment] if not segments: return "root" if segments[0] == "gao" and len(segments) > 1: return f"gao-{segments[1]}" return segments[0] def module_prefix(key: str) -> str: if key == "root": return "/" if key.startswith("gao-"): return f"/gao/{key[4:]}/" return f"/{key}/" def module_sort(key: str) -> tuple[int, str]: if key.startswith("gao-"): return 0, key order = {"system": 1, "user": 2, "app": 3} return order.get(key, 4), key def collect_operations(spec: dict[str, Any]) -> list[dict[str, Any]]: paths = spec.get("paths") if not isinstance(paths, dict): return [] operations = [] for path, path_item in paths.items(): if not isinstance(path_item, dict): continue path_item = resolve(spec, path_item) if not isinstance(path_item, dict): continue for method in HTTP_METHODS: operation = path_item.get(method) if not isinstance(operation, dict): continue operation = resolve(spec, operation) if not isinstance(operation, dict): continue summary = operation.get("summary") or operation.get("operationId") or "" if operation.get("summary") is None and isinstance(summary, str): summary = re.sub(r"_\d+$", "", summary) if operation.get("deprecated"): summary = f"[已废弃] {summary}" public = operation["security"] == [] if "security" in operation else not spec.get("security") if public: summary = f"[公开] {summary}" operations.append({ "methods": [method.upper()], "path": path, "summary": summary, "parameters": parameter_label(spec, path_item, operation), "request": request_label(spec, operation), "response": response_label(spec, operation), "tag": ", ".join(operation.get("tags") or []), "module": module_key(path), "order": (path, HTTP_METHODS.index(method)), }) # 同一个处理器的多个 HTTP 方法(如 @RequestMapping 未限定 method)合并为一行。 merged: dict[tuple[Any, ...], dict[str, Any]] = {} for operation in operations: key = ( operation["path"], operation["summary"], operation["parameters"], operation["request"], operation["response"], operation["tag"], operation["module"], ) if key in merged: merged[key]["methods"].append(operation["methods"][0]) else: merged[key] = operation return list(merged.values()) def render(spec: dict[str, Any], source: str) -> str: info = spec.get("info") if isinstance(spec.get("info"), dict) else {} title = info.get("title") or "OpenAPI" version = info.get("version") or "-" openapi_version = spec.get("openapi") or "-" paths = spec.get("paths") if isinstance(spec.get("paths"), dict) else {} operations = collect_operations(spec) groups: dict[str, list[dict[str, Any]]] = {} for operation in operations: groups.setdefault(operation["module"], []).append(operation) for items in groups.values(): items.sort(key=lambda item: item["order"]) lines = [ f"# {title} 接口索引", "", "> 本文件由 `scripts/openapi-index.py` 从 OpenAPI 快照生成,请勿手工编辑。", f"> 数据来源:`{source}`。完整字段定义以 OpenAPI 原文为准。", "", f"- 服务版本:`{version}`", f"- OpenAPI 版本:`{openapi_version}`", f"- 路径数:{len(paths)}", f"- 接口数:{len(operations)}(同一路径的同一处理器会合并多个 HTTP 方法)", f"- 模块数:{len(groups)}", "", "## 使用说明", "", "- 先按模块定位接口,再读取 `docs/openapi.local.yaml` 中对应的 `path` 或 `components/schemas`,不要整文件加载。", "- 参数列中 `*` 表示必填;`header:`、`cookie:` 为参数位置前缀,其余为 path/query 参数。", "- 摘要前的 `[公开]` 表示 OpenAPI 中显式标记为无需登录;未标记的接口默认使用 `Token` 鉴权。", "- 方法列出现多个 HTTP 方法,表示 Controller 使用了未限定 method 的 `@RequestMapping`。", "- 请求体和响应列展示顶层 schema 名称;`binary` 表示二进制响应,`SSE` 表示 `text/event-stream`。", "- 普通 JSON 接口的响应仍由 `TimiResponse` 包装,鉴权、错误码、分页等约定见 `docs/api-integration.md`。", "", "## 模块导航", "", "| 模块 | 接口数 | 路径前缀 |", "| --- | ---: | --- |", ] for key in sorted(groups, key=module_sort): lines.append(f"| [`{cell(key)}`](#module-{key}) | {len(groups[key])} | `{module_prefix(key)}` |") for key in sorted(groups, key=module_sort): lines.extend([ "", f'', f"## {key}", "", f"共 {len(groups[key])} 个接口,路径前缀 `{module_prefix(key)}`。", "", "| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |", "| --- | --- | --- | --- | --- | --- | --- |", ]) for operation in groups[key]: lines.append( "| {method} | `{path}` | {summary} | {parameters} | {request} | {response} | {tag} |".format( method="/".join(operation["methods"]), path=cell(operation["path"]), summary=cell(operation["summary"]), parameters=cell(operation["parameters"]), request=cell(operation["request"]), response=cell(operation["response"]), tag=cell(operation["tag"]), ) ) lines.append("") return "\n".join(lines) def main() -> int: parser = argparse.ArgumentParser(description="从 OpenAPI 文档生成 AI Agent 接口索引") parser.add_argument("input", type=Path, help="OpenAPI JSON/YAML 文件") parser.add_argument("output", type=Path, help="输出的 Markdown 文件") parser.add_argument( "--source-label", default="docs/openapi.local.yaml", help="索引中显示的数据来源(默认 docs/openapi.local.yaml)", ) args = parser.parse_args() spec = load_spec(args.input) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(render(spec, args.source_label), encoding="utf-8", newline="\n") print(f"OpenAPI index written to {args.output}") return 0 if __name__ == "__main__": sys.exit(main())