""" backend/app/api/maintenance_tools.py 用途:设备维保助手 Dify Tool API,只开放只读查询工具。 依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。 逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。 """ from __future__ import annotations from flask import Blueprint, current_app, jsonify, request from sqlalchemy import or_ from app import db from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError from app.models import MaintenanceRecord from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE from app.services.maintenance_chat_service import build_device_query_result from app.services.maintenance_record_service import serialize_record from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec maintenance_tool_bp = Blueprint("maintenance_tools", __name__) def _require_tool_auth() -> None: """ 校验设备维保 Tool API 鉴权。 AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。 """ configured = str( current_app.config.get("MAINTENANCE_TOOL_API_KEY") or current_app.config.get("INTEGRATION_API_KEY") or "" ).strip() if not configured: raise ServiceUnavailableError( "MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured", code="missing_auth", ) bearer = str(request.headers.get("Authorization") or "").strip() token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else "" integration_key = str(request.headers.get("X-Integration-Key") or "").strip() if configured in {token, integration_key}: return if not token and not integration_key: raise UnauthorizedError("missing_auth") raise UnauthorizedError("invalid_auth") def _tool_error_code(exc: AppError) -> str: """把 AppError 归一成 Dify Tool 侧可读错误码。""" message = str(exc.message or "").strip() if message in {"missing_auth", "invalid_auth"}: return message if exc.code == "AUTH.UNAUTHORIZED": return "invalid_auth" if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower(): return "missing_auth" if exc.code == "VALIDATION.INVALID_PARAM": return message or "invalid_request" return exc.code @maintenance_tool_bp.errorhandler(AppError) def _handle_tool_app_error(exc: AppError): """Tool API 统一错误响应。""" return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status @maintenance_tool_bp.before_request def _verify_tool_access(): """除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。""" if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"): return None _require_tool_auth() return None def _payload() -> dict: """读取 JSON 请求体。""" return request.get_json(silent=True) or {} def _clean_text(value) -> str: return str(value or "").strip() @maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"]) def openapi_spec(): """返回 Dify 导入用的 OpenAPI JSON。""" return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE())) @maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"]) def openapi_dify_yaml(): """返回 Dify 导入用的 OpenAPI YAML。""" import yaml body = yaml.safe_dump( build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()), allow_unicode=True, sort_keys=False, ) return current_app.response_class(body, mimetype="text/yaml; charset=utf-8") @maintenance_tool_bp.route("/tools/query_device", methods=["POST"]) def query_device(): """按设备编号或名称查询设备台账,并可带出最近维修记录。""" data = _payload() keyword = _clean_text(data.get("keyword")) if not keyword: raise ValidationError("keyword is required") include_records = bool(data.get("include_records", True)) record_limit = max(0, min(20, int(data.get("record_limit") or 5))) result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit) return jsonify({"ok": True, **result}) @maintenance_tool_bp.route("/tools/query_records", methods=["POST"]) def query_records(): """按设备编号/名称和状态查询维修记录。""" data = _payload() keyword = _clean_text(data.get("keyword")) if not keyword: raise ValidationError("keyword is required") status = _clean_text(data.get("status")) limit = max(1, min(50, int(data.get("limit") or 10))) query = db.session.query(MaintenanceRecord) like = f"%{keyword}%" query = query.filter( or_( MaintenanceRecord.device_code.ilike(like), MaintenanceRecord.device_name.ilike(like), ) ) if status: query = query.filter(MaintenanceRecord.repair_status == status) rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all() return jsonify({ "ok": True, "matched": bool(rows), "keyword": keyword, "items": [serialize_record(item) for item in rows], "totalReturned": len(rows), })