From 24310b63b3a2425b8a15ab9ae5acae92265df817 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 16 Jun 2026 09:28:37 +0800 Subject: [PATCH] =?UTF-8?q?feat(file-check):=20=E6=96=B0=E5=A2=9E=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=A3=80=E6=A0=B8=E7=9B=B8=E5=85=B3=20API=20=E5=92=8C?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=EF=BC=8C=E6=9B=BF=E6=8D=A2=20RoHS=20?= =?UTF-8?q?=E6=A3=80=E6=A0=B8=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/__init__.py | 8 +- backend/app/api/chat.py | 39 +- ...ohs_check_tools.py => file_check_tools.py} | 177 +-- backend/app/api/user.py | 6 +- ..._rohs_check.py => workspace_file_check.py} | 72 +- backend/app/config.py | 6 +- backend/app/services/dify.py | 16 +- .../services/{rohs_check.py => file_check.py} | 32 +- .../app/services/file_check_tools/__init__.py | 1 + .../file_check_tools/agent_resolver.py | 60 + .../chat_log_run_binding.py | 48 +- .../chat_log_run_resolver.py | 16 +- .../chat_turn_registry.py | 28 +- .../services/file_check_tools/dify_inputs.py | 93 ++ .../openapi_base.json | 88 +- .../openapi_spec.py | 11 +- .../file_check_tools/progress_paths.py | 39 + .../file_check_tools/task_resolver.py | 117 ++ .../app/services/rohs_check_tools/__init__.py | 0 .../rohs_check_tools/agent_resolver.py | 21 - .../services/rohs_check_tools/dify_inputs.py | 59 - .../rohs_check_tools/task_resolver.py | 114 -- backend/app/services/schedule/srm_service.py | 6 +- ...penapi.py => export_file_check_openapi.py} | 10 +- ...heck_tools.py => test_file_check_tools.py} | 408 +++-- docs/convention/COMMIT_CONVENTION.md | 3 +- docs/demand.md | 13 +- docs/file_check_chatflow_guide.md | 1401 +++++++++++++++++ docs/funclist.md | 15 +- docs/openapi/file_check_tools_openapi.json | 724 +++++++++ docs/tec.md | 12 +- .../chat/composables/useToolRunProgress.ts | 11 +- .../features/chat/page/useChatPageToolRun.ts | 34 +- .../src/features/chat/types/chat.types.ts | 2 +- .../chat/utils/toolRunProgressConfig.ts | 35 +- 35 files changed, 3066 insertions(+), 659 deletions(-) rename backend/app/api/{rohs_check_tools.py => file_check_tools.py} (70%) rename backend/app/api/{workspace_rohs_check.py => workspace_file_check.py} (74%) rename backend/app/services/{rohs_check.py => file_check.py} (72%) create mode 100644 backend/app/services/file_check_tools/__init__.py create mode 100644 backend/app/services/file_check_tools/agent_resolver.py rename backend/app/services/{rohs_check_tools => file_check_tools}/chat_log_run_binding.py (81%) rename backend/app/services/{rohs_check_tools => file_check_tools}/chat_log_run_resolver.py (62%) rename backend/app/services/{rohs_check_tools => file_check_tools}/chat_turn_registry.py (90%) create mode 100644 backend/app/services/file_check_tools/dify_inputs.py rename backend/app/services/{rohs_check_tools => file_check_tools}/openapi_base.json (87%) rename backend/app/services/{rohs_check_tools => file_check_tools}/openapi_spec.py (61%) create mode 100644 backend/app/services/file_check_tools/progress_paths.py create mode 100644 backend/app/services/file_check_tools/task_resolver.py delete mode 100644 backend/app/services/rohs_check_tools/__init__.py delete mode 100644 backend/app/services/rohs_check_tools/agent_resolver.py delete mode 100644 backend/app/services/rohs_check_tools/dify_inputs.py delete mode 100644 backend/app/services/rohs_check_tools/task_resolver.py rename backend/scripts/{export_rohs_check_openapi.py => export_file_check_openapi.py} (65%) rename backend/tests/{test_rohs_check_tools.py => test_file_check_tools.py} (74%) create mode 100644 docs/file_check_chatflow_guide.md create mode 100644 docs/openapi/file_check_tools_openapi.json diff --git a/backend/app/__init__.py b/backend/app/__init__.py index b76b5828..fc8a7ba0 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -56,10 +56,10 @@ def create_app(config_name='default'): from app.api.schedule_admin import schedule_admin_bp from app.api.workspace_schedule import workspace_schedule_bp from app.api.workspace_shipping_notice import workspace_shipping_notice_bp - from app.api.workspace_rohs_check import workspace_rohs_check_bp + from app.api.workspace_file_check import workspace_file_check_bp from app.api.internal_jobs import internal_jobs_bp from app.api.shipping_notice_tools import shipping_notice_bp - from app.api.rohs_check_tools import rohs_check_bp + from app.api.file_check_tools import file_check_bp from app.api.speech import speech_bp # 聊天相关接口 @@ -77,10 +77,10 @@ def create_app(config_name='default'): app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace') - app.register_blueprint(workspace_rohs_check_bp, url_prefix='/api/workspace') + app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') - app.register_blueprint(rohs_check_bp, url_prefix='/api/rohs-check') + app.register_blueprint(file_check_bp, url_prefix='/api/file-check') app.register_blueprint(speech_bp, url_prefix='/api/speech') # Eagerly load persisted runtime settings so the very first request after diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 38c35c47..4b71f52c 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -1084,6 +1084,7 @@ def chat_completions(): name=getattr(agent, 'name', None), dify_api_key=getattr(agent, 'dify_api_key', None), api_base_url=getattr(agent, 'api_base_url', None), + extra_config=getattr(agent, 'extra_config', None) or {}, ) user_proxy = SimpleNamespace( id=user_id, @@ -1174,31 +1175,33 @@ def chat_completions(): else: dify_inputs: dict[str, str] | None = None hxops_turn_id: str | None = None - from app.services.rohs_check_tools.dify_inputs import ( - build_dify_chat_inputs as build_rohs_dify_chat_inputs, - is_rohs_check_chat_agent, + from app.services.file_check_tools.agent_resolver import ( + agent_declares_file_check_progress, + is_file_check_chat_agent, ) + from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs from app.services.shipping_notice.dify_inputs import ( build_dify_chat_inputs as build_shipping_dify_chat_inputs, is_shipping_notice_chat_agent, ) + declares_file_check = agent_declares_file_check_progress(agent_proxy) + is_file_check_agent = is_file_check_chat_agent(agent_proxy) if is_shipping_notice_chat_agent(agent_proxy): dify_inputs = build_shipping_dify_chat_inputs() - elif is_rohs_check_chat_agent(agent_proxy): - hxops_turn_id = uuid.uuid4().hex - from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn + elif declares_file_check or is_file_check_agent: + # [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死 + dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True) + if is_file_check_agent: + hxops_turn_id = uuid.uuid4().hex + from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn - register_rohs_chat_turn( - turn_id=hxops_turn_id, - session_id=session.session_id, - user_id=user_proxy.id, - agent_id=agent_proxy.id, - query=query, - ) - dify_inputs = build_rohs_dify_chat_inputs( - hxops_session_id=session.session_id, - hxops_turn_id=hxops_turn_id, - ) + register_file_check_chat_turn( + turn_id=hxops_turn_id, + session_id=session.session_id, + user_id=user_proxy.id, + agent_id=agent_proxy.id, + query=query, + ) generator = DifyService.stream_chat( query, user_proxy.id, @@ -1206,7 +1209,7 @@ def chat_completions(): external_conversation_id, request_id=request_id, session_id=session.session_id, - hxops_turn_id=hxops_turn_id if is_rohs_check_chat_agent(agent_proxy) else None, + hxops_turn_id=hxops_turn_id if is_file_check_agent else None, files=normalized_files, inputs=dify_inputs, ) diff --git a/backend/app/api/rohs_check_tools.py b/backend/app/api/file_check_tools.py similarity index 70% rename from backend/app/api/rohs_check_tools.py rename to backend/app/api/file_check_tools.py index 151ce4c2..9f09d080 100644 --- a/backend/app/api/rohs_check_tools.py +++ b/backend/app/api/file_check_tools.py @@ -1,6 +1,9 @@ """ -backend/app/api/rohs_check_tools.py -文件用途:RoHS Chatflow 显式 HTTP Tool API。 +backend/app/api/file_check_tools.py + +用途:文件检核 Chatflow 显式 HTTP Tool API。 +依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。 +逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。 """ from __future__ import annotations @@ -13,25 +16,24 @@ from flask import Blueprint, current_app, jsonify, request, send_file from sqlalchemy import text from app import db -from app.api.workspace_rohs_check import serialize_rohs_judgement +from app.api.workspace_file_check import serialize_file_judgement from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError from app.models import ScheduleRun, ScheduleTask +from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE -from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec from app.services.schedule.query_service import get_run, serialize_run from app.services.schedule.scheduler_service import _generate_run_no, run_task_now -rohs_check_bp = Blueprint("rohs_check_tools", __name__) +file_check_bp = Blueprint("file_check_tools", __name__) -_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"} +_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"} _RUN_START_LOCK = threading.Lock() -_ROHS_GLOBAL_LOCK_KEY = 8700000000 -_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核") +_TASK_LOCK_KEY_BASE = 8700000000 def _tool_token_secret() -> str: return str( - current_app.config.get("ROHS_TOOLS_API_KEY") + current_app.config.get("FILE_CHECK_TOOLS_API_KEY") or current_app.config.get("INTEGRATION_API_KEY") or current_app.config.get("SECRET_KEY") or "default-secret" @@ -48,19 +50,19 @@ def _decode_download_token(token: str | None) -> dict | None: payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"]) return payload if isinstance(payload, dict) else None except Exception as exc: - current_app.logger.warning("[rohs-tool] download token validation failed: %s", exc) + current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc) return None def _require_tool_auth() -> None: configured = str( - current_app.config.get("ROHS_TOOLS_API_KEY") + current_app.config.get("FILE_CHECK_TOOLS_API_KEY") or current_app.config.get("INTEGRATION_API_KEY") or "" ).strip() if not configured: raise ServiceUnavailableError( - "ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured", + "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured", code="missing_auth", ) @@ -100,7 +102,7 @@ def _tool_error_code(exc: AppError) -> str: return exc.code -@rohs_check_bp.errorhandler(AppError) +@file_check_bp.errorhandler(AppError) def _handle_tool_app_error(exc: AppError): status = exc.http_status return jsonify({ @@ -114,39 +116,28 @@ def _public_base_url() -> str: return resolve_HXOPS_TOOLS_API_BASE() -def _is_rohs_check_task(task: ScheduleTask | None) -> bool: - if not task: - return False - values = ( - getattr(task, "schedule_no", None), - getattr(task, "name", None), - getattr(task, "platform_api_path", None), - ) - haystack = " ".join(str(item or "").lower() for item in values) - return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS) - - -def _acquire_rohs_start_lock() -> None: - """Serialize RoHS start checks across processes when PostgreSQL is used.""" +def _acquire_task_start_lock(task_id: int) -> None: + """按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。""" bind = db.session.get_bind() if bind.dialect.name != "postgresql": return - db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY}) + lock_key = _TASK_LOCK_KEY_BASE + int(task_id) + db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key}) def _build_excel_download_url(run: ScheduleRun) -> str: import jwt payload = { - "scope": "rohs_check_excel", + "scope": "file_check_excel", "run_id": run.id, "exp": int(time.time()) + 600, } token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256") - return f"{_public_base_url()}/api/rohs-check/tools/runs/{run.id}/excel?token={token}" + return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}" -@rohs_check_bp.before_request +@file_check_bp.before_request def _verify_tool_access(): if request.path.endswith("/openapi.json"): return None @@ -166,7 +157,7 @@ def _serialize_tool_run(run: ScheduleRun) -> dict: "success_count": payload["success_count"], "failed_count": payload["failed_count"], "skipped_count": payload["skipped_count"], - "judgement": serialize_rohs_judgement(payload), + "judgement": serialize_file_judgement(payload), "started_at": payload.get("started_at"), "finished_at": payload.get("finished_at"), "duration_ms": payload.get("duration_ms"), @@ -204,41 +195,37 @@ def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) task = ScheduleTask.query.filter_by(schedule_no=task_no).first() if not task: raise NotFoundError("task_not_found") - if not _is_rohs_check_task(task): - raise NotFoundError("task_not_found") return task -@rohs_check_bp.route("/tools/tasks", methods=["GET"]) -def list_rohs_tasks(): - rows = ScheduleTask.query.order_by(ScheduleTask.created_at.desc()).all() - tasks = [] - for task in rows: - if not _is_rohs_check_task(task): - continue - latest = ( - ScheduleRun.query.filter_by(schedule_task_id=task.id) - .order_by(ScheduleRun.id.desc()) - .first() - ) - tasks.append({ - "task_id": task.id, - "task_no": task.schedule_no, - "name": task.name, - "enabled": bool(task.enabled), - "last_status": latest.status if latest else None, - "last_run_at": task.last_run_at.isoformat() if task.last_run_at else None, - "next_run_at": task.next_run_at.isoformat() if task.next_run_at else None, - }) +@file_check_bp.route("/tools/tasks", methods=["GET"]) +def list_file_check_tasks(): + """ + 查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。 + """ + raw_task_id = request.args.get("task_id", type=int) + if raw_task_id is None: + raise ValidationError("task_id_required") + task = _resolve_check_task(task_id=raw_task_id) + latest = ( + ScheduleRun.query.filter_by(schedule_task_id=task.id) + .order_by(ScheduleRun.id.desc()) + .first() + ) + tasks = [{ + "task_id": task.id, + "task_no": task.schedule_no, + "name": task.name, + "enabled": bool(task.enabled), + "last_status": latest.status if latest else None, + "last_run_at": task.last_run_at.isoformat() if task.last_run_at else None, + "next_run_at": task.next_run_at.isoformat() if task.next_run_at else None, + }] return jsonify({"ok": True, "tasks": tasks}) -def _normalize_rohs_bind_payload(data: dict | None) -> dict: - """ - 规范化启动检核 Body 中的绑定字段,兼容 Chatflow 漏传 hxops_session_id 的场景。 - - 核心逻辑:若 hxops_session_id 为空但 conversation_id 实为 HXOPS session_id,则自动补齐。 - """ +def _normalize_bind_payload(data: dict | None) -> dict: + """规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。""" payload = dict(data or {}) session_id = str(payload.get("hxops_session_id") or "").strip() if session_id: @@ -254,25 +241,19 @@ def _normalize_rohs_bind_payload(data: dict | None) -> dict: return payload -def _prepare_rohs_bind_payload(data: dict | None) -> dict: - """ - 合并规范化与 turn 注册表推断,得到可用于 ChatLog 绑定的启动检核 Body。 +def _prepare_bind_payload(data: dict | None) -> dict: + from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request - 核心逻辑:Dify HTTP 漏传 hxops_turn_id / hxops_session_id 时,从 HXOPS 侧登记轮次补齐。 - """ - from app.services.rohs_check_tools.chat_turn_registry import infer_bind_context_for_run_request - - payload = _normalize_rohs_bind_payload(data) + payload = _normalize_bind_payload(data) inferred = infer_bind_context_for_run_request(payload) if inferred: payload = {**payload, **inferred} return payload -def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None: - """写入 ScheduleRun 绑定上下文,并同步 turn 注册表。""" - from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context - from app.services.rohs_check_tools.chat_turn_registry import attach_run_to_turn +def _record_run_bind(run: ScheduleRun, data: dict) -> None: + from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context + from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn merge_chat_log_bind_context(run, data) turn_id = str(data.get("hxops_turn_id") or "").strip() @@ -280,31 +261,29 @@ def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None: attach_run_to_turn(turn_id, int(run.id)) -@rohs_check_bp.route("/tools/tasks/run", methods=["POST"]) -def run_rohs_check(): +@file_check_bp.route("/tools/tasks/run", methods=["POST"]) +def run_file_check(): """立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。""" perf_started = time.perf_counter() - data = _prepare_rohs_bind_payload(request.get_json(silent=True) or {}) + data = _prepare_bind_payload(request.get_json(silent=True) or {}) task = _resolve_check_task(data) resolve_ms = int((time.perf_counter() - perf_started) * 1000) lock_started = time.perf_counter() with _RUN_START_LOCK: - _acquire_rohs_start_lock() + _acquire_task_start_lock(task.id) existing = ( - ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id) - .filter(ScheduleRun.status == "running") + ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running") .order_by(ScheduleRun.id.desc()) - .all() + .first() ) - existing = next((row for row in existing if _is_rohs_check_task(row.task)), None) if existing: - _record_rohs_run_bind(existing, data) + _record_run_bind(existing, data) db.session.commit() lock_ms = int((time.perf_counter() - lock_started) * 1000) total_ms = int((time.perf_counter() - perf_started) * 1000) current_app.logger.info( - "[rohs-tool-perf] run_rohs_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s", + "[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s", resolve_ms, lock_ms, total_ms, @@ -333,7 +312,7 @@ def run_rohs_check(): ) db.session.add(run) db.session.commit() - _record_rohs_run_bind(run, data) + _record_run_bind(run, data) db.session.commit() app = current_app._get_current_object() run_id = run.id @@ -348,7 +327,7 @@ def run_rohs_check(): try: run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r) except Exception as exc: - current_app.logger.error("[rohs-tool] run_id=%s failed: %s", run_id, exc, exc_info=True) + current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True) r = db.session.get(ScheduleRun, run_id) if r and r.status == "running": r.status = "failed" @@ -356,12 +335,12 @@ def run_rohs_check(): r.finished_at = datetime.utcnow() db.session.commit() - threading.Thread(target=_background, daemon=True, name=f"rohs-check-run-{run_id}").start() + threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start() db.session.refresh(run) lock_ms = int((time.perf_counter() - lock_started) * 1000) total_ms = int((time.perf_counter() - perf_started) * 1000) current_app.logger.info( - "[rohs-tool-perf] run_rohs_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s", + "[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s", resolve_ms, lock_ms, total_ms, @@ -370,16 +349,16 @@ def run_rohs_check(): return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)}) -@rohs_check_bp.route("/tools/runs/", methods=["GET"]) -def get_rohs_run(run_id: int): +@file_check_bp.route("/tools/runs/", methods=["GET"]) +def get_file_check_run(run_id: int): run = get_run(run_id) if not run: raise NotFoundError("run_not_found") return jsonify({"ok": True, "run": _serialize_tool_run(run)}) -@rohs_check_bp.route("/tools/runs", methods=["GET"]) -def list_rohs_runs(): +@file_check_bp.route("/tools/runs", methods=["GET"]) +def list_file_check_runs(): raw_task_id = request.args.get("task_id", type=int) raw_limit = request.args.get("limit", default=20, type=int) limit = max(1, min(int(raw_limit or 20), 100)) @@ -389,12 +368,12 @@ def list_rohs_runs(): else: query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id) rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all() - runs = [_serialize_tool_run(row) for row in rows if _is_rohs_check_task(row.task)] + runs = [_serialize_tool_run(row) for row in rows] return jsonify({"ok": True, "runs": runs, "count": len(runs)}) -@rohs_check_bp.route("/tools/runs//excel", methods=["GET"]) -def download_rohs_run_excel(run_id: int): +@file_check_bp.route("/tools/runs//excel", methods=["GET"]) +def download_file_check_run_excel(run_id: int): token_payload = _decode_download_token(request.args.get("token")) if token_payload: if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id: @@ -413,8 +392,8 @@ def download_rohs_run_excel(run_id: int): ) -@rohs_check_bp.route("/tools/tasks//latest-run", methods=["GET"]) -def get_latest_rohs_run(task_id: int): +@file_check_bp.route("/tools/tasks//latest-run", methods=["GET"]) +def get_latest_file_check_run(task_id: int): task = _resolve_check_task(task_id=task_id) run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first() if not run: @@ -422,6 +401,6 @@ def get_latest_rohs_run(task_id: int): return jsonify({"ok": True, "run": _serialize_tool_run(run)}) -@rohs_check_bp.route("/tools/openapi.json", methods=["GET"]) -def rohs_openapi_spec(): - return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE())) +@file_check_bp.route("/tools/openapi.json", methods=["GET"]) +def file_check_openapi_spec(): + return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE())) diff --git a/backend/app/api/user.py b/backend/app/api/user.py index 676b3c1c..7082e3ca 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -1624,11 +1624,9 @@ def get_agent_details(id): raise ForbiddenError('Access denied') extra_config = agent.extra_config or {} if isinstance(extra_config, dict): - from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent - from app.services.rohs_check_tools.task_resolver import enrich_tool_run_progress_extra + from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check - if is_rohs_check_chat_agent(agent): - extra_config = enrich_tool_run_progress_extra(extra_config) + extra_config = enrich_agent_extra_if_file_check(agent) dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None dify_parameters = None diff --git a/backend/app/api/workspace_rohs_check.py b/backend/app/api/workspace_file_check.py similarity index 74% rename from backend/app/api/workspace_rohs_check.py rename to backend/app/api/workspace_file_check.py index 4ff53882..8ed1cbc1 100644 --- a/backend/app/api/workspace_rohs_check.py +++ b/backend/app/api/workspace_file_check.py @@ -1,3 +1,10 @@ +""" +backend/app/api/workspace_file_check.py + +用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。 +依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。 +逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。 +""" from __future__ import annotations from io import BytesIO @@ -5,14 +12,12 @@ from io import BytesIO from flask import Blueprint, jsonify, request, send_file from app.auth_jwt import get_current_user -from app.errors import ForbiddenError, NotFoundError, UnauthorizedError +from app.errors import NotFoundError, UnauthorizedError from app.models import ScheduleRun, ScheduleTask -from app.services.rohs_check_tools.chat_log_run_resolver import find_run_for_chat_log +from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log from app.services.schedule.query_service import get_run, serialize_run -workspace_rohs_check_bp = Blueprint("workspace_rohs_check", __name__) - -_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核") +workspace_file_check_bp = Blueprint("workspace_file_check", __name__) def _require_user(): @@ -22,21 +27,12 @@ def _require_user(): return user -def _is_rohs_check_task(task: ScheduleTask | None) -> bool: - if not task: - return False - values = ( - getattr(task, "schedule_no", None), - getattr(task, "name", None), - getattr(task, "platform_api_path", None), - ) - haystack = " ".join(str(item or "").lower() for item in values) - return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS) - - -def serialize_rohs_judgement(payload: dict) -> dict: +def serialize_file_judgement(payload: dict) -> dict: + """序列化检核判定统计(读取 response_summary_json.file_judgement)。""" response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {} - judgement = response_summary.get("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), dict) else {} + judgement = response_summary.get("file_judgement") + if not isinstance(judgement, dict): + judgement = {} return { "qualified_count": int(judgement.get("qualified_count") or 0), "unqualified_count": int(judgement.get("unqualified_count") or 0), @@ -76,14 +72,14 @@ def _serialize_progress_run(run: ScheduleRun) -> dict: "run_id": payload["id"], "run_no": payload["run_no"], "task_id": payload["schedule_task_id"], - "title": payload.get("schedule_name") or "RoHS 文件检核", + "title": payload.get("schedule_name") or "", "status": payload["status"], "total_count": total, "processed_count": processed, "success_count": success, "failed_count": failed, "skipped_count": skipped, - "judgement": serialize_rohs_judgement(payload), + "judgement": serialize_file_judgement(payload), "current_step": serialize_current_step(payload), "progress_percent": percent, "started_at": payload.get("started_at"), @@ -93,7 +89,7 @@ def _serialize_progress_run(run: ScheduleRun) -> dict: "excel": { "file_name": payload.get("excel_file_name"), "file_size": payload.get("excel_file_size"), - "download_url": f"/api/workspace/rohs-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None, + "download_url": f"/api/workspace/file-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None, }, "knowledge_base": { "sync_status": payload.get("kb_sync_status"), @@ -106,8 +102,8 @@ def _serialize_progress_run(run: ScheduleRun) -> dict: } -@workspace_rohs_check_bp.route("/rohs-check/runs/for-log", methods=["GET"]) -def workspace_rohs_run_for_log(): +@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"]) +def workspace_file_check_run_for_log(): """按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。""" _require_user() task_id = request.args.get("task_id", type=int) @@ -125,16 +121,16 @@ def workspace_rohs_run_for_log(): }) -@workspace_rohs_check_bp.route("/rohs-check/runs/for-session", methods=["GET"]) -def workspace_rohs_run_for_session(): +@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"]) +def workspace_file_check_run_for_session(): """已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。""" _require_user() return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None}) -@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"]) -def workspace_rohs_active_run(): - """查询当前进行中的 RoHS 检核批次;优先按 schedule_task_id(query: task_id)过滤。""" +@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"]) +def workspace_file_check_active_run(): + """查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。""" _require_user() task_id = request.args.get("task_id", type=int) conversation_id = str(request.args.get("conversation_id") or "").strip() @@ -146,13 +142,11 @@ def workspace_rohs_active_run(): query = query.filter(ScheduleRun.schedule_task_id == task_id) rows = query.order_by(ScheduleRun.id.desc()).all() if task_id is not None: - # 已按 schedule_task_id 过滤;不再比对 conversation_id(HXOPS session_id ≠ Dify sys.conversation_id) - run = next((row for row in rows if _is_rohs_check_task(row.task)), None) + run = rows[0] if rows else None else: run = next(( row for row in rows - if _is_rohs_check_task(row.task) - and ( + if ( not conversation_id or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id ) @@ -160,25 +154,21 @@ def workspace_rohs_active_run(): return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None}) -@workspace_rohs_check_bp.route("/rohs-check/runs/", methods=["GET"]) -def workspace_rohs_run_detail(run_id: int): +@workspace_file_check_bp.route("/file-check/runs/", methods=["GET"]) +def workspace_file_check_run_detail(run_id: int): _require_user() run = get_run(run_id) if not run: raise NotFoundError("run_not_found") - if not _is_rohs_check_task(run.task): - raise ForbiddenError("Forbidden") return jsonify({"ok": True, "run": _serialize_progress_run(run)}) -@workspace_rohs_check_bp.route("/rohs-check/runs//excel", methods=["GET"]) -def workspace_rohs_run_excel(run_id: int): +@workspace_file_check_bp.route("/file-check/runs//excel", methods=["GET"]) +def workspace_file_check_run_excel(run_id: int): _require_user() run = get_run(run_id) if not run: raise NotFoundError("run_not_found") - if not _is_rohs_check_task(run.task): - raise ForbiddenError("Forbidden") if not run.excel_file_data: raise NotFoundError("excel_not_found") return send_file( diff --git a/backend/app/config.py b/backend/app/config.py index acf0d238..b934d886 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -109,14 +109,14 @@ class Config: INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE') INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY') - # HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 共用;无尾斜杠) + # HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠) HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE') # 货代发货通知 Agent Tool API SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY') - # RoHS 检核 Chatflow Tool API - ROHS_TOOLS_API_KEY = os.getenv('ROHS_TOOLS_API_KEY') + # 文件检核 Chatflow Tool API + FILE_CHECK_TOOLS_API_KEY = os.getenv('FILE_CHECK_TOOLS_API_KEY') SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice") SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float( os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7' diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index a1a33aba..80b7b537 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -577,10 +577,10 @@ class DifyService: def _resolve_persist_run_id() -> int | None: try: - from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent - from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log + from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent + from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log - if not is_rohs_check_chat_agent(agent): + if not is_file_check_chat_agent(agent): return None return resolve_run_id_for_chat_log( session_id=session_id, @@ -604,7 +604,7 @@ class DifyService: if chat_persist_started and event_name == "workflow_finished" and chat_log_id_persisted: run_id = _resolve_persist_run_id() if run_id and run_id != run_id_persisted: - from app.services.rohs_check_tools.chat_log_run_binding import update_chat_log_run_id + from app.services.file_check_tools.chat_log_run_binding import update_chat_log_run_id if update_chat_log_run_id(chat_log_id_persisted, run_id): run_id_persisted = run_id @@ -845,7 +845,7 @@ class DifyService: latency: End-to-end latency in milliseconds. retriever_resources: Source retrieval metadata list. attribution_parts: Attribution/annotation list. - run_id: RoHS 检核批次 ID(按轮问答绑定,可选)。 + run_id: 文件检核批次 ID(按轮问答绑定,可选)。 """ try: chat_log = ChatLog( @@ -912,10 +912,10 @@ class DifyService: db_write_started = time.time() run_id = None try: - from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent - from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log + from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent + from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log - if is_rohs_check_chat_agent(agent): + if is_file_check_chat_agent(agent): run_id = resolve_run_id_for_chat_log( session_id=session_id, query=query, diff --git a/backend/app/services/rohs_check.py b/backend/app/services/file_check.py similarity index 72% rename from backend/app/services/rohs_check.py rename to backend/app/services/file_check.py index b4a7ebab..c094b682 100644 --- a/backend/app/services/rohs_check.py +++ b/backend/app/services/file_check.py @@ -1,6 +1,9 @@ """ -backend/app/services/rohs_check.py -文件用途:RoHS 文件检核统一判定入口,当前适配现有 Dify Workflow。 +backend/app/services/file_check.py + +用途:文件检核统一判定入口,调用 ScheduleTask 绑定的 Dify Workflow。 +依赖:DifyService.run_workflow_streaming。 +逻辑:由 schedule/srm_service 检核循环逐条调用;RoHS/MSDS 等差异在 Workflow 与排程 SQL 配置。 """ from __future__ import annotations @@ -8,12 +11,11 @@ from typing import Any from app.services.dify import DifyService - -VALID_ROHS_RESULTS = {"合格", "不合格", "人工判定"} +VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"} -class RoHSCheckService: - """Wrap RoHS judgement behind a stable backend interface.""" +class FileCheckService: + """文件检核 Dify Workflow 调用与结果规范化。""" PROVIDER = "dify_workflow" @@ -29,6 +31,21 @@ class RoHSCheckService: user: str = "schedule_system", timeout: tuple[int, int] = (5, 300), ) -> dict[str, Any]: + """ + 对单条待检记录调用 Dify Workflow 并返回规范化判定。 + + Args: + agent: ScheduleTask.dify_agent 对应的 Agent 记录。 + run_no: 当前检核批次号。 + record: 待检记录文本(由排程 SQL 组装)。 + attachment_url: 附件 URL,可选。 + system_prompt: 排程配置的补充系统提示,可选。 + user: Dify 用户标识。 + timeout: HTTP 超时 (connect, read) 秒。 + + Returns: + 含 dify_result、dify_message、workflow_run_id 等字段的 dict。 + """ inputs: dict[str, Any] = { "run_no": run_no, "record": record, @@ -60,6 +77,7 @@ class RoHSCheckService: @staticmethod def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]: + """将 Dify Workflow 输出规范为合格/不合格/人工判定。""" data = workflow_result if isinstance(workflow_result, dict) else {} outputs = (data.get("outputs") or {}).get("output") or data.get("outputs") or data output_data = outputs if isinstance(outputs, dict) else {} @@ -78,7 +96,7 @@ class RoHSCheckService: "raw_outputs": output_data, } - if dify_result not in VALID_ROHS_RESULTS: + if dify_result not in VALID_FILE_CHECK_RESULTS: bad_value = dify_result or "空" extra = f" | {dify_message}" if dify_message else "" return { diff --git a/backend/app/services/file_check_tools/__init__.py b/backend/app/services/file_check_tools/__init__.py new file mode 100644 index 00000000..70458b6e --- /dev/null +++ b/backend/app/services/file_check_tools/__init__.py @@ -0,0 +1 @@ +"""文件检核 Chatflow 工具包。""" diff --git a/backend/app/services/file_check_tools/agent_resolver.py b/backend/app/services/file_check_tools/agent_resolver.py new file mode 100644 index 00000000..f9f01710 --- /dev/null +++ b/backend/app/services/file_check_tools/agent_resolver.py @@ -0,0 +1,60 @@ +""" +services/file_check_tools/agent_resolver.py + +用途:识别具备文件检核进度能力的对话 Agent。 +依赖:Agent.extra_config(capabilities + tool_run_progress.schedule_task_id)。 +逻辑:chat.py / dify.py / user.py 通过 capabilities 驱动;agent_declares_file_check_progress 用于缺参时快速失败。 +""" +from __future__ import annotations + +from app.models import Agent + + +def _resolve_task_id_from_mapping(mapping: dict | None) -> int | None: + if not isinstance(mapping, dict): + return None + raw = mapping.get("schedule_task_id", mapping.get("task_id")) + try: + task_id = int(raw) + except (TypeError, ValueError): + return None + return task_id if task_id > 0 else None + + +def _extra_dict(agent) -> dict: + extra = getattr(agent, "extra_config", None) or {} + return extra if isinstance(extra, dict) else {} + + +def agent_declares_file_check_progress(agent) -> bool: + """ + 判断 Agent 是否声明了文件检核进度能力(不要求 schedule_task_id 已配齐)。 + + 用途:识别「已声明 tool_run_progress 但未配置 task_id」的 Agent,在调 Dify 前快速报错。 + """ + extra = _extra_dict(agent) + caps = extra.get("capabilities") or [] + if isinstance(caps, list) and "tool_run_progress" in caps: + return True + return isinstance(extra.get("tool_run_progress"), dict) + + +def is_file_check_chat_agent(agent) -> bool: + """ + 判断 Agent 是否为文件检核对话入口。 + + 核心逻辑:extra_config.capabilities 含 tool_run_progress,且配置了 schedule_task_id。 + """ + extra = _extra_dict(agent) + if not agent_declares_file_check_progress(agent): + return False + tool_cfg = extra.get("tool_run_progress") + if isinstance(tool_cfg, dict) and _resolve_task_id_from_mapping(tool_cfg): + return True + return bool(_resolve_task_id_from_mapping(extra)) + + +def resolve_chat_agent() -> Agent | None: + """返回第一个具备文件检核进度能力的活跃 Agent(测试/运维辅助)。""" + rows = Agent.query.filter(Agent.is_active.is_(True)).order_by(Agent.id.asc()).all() + return next((row for row in rows if is_file_check_chat_agent(row)), None) diff --git a/backend/app/services/rohs_check_tools/chat_log_run_binding.py b/backend/app/services/file_check_tools/chat_log_run_binding.py similarity index 81% rename from backend/app/services/rohs_check_tools/chat_log_run_binding.py rename to backend/app/services/file_check_tools/chat_log_run_binding.py index bd18ebf9..8783b49c 100644 --- a/backend/app/services/rohs_check_tools/chat_log_run_binding.py +++ b/backend/app/services/file_check_tools/chat_log_run_binding.py @@ -1,11 +1,10 @@ """ -services/rohs_check_tools/chat_log_run_binding.py +services/file_check_tools/chat_log_run_binding.py -用途:将 RoHS 检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。 -依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。 +用途:将文件检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。 +依赖:ChatLog、ScheduleRun、chat_turn_registry。 逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。 """ - from __future__ import annotations import re @@ -16,13 +15,11 @@ from flask import current_app from app import db from app.models import ChatLog, ScheduleRun -from app.services.rohs_check_tools.chat_turn_registry import ( +from app.services.file_check_tools.chat_turn_registry import ( attach_run_to_turn, - infer_bind_context_for_run_request, resolve_run_id_by_session_query, resolve_run_id_by_turn, ) -from app.services.rohs_check_tools.task_resolver import is_rohs_check_schedule_task def _normalize_bind_text(text: str | None) -> str: @@ -70,15 +67,10 @@ def resolve_run_id_for_chat_log( turn_id: str | None = None, ) -> int | None: """ - 匹配本轮问答应对绑定的 RoHS 检核批次 ID。 + 匹配本轮问答应对绑定的检核批次 ID。 优先级:hxops_turn_id > session_id + 归一化 query > session_id + 近期 bind。 - Args: - session_id: HXOPS ChatSession.session_id。 - query: 本轮用户输入(ChatLog.query)。 - turn_id: 本轮对话 turn 标识(HXOPS 注入 Dify inputs)。 - Returns: 匹配到的 ScheduleRun.id,或 None。 """ @@ -95,20 +87,18 @@ def resolve_run_id_for_chat_log( def _req(run: ScheduleRun) -> dict: return run.api_request_json if isinstance(run.api_request_json, dict) else {} - rohs_rows = [row for row in rows if is_rohs_check_schedule_task(row.task)] - if turn_key: registry_run_id = resolve_run_id_by_turn(turn_key) if registry_run_id: return registry_run_id - for run in rohs_rows: + for run in rows: req = _req(run) bind_turn = str(req.get("bind_turn_id") or req.get("hxops_turn_id") or "").strip() if bind_turn == turn_key: return int(run.id) if session_key and query_key: - for run in rohs_rows: + for run in rows: req = _req(run) bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip() bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message")) @@ -116,7 +106,7 @@ def resolve_run_id_for_chat_log( return int(run.id) if session_key and query_key: - for run in rohs_rows: + for run in rows: req = _req(run) bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip() bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message")) @@ -127,7 +117,7 @@ def resolve_run_id_for_chat_log( if session_key: cutoff = datetime.utcnow() - timedelta(minutes=15) - for run in rohs_rows: + for run in rows: req = _req(run) bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip() if bind_session != session_key: @@ -146,7 +136,7 @@ def resolve_run_id_for_chat_log( if current_app and (turn_key or session_key): current_app.logger.warning( - "[rohs-bind] resolve run_id miss turn_id=%s session_id=%s query_len=%s", + "[file-check-bind] resolve run_id miss turn_id=%s session_id=%s query_len=%s", turn_key or None, session_key or None, len(query_key), @@ -155,12 +145,7 @@ def resolve_run_id_for_chat_log( def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool: - """ - 回写已有 ChatLog.run_id(workflow_finished 二次绑定)。 - - Returns: - 是否成功更新。 - """ + """回写已有 ChatLog.run_id(workflow_finished 二次绑定)。""" if not chat_log_id or not run_id or run_id <= 0: return False log = db.session.get(ChatLog, chat_log_id) @@ -169,7 +154,7 @@ def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool: if log.run_id == run_id: return True run = db.session.get(ScheduleRun, run_id) - if not run or not is_rohs_check_schedule_task(run.task): + if not run: return False log.run_id = run_id db.session.commit() @@ -177,16 +162,11 @@ def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool: def bind_run_id_to_chat_log(*, chat_log: ChatLog | None, run_id: int | None) -> bool: - """ - 将检核批次 ID 写入 ChatLog.run_id。 - - Returns: - 是否成功写入并提交。 - """ + """将检核批次 ID 写入 ChatLog.run_id。""" if not chat_log or not run_id or run_id <= 0: return False run = db.session.get(ScheduleRun, run_id) - if not run or not is_rohs_check_schedule_task(run.task): + if not run: return False chat_log.run_id = run_id db.session.commit() diff --git a/backend/app/services/rohs_check_tools/chat_log_run_resolver.py b/backend/app/services/file_check_tools/chat_log_run_resolver.py similarity index 62% rename from backend/app/services/rohs_check_tools/chat_log_run_resolver.py rename to backend/app/services/file_check_tools/chat_log_run_resolver.py index 83d44f92..f1ab478a 100644 --- a/backend/app/services/rohs_check_tools/chat_log_run_resolver.py +++ b/backend/app/services/file_check_tools/chat_log_run_resolver.py @@ -1,16 +1,14 @@ """ -services/rohs_check_tools/chat_log_run_resolver.py +services/file_check_tools/chat_log_run_resolver.py -用途:按 ChatLog.run_id 解析 RoHS 检核进度(按轮问答)。 -依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。 +用途:按 ChatLog.run_id 解析文件检核进度(按轮问答)。 +依赖:ChatLog、ScheduleRun。 逻辑:由 for-log API 调用;run_id 在 message_end 写入 chat_logs 表。 """ - from __future__ import annotations from app import db from app.models import ChatLog, ScheduleRun -from app.services.rohs_check_tools.task_resolver import is_rohs_check_schedule_task def find_run_for_chat_log( @@ -19,7 +17,7 @@ def find_run_for_chat_log( chat_log_id: int, ) -> ScheduleRun | None: """ - 查询某条问答记录绑定的 RoHS 检核批次。 + 查询某条问答记录绑定的检核批次。 Args: task_id: ScheduleTask.id。 @@ -36,11 +34,7 @@ def find_run_for_chat_log( return None run = db.session.get(ScheduleRun, log.run_id) - if ( - run - and run.schedule_task_id == task_id - and is_rohs_check_schedule_task(run.task) - ): + if run and run.schedule_task_id == task_id: return run return None diff --git a/backend/app/services/rohs_check_tools/chat_turn_registry.py b/backend/app/services/file_check_tools/chat_turn_registry.py similarity index 90% rename from backend/app/services/rohs_check_tools/chat_turn_registry.py rename to backend/app/services/file_check_tools/chat_turn_registry.py index 51f12970..e7330665 100644 --- a/backend/app/services/rohs_check_tools/chat_turn_registry.py +++ b/backend/app/services/file_check_tools/chat_turn_registry.py @@ -1,11 +1,10 @@ """ -services/rohs_check_tools/chat_turn_registry.py +services/file_check_tools/chat_turn_registry.py -用途:RoHS 对话轮次与检核批次的内存注册表(HXOPS 侧登记 turn,不依赖 Dify HTTP 传参)。 +用途:文件检核对话轮次与检核批次的内存注册表(HXOPS 侧登记 turn,不依赖 Dify HTTP 传参)。 依赖:threading、datetime。 逻辑:chat.py 发消息时 register;run API 推断绑定并 attach_run;message_end 按 turn_id 解析 run_id。 """ - from __future__ import annotations import re @@ -24,8 +23,8 @@ def _normalize_text(text: str | None) -> str: @dataclass -class RohsChatTurn: - """单轮 RoHS 对话的绑定上下文。""" +class FileCheckChatTurn: + """单轮文件检核对话的绑定上下文。""" turn_id: str session_id: str @@ -37,7 +36,7 @@ class RohsChatTurn: _lock = Lock() -_turns_by_id: dict[str, RohsChatTurn] = {} +_turns_by_id: dict[str, FileCheckChatTurn] = {} def _prune_locked(now: datetime | None = None) -> None: @@ -55,7 +54,7 @@ def _prune_locked(now: datetime | None = None) -> None: _turns_by_id.pop(key, None) -def register_rohs_chat_turn( +def register_file_check_chat_turn( *, turn_id: str, session_id: str, @@ -64,7 +63,7 @@ def register_rohs_chat_turn( query: str, ) -> None: """ - 登记本轮 RoHS 对话上下文(chat API 在调用 Dify 前执行)。 + 登记本轮文件检核对话上下文(chat API 在调用 Dify 前执行)。 Args: turn_id: 本轮唯一标识(hxops_turn_id)。 @@ -77,7 +76,7 @@ def register_rohs_chat_turn( session_key = str(session_id or "").strip() if not turn_key or not session_key: return - item = RohsChatTurn( + item = FileCheckChatTurn( turn_id=turn_key, session_id=session_key, user_id=int(user_id), @@ -91,12 +90,7 @@ def register_rohs_chat_turn( def attach_run_to_turn(turn_id: str, run_id: int) -> bool: - """ - 将检核批次 ID 关联到已登记轮次。 - - Returns: - 是否成功关联。 - """ + """将检核批次 ID 关联到已登记轮次。""" turn_key = str(turn_id or "").strip() if not turn_key or run_id <= 0: return False @@ -124,8 +118,6 @@ def infer_bind_context_for_run_request(data: dict[str, Any] | None) -> dict[str, """ 为启动检核 HTTP Body 推断缺失的 hxops_session_id / hxops_turn_id。 - 核心逻辑:Dify HTTP 常漏传绑定字段时,用近期未绑定轮次 + query 模糊匹配补齐。 - Args: data: 启动检核请求 Body。 @@ -219,7 +211,7 @@ __all__ = [ "attach_run_to_turn", "clear_registry_for_tests", "infer_bind_context_for_run_request", - "register_rohs_chat_turn", + "register_file_check_chat_turn", "resolve_run_id_by_session_query", "resolve_run_id_by_turn", ] diff --git a/backend/app/services/file_check_tools/dify_inputs.py b/backend/app/services/file_check_tools/dify_inputs.py new file mode 100644 index 00000000..64d3489b --- /dev/null +++ b/backend/app/services/file_check_tools/dify_inputs.py @@ -0,0 +1,93 @@ +""" +services/file_check_tools/dify_inputs.py + +用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。 +依赖:task_resolver、agent_resolver、errors.ValidationError。 +逻辑:chat.py 在调 Dify 前调用本模块;缺失 schedule_task_id 时抛 ValidationError,避免 Dify 长连接挂死。 +""" +from __future__ import annotations + +from app.errors import ValidationError +from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent + +# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致 +FILE_CHECK_TASK_ID_INPUT = "task_id" +FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required" + + +def _missing_task_id_error(agent) -> ValidationError: + """ + 构造 task_id 未配置时的业务异常。 + + 核心逻辑:返回可操作的配置提示,供管理后台与前端直接展示。 + """ + return ValidationError( + "文件检核 Agent 未配置有效的 schedule_task_id,无法调用 Dify Chatflow。" + "请在管理后台编辑该 Agent,于 extra_config 中设置 " + "tool_run_progress.schedule_task_id(绑定排程任务 ID)。", + details={ + "error_code": FILE_CHECK_TASK_ID_MISSING_CODE, + "agent_id": getattr(agent, "id", None), + "agent_name": getattr(agent, "name", None) or "", + "config_hint": { + "capabilities": ["tool_run_progress"], + "tool_run_progress": { + "type": "file_check", + "schedule_task_id": "", + }, + }, + }, + ) + + +def ensure_file_check_task_id_configured(agent) -> int: + """ + 解析并校验文件检核 Agent 绑定的 schedule_task_id。 + + Args: + agent: 当前对话 Agent。 + + Returns: + 有效的 ScheduleTask.id。 + + Raises: + ValidationError: extra_config 未配置或 schedule_task_id 非法。 + """ + task_id = resolve_schedule_task_id_from_agent(agent) + if not task_id: + raise _missing_task_id_error(agent) + return task_id + + +def build_file_check_dify_inputs(agent, *, required: bool = False) -> dict[str, str]: + """ + 构建文件检核 Chatflow 的 Dify chat inputs。 + + 仅注入 task_id。hxops_session_id / hxops_turn_id 由 chat.py 登记 turn 注册表, + Tool API 启动时通过 user_message 推断,无需传入 Dify 画布。 + + Args: + agent: 当前对话 Agent;task_id 从其 extra_config 解析。 + required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。 + + Returns: + 含 task_id 的 inputs 字典;required=False 且未配置时返回空 dict。 + + Raises: + ValidationError: required=True 且 schedule_task_id 未配置。 + """ + task_id = resolve_schedule_task_id_from_agent(agent) + if not task_id: + if required: + raise _missing_task_id_error(agent) + return {} + return {FILE_CHECK_TASK_ID_INPUT: str(task_id)} + + +__all__ = [ + "FILE_CHECK_TASK_ID_INPUT", + "FILE_CHECK_TASK_ID_MISSING_CODE", + "build_file_check_dify_inputs", + "ensure_file_check_task_id_configured", +] + \ No newline at end of file diff --git a/backend/app/services/rohs_check_tools/openapi_base.json b/backend/app/services/file_check_tools/openapi_base.json similarity index 87% rename from backend/app/services/rohs_check_tools/openapi_base.json rename to backend/app/services/file_check_tools/openapi_base.json index 0b33ea9e..f2d543dd 100644 --- a/backend/app/services/rohs_check_tools/openapi_base.json +++ b/backend/app/services/file_check_tools/openapi_base.json @@ -1,13 +1,13 @@ { "openapi": "3.0.3", "info": { - "title": "HXOPS RoHS Check Tool API", - "description": "RoHS 文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。", + "title": "HXOPS File Check Tool API", + "description": "文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。", "version": "1.0.0" }, "servers": [ { - "url": "http://192.168.100.192:8890", + "url": "https://your-hxops-host", "description": "部署时设为 HXOPS_TOOLS_API_BASE;GET /tools/openapi.json 会按服务端配置自动覆盖" } ], @@ -20,12 +20,24 @@ } ], "paths": { - "/api/rohs-check/tools/tasks": { + "/api/file-check/tools/tasks": { "get": { - "operationId": "list_rohs_tasks", - "summary": "查询 RoHS 检核任务列表", + "operationId": "list_file_check_tasks", + "summary": "查询指定文件检核任务", "tags": [ - "RoHS Check" + "File Check" + ], + "parameters": [ + { + "name": "task_id", + "in": "query", + "required": true, + "schema": { + "type": "integer", + "example": 12 + }, + "description": "检核任务 ID(Agent 绑定的 schedule_task_id)" + } ], "responses": { "200": { @@ -38,21 +50,27 @@ } } }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, "401": { "$ref": "#/components/responses/Unauthorized" }, + "404": { + "$ref": "#/components/responses/TaskNotFound" + }, "503": { "$ref": "#/components/responses/MissingAuth" } } } }, - "/api/rohs-check/tools/tasks/run": { + "/api/file-check/tools/tasks/run": { "post": { - "operationId": "run_rohs_check", - "summary": "异步启动 RoHS 检核", + "operationId": "run_file_check", + "summary": "异步启动 文件检核", "tags": [ - "RoHS Check" + "File Check" ], "requestBody": { "required": true, @@ -66,7 +84,7 @@ }, "responses": { "200": { - "description": "启动成功;或已有 RoHS 检核进行中,返回 ok=false/error_code=check_running", + "description": "启动成功;或已有 文件检核进行中,返回 ok=false/error_code=check_running", "content": { "application/json": { "schema": { @@ -94,12 +112,12 @@ } } }, - "/api/rohs-check/tools/runs": { + "/api/file-check/tools/runs": { "get": { - "operationId": "list_rohs_runs", - "summary": "查询 RoHS 检核批次列表", + "operationId": "list_file_check_runs", + "summary": "查询 文件检核批次列表", "tags": [ - "RoHS Check" + "File Check" ], "parameters": [ { @@ -145,12 +163,12 @@ } } }, - "/api/rohs-check/tools/runs/{run_id}": { + "/api/file-check/tools/runs/{run_id}": { "get": { - "operationId": "get_rohs_run", + "operationId": "get_file_check_run", "summary": "查询指定检核批次", "tags": [ - "RoHS Check" + "File Check" ], "parameters": [ { @@ -183,12 +201,12 @@ } } }, - "/api/rohs-check/tools/tasks/{task_id}/latest-run": { + "/api/file-check/tools/tasks/{task_id}/latest-run": { "get": { - "operationId": "get_latest_rohs_run", + "operationId": "get_latest_file_check_run", "summary": "查询检核任务最近一次检核", "tags": [ - "RoHS Check" + "File Check" ], "parameters": [ { @@ -221,12 +239,12 @@ } } }, - "/api/rohs-check/tools/runs/{run_id}/excel": { + "/api/file-check/tools/runs/{run_id}/excel": { "get": { - "operationId": "download_rohs_run_excel", + "operationId": "download_file_check_run_excel", "summary": "下载检核报告 Excel(短期签名 token)", "tags": [ - "RoHS Check" + "File Check" ], "security": [], "parameters": [ @@ -243,7 +261,7 @@ "name": "token", "in": "query", "required": true, - "description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒", + "description": "由 get_file_check_run 返回的 excel.download_url 中的 JWT,有效期 600 秒", "schema": { "type": "string" } @@ -273,7 +291,7 @@ "BearerAuth": { "type": "http", "scheme": "bearer", - "description": "ROHS_TOOLS_API_KEY 或 INTEGRATION_API_KEY" + "description": "FILE_CHECK_TOOLS_API_KEY 或 INTEGRATION_API_KEY" }, "IntegrationKey": { "type": "apiKey", @@ -296,7 +314,7 @@ }, "name": { "type": "string", - "example": "RoHS 自动检核" + "example": "文件自动检核" }, "enabled": { "type": "boolean" @@ -334,7 +352,7 @@ "download_url": { "type": "string", "nullable": true, - "example": "http://192.168.100.192:8891/api/rohs-check/tools/runs/88/excel?token=..." + "example": "https://your-hxops-host/api/file-check/tools/runs/88/excel?token=..." } } }, @@ -396,7 +414,7 @@ }, "task_name": { "type": "string", - "example": "RoHS 自动检核" + "example": "文件自动检核" }, "status": { "type": "string", @@ -473,10 +491,6 @@ "type": "integer", "example": 12 }, - "task_no": { - "type": "string", - "example": "CHK202606090001" - }, "trigger_source": { "type": "string", "default": "dify_chatflow" @@ -493,7 +507,7 @@ "required": [ "task_id" ], - "description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程" + "description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配" }, "RunCheckSuccessResponse": { "type": "object", @@ -631,7 +645,7 @@ } }, "MissingAuth": { - "description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY", + "description": "服务端未配置 FILE_CHECK_TOOLS_API_KEY / INTEGRATION_API_KEY", "content": { "application/json": { "schema": { @@ -640,7 +654,7 @@ "example": { "ok": false, "error_code": "missing_auth", - "message": "ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured" + "message": "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured" } } } diff --git a/backend/app/services/rohs_check_tools/openapi_spec.py b/backend/app/services/file_check_tools/openapi_spec.py similarity index 61% rename from backend/app/services/rohs_check_tools/openapi_spec.py rename to backend/app/services/file_check_tools/openapi_spec.py index 5f4a08b3..2863d3bc 100644 --- a/backend/app/services/rohs_check_tools/openapi_spec.py +++ b/backend/app/services/file_check_tools/openapi_spec.py @@ -1,3 +1,10 @@ +""" +services/file_check_tools/openapi_spec.py + +用途:构建文件检核 Chatflow 的 OpenAPI 3.0 规范。 +依赖:openapi_base.json。 +逻辑:GET /api/file-check/tools/openapi.json 调用 build_file_check_openapi_spec。 +""" from __future__ import annotations import copy @@ -13,8 +20,8 @@ def _load_base_spec() -> dict[str, Any]: return json.load(fp) -def build_rohs_openapi_spec(base_url: str) -> dict[str, Any]: - """Build OpenAPI 3.0 spec for RoHS Chatflow HTTP tools.""" +def build_file_check_openapi_spec(base_url: str) -> dict[str, Any]: + """Build OpenAPI 3.0 spec for file-check Chatflow HTTP tools.""" spec = copy.deepcopy(_load_base_spec()) base = str(base_url or "").strip().rstrip("/") servers = spec.get("servers") diff --git a/backend/app/services/file_check_tools/progress_paths.py b/backend/app/services/file_check_tools/progress_paths.py new file mode 100644 index 00000000..9f057168 --- /dev/null +++ b/backend/app/services/file_check_tools/progress_paths.py @@ -0,0 +1,39 @@ +""" +services/file_check_tools/progress_paths.py + +用途:文件检核进度轮询 API 路径常量与展示标题解析。 +依赖:ScheduleTask。 +逻辑:前端/ enrich 由 schedule_task_id 推导 URL,管理员无需配置 log_progress_url。 +""" +from __future__ import annotations + +from app import db +from app.models import ScheduleTask + +FILE_CHECK_LOG_PROGRESS_PATH = "/api/workspace/file-check/runs/for-log" +FILE_CHECK_DETAIL_PATH_TEMPLATE = "/api/workspace/file-check/runs/{run_id}" + + +def resolve_file_check_progress_title(task_id: int | None) -> str: + """ + 从 ScheduleTask.name 解析进度卡片标题。 + + Args: + task_id: Agent extra_config 中的 schedule_task_id。 + + Returns: + 排程任务名称;不存在时返回空字符串。 + """ + if not task_id or task_id <= 0: + return "" + task = db.session.get(ScheduleTask, int(task_id)) + if not task: + return "" + return str(getattr(task, "name", "") or "").strip() + + +__all__ = [ + "FILE_CHECK_DETAIL_PATH_TEMPLATE", + "FILE_CHECK_LOG_PROGRESS_PATH", + "resolve_file_check_progress_title", +] diff --git a/backend/app/services/file_check_tools/task_resolver.py b/backend/app/services/file_check_tools/task_resolver.py new file mode 100644 index 00000000..5cd25b7c --- /dev/null +++ b/backend/app/services/file_check_tools/task_resolver.py @@ -0,0 +1,117 @@ +""" +services/file_check_tools/task_resolver.py + +用途:解析文件检核 Chatflow 绑定的 ScheduleTask.id 与 Agent 进度配置。 +依赖:ScheduleTask、Agent.extra_config、progress_paths、agent_resolver。 +逻辑:task_id 来自 Agent extra_config;title 来自 ScheduleTask.name;轮询 URL 由代码推导。 +""" +from __future__ import annotations + +from app.models import Agent, ScheduleTask +from app.services.file_check_tools.agent_resolver import _resolve_task_id_from_mapping +from app.services.file_check_tools.progress_paths import resolve_file_check_progress_title + +resolve_schedule_task_id_from_mapping = _resolve_task_id_from_mapping + + +def resolve_schedule_task_id_from_agent(agent) -> int | None: + """从 Agent extra_config 解析绑定的检核排程 task_id。""" + extra = getattr(agent, "extra_config", None) or {} + if not isinstance(extra, dict): + return None + tool_cfg = extra.get("tool_run_progress") + if isinstance(tool_cfg, dict): + task_id = resolve_schedule_task_id_from_mapping(tool_cfg) + if task_id: + return task_id + return resolve_schedule_task_id_from_mapping(extra) + + +def is_file_check_schedule_task(task: ScheduleTask | None) -> bool: + """判断排程任务是否存在(文件检核以 task_id 为准,不再按名称关键词过滤)。""" + return task is not None and int(getattr(task, "id", 0) or 0) > 0 + + +def _has_tool_run_progress_capability(extra: dict) -> bool: + caps = extra.get("capabilities") or [] + if isinstance(caps, list) and "tool_run_progress" in caps: + return True + if isinstance(extra.get("tool_run_progress"), dict): + return True + progress_type = str(extra.get("type") or "").strip().lower() + if progress_type == "file_check": + return True + tool_cfg = extra.get("tool_run_progress") + if isinstance(tool_cfg, dict): + nested_type = str(tool_cfg.get("type") or "").strip().lower() + if nested_type == "file_check": + return True + return False + + +def _apply_schedule_task_metadata(merged: dict) -> None: + """按 schedule_task_id 写入展示 title(ScheduleTask.name)。""" + task_id = resolve_schedule_task_id_from_mapping(merged) + if not task_id: + return + schedule_title = resolve_file_check_progress_title(task_id) + if schedule_title: + merged["title"] = schedule_title + + +def enrich_tool_run_progress_extra(extra_config: dict | None, *, agent: Agent | None = None) -> dict: + """ + 为文件检核 Agent 的 extra_config 补全 tool_run_progress 能力与轮询参数。 + + 核心逻辑:管理员只需配置 schedule_task_id;进度轮询 URL 由前后端按 task_id 推导,无需 log_progress_url。 + + Returns: + 新的 extra_config 副本。 + """ + extra = dict(extra_config or {}) + tool_cfg = extra.get("tool_run_progress") + merged = dict(tool_cfg) if isinstance(tool_cfg, dict) else { + "type": "file_check", + "poll_interval_seconds": 2, + "lock_input_when_running": True, + } + merged.setdefault("poll_interval_seconds", 2) + merged.setdefault("type", "file_check") + merged.setdefault("lock_input_when_running", True) + + if not resolve_schedule_task_id_from_mapping(merged) and agent is not None: + task_id = resolve_schedule_task_id_from_agent(agent) + if task_id: + merged["schedule_task_id"] = task_id + + _apply_schedule_task_metadata(merged) + + # 历史字段:若 DB 仍存有 URL,去掉以免误导运维重复维护 + merged.pop("log_progress_url", None) + merged.pop("detail_url_template", None) + merged.pop("session_progress_url", None) + + extra["tool_run_progress"] = merged + + capabilities = list(extra.get("capabilities") or []) + if "tool_run_progress" not in capabilities: + capabilities.append("tool_run_progress") + extra["capabilities"] = capabilities + return extra + + +def enrich_agent_extra_if_file_check(agent: Agent) -> dict: + """若 Agent 已声明 tool_run_progress 能力则 enrich extra_config,否则原样返回。""" + extra = dict(agent.extra_config or {}) if isinstance(agent.extra_config, dict) else {} + if _has_tool_run_progress_capability(extra): + return enrich_tool_run_progress_extra(extra, agent=agent) + return extra + + +__all__ = [ + "enrich_agent_extra_if_file_check", + "enrich_tool_run_progress_extra", + "is_file_check_schedule_task", + "resolve_schedule_task_id_from_agent", + "resolve_schedule_task_id_from_mapping", +] diff --git a/backend/app/services/rohs_check_tools/__init__.py b/backend/app/services/rohs_check_tools/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/backend/app/services/rohs_check_tools/agent_resolver.py b/backend/app/services/rohs_check_tools/agent_resolver.py deleted file mode 100644 index 3f43c785..00000000 --- a/backend/app/services/rohs_check_tools/agent_resolver.py +++ /dev/null @@ -1,21 +0,0 @@ -from __future__ import annotations - -from app.models import Agent - -# Dify / HXOPS Agent.name 常见取值(含「助手」后缀) -CHAT_AGENT_NAMES = frozenset( - { - "RoHS文件检核", - "RoHS文件检核助手", - "RoHS 文件检核助手", - } -) - - -def is_rohs_check_chat_agent(agent) -> bool: - name = (getattr(agent, "name", None) or "").strip() - return name in CHAT_AGENT_NAMES - - -def resolve_chat_agent() -> Agent | None: - return Agent.query.filter(Agent.name.in_(CHAT_AGENT_NAMES), Agent.is_active.is_(True)).first() diff --git a/backend/app/services/rohs_check_tools/dify_inputs.py b/backend/app/services/rohs_check_tools/dify_inputs.py deleted file mode 100644 index 88177a89..00000000 --- a/backend/app/services/rohs_check_tools/dify_inputs.py +++ /dev/null @@ -1,59 +0,0 @@ -from __future__ import annotations - -from flask import current_app - -from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE -from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent -from app.services.rohs_check_tools.task_resolver import resolve_default_rohs_schedule_task_id - -# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致(见 docs/rohs_chatflow_guide.md §3.1) -HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE" -HXOPS_TOOL_API_TOKEN_INPUT = "hxops_tool_api_token" -ROHS_TASK_ID_INPUT = "task_id" -HXOPS_SESSION_ID_INPUT = "hxops_session_id" -HXOPS_TURN_ID_INPUT = "hxops_turn_id" - - -def build_dify_chat_inputs( - hxops_session_id: str | None = None, - hxops_turn_id: str | None = None, -) -> dict[str, str]: - """ - 构建 RoHS Chatflow 的 Dify chat inputs(HTTP 节点与启动检核 Body 共用变量名)。 - - Args: - hxops_session_id: 当前 HXOPS ChatSession.session_id。 - hxops_turn_id: 本轮对话 turn 标识,用于 ChatLog.run_id 精确回写。 - """ - base = resolve_HXOPS_TOOLS_API_BASE() - key = str( - current_app.config.get("ROHS_TOOLS_API_KEY") - or current_app.config.get("INTEGRATION_API_KEY") - or "" - ).strip() - inputs: dict[str, str] = {} - if base: - inputs[HXOPS_TOOLS_API_BASE_INPUT] = base - if key: - inputs[HXOPS_TOOL_API_TOKEN_INPUT] = key - task_id = resolve_default_rohs_schedule_task_id() - if task_id: - inputs[ROHS_TASK_ID_INPUT] = str(task_id) - session_id = str(hxops_session_id or "").strip() - if session_id: - inputs[HXOPS_SESSION_ID_INPUT] = session_id - turn_id = str(hxops_turn_id or "").strip() - if turn_id: - inputs[HXOPS_TURN_ID_INPUT] = turn_id - return inputs - - -__all__ = [ - "HXOPS_TOOLS_API_BASE_INPUT", - "HXOPS_TOOL_API_TOKEN_INPUT", - "HXOPS_SESSION_ID_INPUT", - "HXOPS_TURN_ID_INPUT", - "ROHS_TASK_ID_INPUT", - "build_dify_chat_inputs", - "is_rohs_check_chat_agent", -] diff --git a/backend/app/services/rohs_check_tools/task_resolver.py b/backend/app/services/rohs_check_tools/task_resolver.py deleted file mode 100644 index 35422f21..00000000 --- a/backend/app/services/rohs_check_tools/task_resolver.py +++ /dev/null @@ -1,114 +0,0 @@ -""" -services/rohs_check_tools/task_resolver.py - -用途:解析 RoHS Chatflow 绑定的 ScheduleTask.id,供 Dify inputs、Agent 进度能力与 active 轮询使用。 -依赖:ScheduleTask、rohs_check_tools 任务识别逻辑。 -逻辑:优先读 Agent extra_config;否则在仅有一个 RoHS 检核任务时自动选用。 -""" - -from __future__ import annotations - -from flask import current_app - -from app.models import ScheduleTask - -_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核") - - -def is_rohs_check_schedule_task(task: ScheduleTask | None) -> bool: - """判断排程任务是否为 RoHS 文件检核任务。""" - if not task: - return False - values = ( - getattr(task, "schedule_no", None), - getattr(task, "name", None), - getattr(task, "platform_api_path", None), - ) - haystack = " ".join(str(item or "").lower() for item in values) - return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS) - - -def list_rohs_schedule_tasks() -> list[ScheduleTask]: - """列出全部 RoHS 检核排程任务。""" - rows = ScheduleTask.query.order_by(ScheduleTask.id.asc()).all() - return [task for task in rows if is_rohs_check_schedule_task(task)] - - -def resolve_schedule_task_id_from_mapping(mapping: dict | None) -> int | None: - """从 tool_run_progress 或等价 dict 解析 schedule_task_id / task_id。""" - if not isinstance(mapping, dict): - return None - raw = mapping.get("schedule_task_id", mapping.get("task_id")) - try: - task_id = int(raw) - except (TypeError, ValueError): - return None - return task_id if task_id > 0 else None - - -def resolve_default_rohs_schedule_task_id() -> int | None: - """ - 解析默认 RoHS 检核 ScheduleTask.id。 - - 优先级:环境变量/配置 ROHS_CHATFLOW_SCHEDULE_TASK_ID → 库内唯一 RoHS 任务 → None。 - """ - configured = current_app.config.get("ROHS_CHATFLOW_SCHEDULE_TASK_ID") - if configured not in (None, "", 0, "0"): - try: - task_id = int(configured) - if task_id > 0: - return task_id - except (TypeError, ValueError): - pass - - tasks = list_rohs_schedule_tasks() - if len(tasks) == 1: - return int(tasks[0].id) - return None - - -def enrich_tool_run_progress_extra(extra_config: dict | None) -> dict: - """ - 为 RoHS Agent 的 extra_config 补全 tool_run_progress 能力与默认轮询配置。 - - 核心逻辑:RoHS 对话 Agent 自动挂载 tool_run_progress 能力,避免漏配 capabilities 导致进度卡片不显示。 - - Returns: - 新的 extra_config 副本。 - """ - extra = dict(extra_config or {}) - tool_cfg = extra.get("tool_run_progress") - merged = dict(tool_cfg) if isinstance(tool_cfg, dict) else { - "type": "rohs_check", - "title": "RoHS 文件检核", - "poll_interval_seconds": 2, - "lock_input_when_running": True, - } - merged.setdefault("log_progress_url", "/api/workspace/rohs-check/runs/for-log") - merged.setdefault("detail_url_template", "/api/workspace/rohs-check/runs/{run_id}") - merged.setdefault("poll_interval_seconds", 2) - merged.setdefault("title", "RoHS 文件检核") - merged.setdefault("type", "rohs_check") - merged.setdefault("lock_input_when_running", True) - - if not resolve_schedule_task_id_from_mapping(merged): - task_id = resolve_default_rohs_schedule_task_id() - if task_id: - merged["schedule_task_id"] = task_id - - extra["tool_run_progress"] = merged - - capabilities = list(extra.get("capabilities") or []) - if "tool_run_progress" not in capabilities: - capabilities.append("tool_run_progress") - extra["capabilities"] = capabilities - return extra - - -__all__ = [ - "enrich_tool_run_progress_extra", - "is_rohs_check_schedule_task", - "list_rohs_schedule_tasks", - "resolve_default_rohs_schedule_task_id", - "resolve_schedule_task_id_from_mapping", -] diff --git a/backend/app/services/schedule/srm_service.py b/backend/app/services/schedule/srm_service.py index c76b74b5..2f337650 100644 --- a/backend/app/services/schedule/srm_service.py +++ b/backend/app/services/schedule/srm_service.py @@ -5,7 +5,7 @@ from typing import Any, Callable from flask import current_app, has_app_context -from app.services.rohs_check import RoHSCheckService +from app.services.file_check import FileCheckService try: import pyodbc # type: ignore @@ -213,7 +213,7 @@ def _run_check_job_loop( progress_run.failed_count = failed_count progress_run.skipped_count = skipped_count summary = dict(progress_run.response_summary_json or {}) - summary["rohs_judgement"] = dict(judgement_stats) + summary["file_judgement"] = dict(judgement_stats) if current_step: summary["current_step"] = dict(current_step) progress_run.response_summary_json = summary @@ -316,7 +316,7 @@ def _run_check_job_loop( t_dify = _ts() try: _set_current_step("call_dify", row_id_value) - dify_res = RoHSCheckService.evaluate( + dify_res = FileCheckService.evaluate( agent=agent, run_no=run_no, record=record_text, diff --git a/backend/scripts/export_rohs_check_openapi.py b/backend/scripts/export_file_check_openapi.py similarity index 65% rename from backend/scripts/export_rohs_check_openapi.py rename to backend/scripts/export_file_check_openapi.py index de485ac5..26a33d46 100644 --- a/backend/scripts/export_rohs_check_openapi.py +++ b/backend/scripts/export_file_check_openapi.py @@ -1,4 +1,4 @@ -"""Export Dify-compatible OpenAPI for RoHS Check tools paste/import.""" +"""Export Dify-compatible OpenAPI for File Check tools paste/import.""" from __future__ import annotations import json @@ -9,7 +9,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "backend")) -from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec +from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec def main() -> None: @@ -18,13 +18,13 @@ def main() -> None: or os.getenv("PUBLIC_BASE_URL") or "http://127.0.0.1:5052" ).rstrip("/") - spec = build_rohs_openapi_spec(base) + spec = build_file_check_openapi_spec(base) out_dir = ROOT / "docs" / "openapi" out_dir.mkdir(parents=True, exist_ok=True) - json_path = out_dir / "rohs_check_tools_openapi.json" + json_path = out_dir / "file_check_tools_openapi.json" json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8") print(f"Wrote {json_path}") - print(f"Import URL: {base}/api/rohs-check/tools/openapi.json") + print(f"Import URL: {base}/api/file-check/tools/openapi.json") if __name__ == "__main__": diff --git a/backend/tests/test_rohs_check_tools.py b/backend/tests/test_file_check_tools.py similarity index 74% rename from backend/tests/test_rohs_check_tools.py rename to backend/tests/test_file_check_tools.py index 001b2892..0be97848 100644 --- a/backend/tests/test_rohs_check_tools.py +++ b/backend/tests/test_file_check_tools.py @@ -5,12 +5,12 @@ import pytest from app import db from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User -from app.services.rohs_check import RoHSCheckService +from app.services.file_check import FileCheckService @pytest.fixture(autouse=True) -def _clear_rohs_turn_registry(): - from app.services.rohs_check_tools.chat_turn_registry import clear_registry_for_tests +def _clear_file_check_turn_registry(): + from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests clear_registry_for_tests() yield @@ -61,7 +61,7 @@ def _mk_check_task(owner_id: int, *, enabled=True): return task -def _mk_non_rohs_task(owner_id: int): +def _mk_other_check_task(owner_id: int): task = ScheduleTask( schedule_no='CHK-GENERAL-001', name='通用检核', @@ -77,8 +77,8 @@ def _mk_non_rohs_task(owner_id: int): return task -def test_rohs_service_normalizes_failed_workflow(): - payload = RoHSCheckService.normalize_workflow_result({ +def test_file_check_service_normalizes_failed_workflow(): + payload = FileCheckService.normalize_workflow_result({ 'status': 'failed', 'error': 'workflow timeout', 'workflow_run_id': 'wf-2', @@ -88,15 +88,15 @@ def test_rohs_service_normalizes_failed_workflow(): assert payload['workflow_run_id'] == 'wf-2' -def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch): +def test_file_check_service_evaluate_degrades_on_dify_error(monkeypatch): class _Agent: id = 1 def _boom(**kwargs): raise RuntimeError('dify down') - monkeypatch.setattr('app.services.rohs_check.DifyService.run_workflow_streaming', _boom) - payload = RoHSCheckService.evaluate( + monkeypatch.setattr('app.services.file_check.DifyService.run_workflow_streaming', _boom) + payload = FileCheckService.evaluate( agent=_Agent(), run_no='RUN-1', record='Pb: 100ppm', @@ -106,8 +106,8 @@ def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch): assert payload['error'] == 'dify down' -def test_rohs_service_normalizes_invalid_result(): - payload = RoHSCheckService.normalize_workflow_result({ +def test_file_check_service_normalizes_invalid_result(): + payload = FileCheckService.normalize_workflow_result({ 'status': 'succeeded', 'outputs': {'dify_result': 'OK', 'dify_message': 'bad enum'}, 'workflow_run_id': 'wf-1', @@ -117,7 +117,7 @@ def test_rohs_service_normalizes_invalid_result(): assert payload['workflow_run_id'] == 'wf-1' -def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch): +def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch): from app.services.schedule.srm_service import _run_check_job_loop class _Agent: @@ -134,7 +134,7 @@ def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch): writebacks = [] - monkeypatch.setattr('app.services.schedule.srm_service.RoHSCheckService.evaluate', _evaluate) + monkeypatch.setattr('app.services.schedule.srm_service.FileCheckService.evaluate', _evaluate) with app.app_context(): admin = _mk_admin() db.session.flush() @@ -158,7 +158,7 @@ def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch): log_prefix='row', ) db.session.refresh(run) - judgement = (run.response_summary_json or {}).get('rohs_judgement') or {} + judgement = (run.response_summary_json or {}).get('file_judgement') or {} assert total == 1 assert success == 1 @@ -216,55 +216,78 @@ def test_srm_sql_operations_apply_configured_timeout(app, monkeypatch): assert observed == {'connect_timeout': 7, 'cursor_timeout': 7} -def test_rohs_tool_requires_auth(app, client): +def test_file_check_tool_requires_auth(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' - res = client.get('/api/rohs-check/tools/tasks') + res = client.get('/api/file-check/tools/tasks') assert res.status_code == 401 assert res.get_json()['error_code'] == 'missing_auth' -def test_rohs_tool_rejects_invalid_auth(app, client): +def test_file_check_tool_rejects_invalid_auth(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' - res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'wrong'}) + res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'wrong'}) assert res.status_code == 401 assert res.get_json()['error_code'] == 'invalid_auth' -def test_rohs_tool_lists_tasks(app, client): +def test_file_check_tool_lists_tasks_requires_task_id(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + + res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'secret'}) + assert res.status_code == 400 + assert res.get_json()['error_code'] == 'task_id_required' + + +def test_file_check_tool_lists_task_by_task_id(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' admin = _mk_admin() db.session.commit() _mk_check_task(admin.id) - _mk_non_rohs_task(admin.id) + other_task = _mk_other_check_task(admin.id) + task_id = other_task.id - res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'secret'}) + res = client.get( + f'/api/file-check/tools/tasks?task_id={task_id}', + headers={'X-Integration-Key': 'secret'}, + ) assert res.status_code == 200 data = res.get_json() assert data['ok'] is True - assert [item['task_no'] for item in data['tasks']] == ['CHK-ROHS-001'] + assert len(data['tasks']) == 1 + assert data['tasks'][0]['task_id'] == task_id + assert data['tasks'][0]['task_no'] == 'CHK-GENERAL-001' -def test_rohs_tool_rejects_non_rohs_task(app, client): +def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch): + class _Thread: + def __init__(self, *args, **kwargs): + pass + + def start(self): + return None + + monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread) with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' admin = _mk_admin() db.session.commit() - task = _mk_non_rohs_task(admin.id) + task = _mk_other_check_task(admin.id) task_id = task.id res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={'task_id': task_id}, ) - assert res.status_code == 404 - assert res.get_json()['error_code'] == 'task_not_found' + assert res.status_code == 200 + assert res.get_json()['ok'] is True -def test_rohs_tool_running_conflict(app, client): +def test_file_check_tool_running_conflict(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' admin = _mk_admin() @@ -276,7 +299,7 @@ def test_rohs_tool_running_conflict(app, client): db.session.commit() res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={'task_id': task_id}, ) @@ -286,7 +309,7 @@ def test_rohs_tool_running_conflict(app, client): assert data['error_code'] == 'check_running' -def test_rohs_tool_check_running_records_chat_log_bind_context(app, client): +def test_file_check_tool_check_running_records_chat_log_bind_context(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' admin = _mk_admin() @@ -304,7 +327,7 @@ def test_rohs_tool_check_running_records_chat_log_bind_context(app, client): running_run_id = run.id res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={ 'task_id': task_id, @@ -322,7 +345,7 @@ def test_rohs_tool_check_running_records_chat_log_bind_context(app, client): assert req.get('bind_user_message') == '立即执行检核' -def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch): +def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkeypatch): class _Thread: def __init__(self, *, target, daemon, name): self.target = target @@ -332,7 +355,7 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch) def start(self): return None - monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread) + monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread) with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' @@ -342,7 +365,7 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch) task_id = task.id res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={ 'task_id': task_id, @@ -360,18 +383,18 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch) assert req.get('bind_session_id') == 'bind-on-start' assert req.get('bind_turn_id') == 'turn-abc-001' assert req.get('bind_user_message') == '执行 RoHS 检核' - from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log + from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log assert resolve_run_id_for_chat_log(turn_id='turn-abc-001') == run_id assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id -def test_rohs_tool_requires_task_id(app, client): +def test_file_check_tool_requires_task_id(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={}, ) @@ -379,12 +402,12 @@ def test_rohs_tool_requires_task_id(app, client): assert res.get_json()['error_code'] == 'task_id_required' -def test_rohs_tool_rejects_invalid_task_id(app, client): +def test_file_check_tool_rejects_invalid_task_id(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={'task_id': 'abc'}, ) @@ -392,7 +415,15 @@ def test_rohs_tool_rejects_invalid_task_id(app, client): assert res.get_json()['error_code'] == 'task_id_invalid' -def test_rohs_tool_running_conflict_is_global(app, client): +def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch): + class _Thread: + def __init__(self, *args, **kwargs): + pass + + def start(self): + return None + + monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread) with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' admin = _mk_admin() @@ -417,24 +448,23 @@ def test_rohs_tool_running_conflict_is_global(app, client): running_id = running.id res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={'task_id': second_task_id}, ) assert res.status_code == 200 data = res.get_json() - assert data['ok'] is False - assert data['error_code'] == 'check_running' - assert data['run']['run_id'] == running_id + assert data['ok'] is True + assert data['run']['task_id'] == second_task_id -def test_rohs_tool_lists_all_rohs_runs(app, client): +def test_file_check_tool_lists_runs_without_task_filter(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' admin = _mk_admin() db.session.commit() rohs_task = _mk_check_task(admin.id) - other_task = _mk_non_rohs_task(admin.id) + other_task = _mk_other_check_task(admin.id) db.session.add_all([ ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=rohs_task.id, status='success', trigger_type='manual', total_count=3, success_count=3), ScheduleRun(run_no='RUN-ROHS-002', schedule_task_id=rohs_task.id, status='partial_failed', trigger_type='manual', total_count=4, success_count=3, failed_count=1), @@ -442,15 +472,15 @@ def test_rohs_tool_lists_all_rohs_runs(app, client): ]) db.session.commit() - res = client.get('/api/rohs-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'}) + res = client.get('/api/file-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'}) assert res.status_code == 200 data = res.get_json() assert data['ok'] is True - assert data['count'] == 2 - assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002'} + assert data['count'] == 3 + assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002', 'RUN-OTHER-001'} -def test_workspace_rohs_active_run_returns_progress(app, client): +def test_workspace_file_check_active_run_returns_progress(app, client): with app.app_context(): admin = _mk_admin() db.session.commit() @@ -480,7 +510,7 @@ def test_workspace_rohs_active_run_returns_progress(app, client): db.session.add(run) db.session.commit() - res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'}) + res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'}) assert res.status_code == 200 data = res.get_json() assert data['ok'] is True @@ -491,7 +521,7 @@ def test_workspace_rohs_active_run_returns_progress(app, client): assert data['run']['current_step']['row_id'] == 'ROW-16' -def test_workspace_rohs_active_run_filters_by_task_id(app, client): +def test_workspace_file_check_active_run_filters_by_task_id(app, client): with app.app_context(): admin = _mk_admin() db.session.commit() @@ -530,21 +560,21 @@ def test_workspace_rohs_active_run_filters_by_task_id(app, client): task_b_id = task_b.id hit = client.get( - f'/api/workspace/rohs-check/runs/active?task_id={task_a_id}', + f'/api/workspace/file-check/runs/active?task_id={task_a_id}', headers={'X-Username': 'admin'}, ) assert hit.status_code == 200 assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-A' miss = client.get( - f'/api/workspace/rohs-check/runs/active?task_id={task_b_id}', + f'/api/workspace/file-check/runs/active?task_id={task_b_id}', headers={'X-Username': 'admin'}, ) assert miss.status_code == 200 assert miss.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-B' -def test_workspace_rohs_active_run_ignores_conversation_when_task_id_set(app, client): +def test_workspace_file_check_active_run_ignores_conversation_when_task_id_set(app, client): with app.app_context(): admin = _mk_admin() db.session.commit() @@ -563,14 +593,14 @@ def test_workspace_rohs_active_run_ignores_conversation_when_task_id_set(app, cl task_id = task.id res = client.get( - f'/api/workspace/rohs-check/runs/active?task_id={task_id}&conversation_id=hxops-session-id', + f'/api/workspace/file-check/runs/active?task_id={task_id}&conversation_id=hxops-session-id', headers={'X-Username': 'admin'}, ) assert res.status_code == 200 assert res.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-CONV-MISMATCH' -def test_workspace_rohs_active_run_filters_by_conversation_id(app, client): +def test_workspace_file_check_active_run_filters_by_conversation_id(app, client): with app.app_context(): admin = _mk_admin() db.session.commit() @@ -587,16 +617,16 @@ def test_workspace_rohs_active_run_filters_by_conversation_id(app, client): db.session.add(run) db.session.commit() - miss = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'}) + miss = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'}) assert miss.status_code == 200 assert miss.get_json()['run'] is None - hit = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'}) + hit = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'}) assert hit.status_code == 200 assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-ACTIVE-CONV' -def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client): +def test_workspace_file_check_run_for_log_returns_null_when_unbound(app, client): with app.app_context(): admin = _mk_admin() db.session.commit() @@ -614,7 +644,7 @@ def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client): chat_log_id = log.id res = client.get( - f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}', + f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}', headers={'X-Username': 'admin'}, ) assert res.status_code == 200 @@ -623,7 +653,7 @@ def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client): assert payload.get('match_source') is None -def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client): +def test_workspace_file_check_run_for_log_reads_bound_run_id(app, client): with app.app_context(): admin = _mk_admin() db.session.commit() @@ -652,7 +682,7 @@ def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client): chat_log_id = log.id res = client.get( - f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}', + f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}', headers={'X-Username': 'admin'}, ) assert res.status_code == 200 @@ -661,7 +691,7 @@ def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client): assert payload['match_source'] == 'chat_log' -def test_workspace_rohs_run_for_log_allows_different_user(app, client): +def test_workspace_file_check_run_for_log_allows_different_user(app, client): with app.app_context(): owner = User(username='rohs-owner', email='owner-rohs@example.com', role='admin', status='active') owner.set_password('x') @@ -694,14 +724,14 @@ def test_workspace_rohs_run_for_log_allows_different_user(app, client): chat_log_id = log.id res = client.get( - f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}', + f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}', headers={'X-Username': 'rohs-viewer'}, ) assert res.status_code == 200 assert res.get_json()['run']['run_no'] == 'RUN-ROHS-CROSS-USER' -def test_workspace_rohs_run_for_log_returns_null_when_task_mismatch(app, client): +def test_workspace_file_check_run_for_log_returns_null_when_task_mismatch(app, client): with app.app_context(): admin = _mk_admin() db.session.commit() @@ -727,24 +757,24 @@ def test_workspace_rohs_run_for_log_returns_null_when_task_mismatch(app, client) chat_log_id = log.id res = client.get( - f'/api/workspace/rohs-check/runs/for-log?task_id=99999&chat_log_id={chat_log_id}', + f'/api/workspace/file-check/runs/for-log?task_id=99999&chat_log_id={chat_log_id}', headers={'X-Username': 'admin'}, ) assert res.status_code == 200 assert res.get_json()['run'] is None -def test_workspace_rohs_active_run_returns_null_when_idle(app, client): +def test_workspace_file_check_active_run_returns_null_when_idle(app, client): with app.app_context(): _mk_admin() db.session.commit() - res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'}) + res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'}) assert res.status_code == 200 assert res.get_json()['run'] is None -def test_rohs_tool_excel_download_uses_signed_token(app, client): +def test_file_check_tool_excel_download_uses_signed_token(app, client): with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' admin = _mk_admin() @@ -763,19 +793,19 @@ def test_rohs_tool_excel_download_uses_signed_token(app, client): db.session.commit() run_id = run.id - query_res = client.get(f'/api/rohs-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'}) + query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'}) token_url = query_res.get_json()['run']['excel']['download_url'] - download_path = token_url[token_url.index('/api/rohs-check'):] + download_path = token_url[token_url.index('/api/file-check'):] res = client.get(download_path) assert res.status_code == 200 assert res.data == b'xlsx-bytes' - res = client.get('/api/rohs-check/tools/tasks?token=' + download_path.split('token=', 1)[1]) + res = client.get('/api/file-check/tools/tasks?token=' + download_path.split('token=', 1)[1]) assert res.status_code == 401 -def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch): +def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch): started_threads = [] class _Thread: @@ -787,7 +817,7 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch): def start(self): started_threads.append(self.name) - monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread) + monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread) with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' @@ -797,7 +827,7 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch): task_id = task.id res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={'task_id': task_id}, ) @@ -806,52 +836,199 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch): assert data['ok'] is True assert data['run']['task_id'] == task_id assert data['run']['status'] == 'running' - assert started_threads == [f"rohs-check-run-{data['run']['run_id']}"] + assert started_threads == [f"file-check-run-{data['run']['run_id']}"] -def test_rohs_openapi_injects_tool_api_base(app, client): +def test_serialize_file_judgement_reads_file_key(): + from app.api.workspace_file_check import serialize_file_judgement + + payload = { + "response_summary_json": { + "file_judgement": { + "qualified_count": 2, + "unqualified_count": 1, + "manual_count": 0, + "dify_error_count": 0, + "invalid_result_count": 0, + } + } + } + result = serialize_file_judgement(payload) + assert result["qualified_count"] == 2 + assert result["unqualified_count"] == 1 + + +def test_file_check_openapi_injects_tool_api_base(app, client): with app.app_context(): - app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com' - res = client.get('/api/rohs-check/tools/openapi.json') + app.config['HXOPS_TOOLS_API_BASE'] = 'https://file-check-tool.example.com' + res = client.get('/api/file-check/tools/openapi.json') assert res.status_code == 200 - assert res.get_json()['servers'][0]['url'] == 'https://rohs-tool.example.com' + assert res.get_json()['servers'][0]['url'] == 'https://file-check-tool.example.com' -def test_rohs_dify_chat_inputs(app): - from app.services.rohs_check_tools.dify_inputs import ( - HXOPS_TOOL_API_TOKEN_INPUT, - HXOPS_TOOLS_API_BASE_INPUT, - build_dify_chat_inputs, +def test_file_check_dify_chat_inputs(app): + from app.services.file_check_tools.dify_inputs import ( + FILE_CHECK_TASK_ID_INPUT, + build_file_check_dify_inputs, ) - from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent + from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent class _Agent: - def __init__(self, name: str): + def __init__(self, name: str, *, extra_config=None): self.name = name + self.extra_config = extra_config or {} - assert is_rohs_check_chat_agent(_Agent('RoHS文件检核助手')) - assert not is_rohs_check_chat_agent(_Agent('货代发货通知 Agent')) + assert is_file_check_chat_agent(_Agent( + 'RoHS文件检核助手', + extra_config={ + 'capabilities': ['tool_run_progress'], + 'tool_run_progress': {'schedule_task_id': 12}, + }, + )) + assert not is_file_check_chat_agent(_Agent('RoHS文件检核助手')) + assert not is_file_check_chat_agent(_Agent('货代发货通知 Agent')) + + agent = _Agent( + 'RoHS文件检核助手', + extra_config={ + 'capabilities': ['tool_run_progress'], + 'tool_run_progress': {'schedule_task_id': 12}, + }, + ) + with app.app_context(): + inputs = build_file_check_dify_inputs(agent) + assert inputs[FILE_CHECK_TASK_ID_INPUT] == '12' + assert 'hxops_session_id' not in inputs + assert 'hxops_turn_id' not in inputs + + +def test_file_check_dify_chat_inputs_without_extra_task_id(app): + import pytest + + from app.errors import ValidationError + from app.services.file_check_tools.dify_inputs import ( + FILE_CHECK_TASK_ID_MISSING_CODE, + build_file_check_dify_inputs, + ) + + class _Agent: + id = 26 + name = 'RoHS文件检核助手' + extra_config = {} with app.app_context(): - app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com' - app.config['ROHS_TOOLS_API_KEY'] = 'rohs-secret' - inputs = build_dify_chat_inputs(hxops_session_id='sess-abc') - assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com' - assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret' - assert inputs['hxops_session_id'] == 'sess-abc' + assert build_file_check_dify_inputs(_Agent()) == {} + with pytest.raises(ValidationError) as exc: + build_file_check_dify_inputs(_Agent(), required=True) + assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE -def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app): - from app.services.rohs_check_tools.dify_inputs import build_dify_chat_inputs +def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(app): + import pytest + from app.errors import ValidationError + from app.services.file_check_tools.agent_resolver import ( + agent_declares_file_check_progress, + is_file_check_chat_agent, + ) + from app.services.file_check_tools.dify_inputs import ( + FILE_CHECK_TASK_ID_MISSING_CODE, + build_file_check_dify_inputs, + ) + + class _Agent: + def __init__(self): + self.id = 26 + self.name = 'RoHS文件检核助手' + self.extra_config = { + 'capabilities': ['tool_run_progress'], + 'tool_run_progress': {'type': 'file_check'}, + } + + agent = _Agent() + assert agent_declares_file_check_progress(agent) + assert not is_file_check_chat_agent(agent) with app.app_context(): - app.config.pop('HXOPS_TOOLS_API_BASE', None) - app.config['HXOPS_TOOLS_API_BASE'] = 'https://legacy-tool.example.com' - app.config.pop('ROHS_TOOLS_API_KEY', None) - app.config['INTEGRATION_API_KEY'] = 'integration-secret' - inputs = build_dify_chat_inputs() - assert inputs['HXOPS_TOOLS_API_BASE'] == 'https://legacy-tool.example.com' - assert inputs['hxops_tool_api_token'] == 'integration-secret' + with pytest.raises(ValidationError) as exc: + build_file_check_dify_inputs(agent, required=True) + assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE + assert 'schedule_task_id' in exc.value.message + + +def test_chat_completions_rejects_missing_file_check_task_id(app, client, mocker): + """声明了文件检核能力但未配置 schedule_task_id 时,/completions 应立即 400 而非挂死。""" + from flask import g + + from app.models import Agent, User + + misconfigured = Agent( + id=26, + name='RoHS文件检核助手', + dify_api_key='app-key', + api_base_url='http://dify.example/v1', + type='api', + extra_config={ + 'capabilities': ['tool_run_progress'], + 'tool_run_progress': {'type': 'file_check'}, + }, + is_active=True, + ) + user = User(id=1, username='admin', status='active', role='admin') + user.agents = [misconfigured] + + def mock_get_user(): + g.current_user = user + return user + + mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user) + mocker.patch('app.models.Agent.query').get.return_value = misconfigured + mock_post = mocker.patch('requests.post') + mock_post.side_effect = AssertionError('Dify must not be called when task_id is missing') + + res = client.post( + '/api/chat/completions', + json={'query': '立即执行RoHS文件检核', 'agent_id': 26}, + headers={'Content-Type': 'application/json'}, + ) + + assert res.status_code == 400 + body = res.get_json() + assert body['error']['code'] == 'VALIDATION.INVALID_PARAM' + assert body['error']['details']['error_code'] == 'file_check_task_id_required' + mock_post.assert_not_called() + + +def test_chat_agent_proxy_passes_extra_config_for_task_id_injection(): + """chat.py agent_proxy 须携带 extra_config,否则 is_file_check_chat_agent / task_id 注入失效。""" + from types import SimpleNamespace + + from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent + from app.services.file_check_tools.dify_inputs import ( + FILE_CHECK_TASK_ID_INPUT, + build_file_check_dify_inputs, + ) + + agent_proxy = SimpleNamespace( + id=26, + name='RoHS文件检核助手', + dify_api_key='app-key', + api_base_url='http://dify.example/v1', + extra_config={ + 'capabilities': ['tool_run_progress'], + 'tool_run_progress': {'schedule_task_id': 12}, + }, + ) + assert is_file_check_chat_agent(agent_proxy) + assert build_file_check_dify_inputs(agent_proxy)[FILE_CHECK_TASK_ID_INPUT] == '12' + + bare_proxy = SimpleNamespace( + id=26, + name='RoHS文件检核助手', + dify_api_key='app-key', + api_base_url='http://dify.example/v1', + ) + assert not is_file_check_chat_agent(bare_proxy) + assert build_file_check_dify_inputs(bare_proxy) == {} def test_kb_sync_skips_failed_run(app): @@ -1168,7 +1345,7 @@ def test_kb_sync_inline_processes_clean_and_sync_jobs(app, monkeypatch, tmp_path assert run.kb_sync_status in ('success', 'ready', 'syncing') -def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch): +def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch): """Dify HTTP 仅传 task_id + user_message 时,仍应通过 turn 注册表回写 run_id。""" class _Thread: def __init__(self, *, target, daemon, name): @@ -1179,7 +1356,7 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa def start(self): return None - monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread) + monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread) with app.app_context(): app.config['INTEGRATION_API_KEY'] = 'secret' @@ -1189,10 +1366,10 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa task_id = task.id admin_id = admin.id - from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn - from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log + from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn + from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log - register_rohs_chat_turn( + register_file_check_chat_turn( turn_id='turn-registry-001', session_id='sess-registry-001', user_id=1, @@ -1201,7 +1378,7 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa ) res = client.post( - '/api/rohs-check/tools/tasks/run', + '/api/file-check/tools/tasks/run', headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, json={ 'task_id': task_id, @@ -1230,7 +1407,14 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa event_name='message_end', request_id='req-bind-test', user_id=admin_id, - agent=type('AgentProxy', (), {'id': 1, 'name': 'RoHS文件检核助手'})(), + agent=type('AgentProxy', (), { + 'id': 1, + 'name': 'RoHS文件检核助手', + 'extra_config': { + 'capabilities': ['tool_run_progress'], + 'tool_run_progress': {'schedule_task_id': task_id}, + }, + })(), session_id='sess-registry-001', hxops_turn_id='turn-registry-001', normalized_conversation_id='sess-registry-001', diff --git a/docs/convention/COMMIT_CONVENTION.md b/docs/convention/COMMIT_CONVENTION.md index 73946c61..3ee04784 100644 --- a/docs/convention/COMMIT_CONVENTION.md +++ b/docs/convention/COMMIT_CONVENTION.md @@ -83,7 +83,8 @@ Scope 应对齐代码模块,便于从提交信息定位到目录。选取规 | --- | --- | | `schedule` | `services/schedule/`、`api/schedule_admin`、前端 `features/admin/modules/schedules/` | | `shipping-notice` | `services/shipping_notice/`、`api/workspace_shipping_notice` | -| `rohs-check` | `services/rohs_check*`、`api/rohs_check_tools` | +| `file-check` | `services/file_check*`、`api/file_check_tools` | +| `rohs-check` | RoHS 实例(历史 scope,新改动请用 `file-check`) | | `knowledge-base` | `api/knowledge_base`、`services/knowledge_cleaning/` | | `chat` | `api/chat`、前端 chat 相关 | | `auth` | 登录认证 | diff --git a/docs/demand.md b/docs/demand.md index f292694a..ee2becdf 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -22,14 +22,13 @@ ## 3. 范围说明 -### 3.x RoHS 文件检核补充需求 +### 3.x 文件检核(file_check)补充需求 -- **核心目标**:提供 RoHS 文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。 -- 新增 `RoHSCheckService` 作为统一判定入口,内部复用现有 Dify RoHS Workflow 中的 Prompt 与模型配置。 -- 新增 Dify Chatflow 显式 HTTP Tool,用于对话中发起检核、查询检核状态与展示结果;不使用 Agent 节点做逐条判定。 -- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 通过 Knowledge Retrieval 检索已入库历史报告(与 Tool API 实时查询并存)。 -- 后台执行、定时触发、数据抓取与写回沿用现有任务引擎(实现细节对用户透明)。 -- Dify Chatflow 编排与 OpenAPI 导入见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)。 +- **核心目标**:提供通用文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。 +- **通用域**:`FileCheckService` + `/api/file-check` Tool API + 单套 Dify Chatflow「文件检核助手」;RoHS、MSDS 等差异仅在排程 SQL、`task_id` 与判定 Workflow。 +- **多 Agent**:RoHS / MSDS 等工作台 Agent 共用同一 `dify_app_id`,HXOPS 按 `extra_config.tool_run_progress.schedule_task_id` 注入 `task_id`。 +- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 历史分支按 `task_id` 选择知识库 Dataset。 +- Dify Chatflow 编排与 OpenAPI 导入见 [docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md)。 ### 3.1 本期范围 diff --git a/docs/file_check_chatflow_guide.md b/docs/file_check_chatflow_guide.md new file mode 100644 index 00000000..30bf3ff6 --- /dev/null +++ b/docs/file_check_chatflow_guide.md @@ -0,0 +1,1401 @@ +> **通用化说明**:本手册适用于 RoHS、MSDS 等所有文件检核类型。多个 Agent 共用同一 Dify Chatflow;HXOPS 按 Agent `extra_config.tool_run_progress.schedule_task_id` 注入不同 `task_id`。历史查询按 `task_id` 分支选择知识库 Dataset。 +> **唯一文档**:编排、OpenAPI Tool 配置、部署、Agent 配置、验证与排错 **均在本文件**;勿再维护 `rohs_chatflow_*` 或 `ops/file_check_deploy_migration.md`。 + +# 文件检核 Chatflow — 完整手册 + +> **唯一技术文档**:文件检核 Chatflow 编排、Dify OpenAPI Tool、HXOPS 部署与 Agent 配置 **仅维护本文件**(`docs/file_check_chatflow_guide.md`)。 +> **同步维护**:Tool API 契约变更时,须同时更新本文件、`backend/app/services/file_check_tools/openapi_base.json`,并执行 `python backend/scripts/export_file_check_openapi.py` 重新生成 [`docs/openapi/file_check_tools_openapi.json`](./openapi/file_check_tools_openapi.json)。 +> **维护原则**:**按编排节点顺序**在 [§3](#3-按节点顺序配置核心维护区) 逐节维护;每节包含该节点的全部配置(输入绑定、Prompt / **Tool** / Code / IF / Answer),不再把同一节点拆到多处。 + +## 产品定位 + +本 Chatflow 是 **文件检核助手**。对用户暴露的能力是: + +1. **发起检核** — 触发一批待检记录的判定与写回 +2. **查询检核** — 查看检核进度、统计摘要、失败原因 +3. **获取报告** — 下载检核结果 Excel +4. **知识库同步** — 查看检核报告是否已入库 +5. **历史查询** — 基于已同步知识库检索历史检核报告、异常、供应商或料号记录 + +**关于执行方式**:无论是定时触发、后台批量还是对话中即时发起,对用户统一称为 **检核**。当前一期由 HXOPS 后台检核任务承载执行,Chatflow 通过 Tool API 发起与查询。 + +**职责边界**: + +- **Dify 检核 Workflow** + `FileCheckService`:逐条判定合格 / 不合格 / 人工判定 +- **本 Chatflow**:编排对话,调用 HXOPS Tool API 发起检核、查结果、展示报告链接;对历史报告类问题调用知识库检索;**不自行做合格判定** +- **当前有效启动方式**:每个 Agent 绑定一个 `task_id`(HXOPS 对话 API 注入);Chatflow 通过 **OpenAPI Tool 节点**调用 `run_file_check`,不再使用 HTTP Request 节点,也不做任务列表选择。 +- **前端进度展示**:HXOPS 前端通过 Agent `extra_config.capabilities=["tool_run_progress"]` 挂载通用任务进度卡片,不按 Agent 名称硬编码。 + +**Tool API 基路径**:`/api/file-check` +**OpenAPI 文件**:[`docs/openapi/file_check_tools_openapi.json`](./openapi/file_check_tools_openapi.json) +**OpenAPI 在线**:`GET /api/file-check/tools/openapi.json`(无需鉴权) +**鉴权 Header**:`Authorization: Bearer ` 或 `X-Integration-Key: ` + +--- + +## 目录 + +1. [部署与前置配置](#1-部署与前置配置) +2. [编排总览](#2-编排总览) +3. [按节点顺序配置(核心维护区)](#3-按节点顺序配置核心维护区) + - [3.0 Dify 变量类型约定](#30-dify-变量类型约定) + - [3.1 用户输入](#31-用户输入) + - [3.2 LLM:意图识别](#32-llm意图识别) + - [3.3 IF:意图分类](#33-if意图分类) + - [3.8 Tool:异步启动检核](#38-tool异步启动检核) + - [3.9 Code:解析启动检核响应](#39-code解析启动检核响应) + - [3.10 IF:启动结果分支](#310-if启动结果分支) + - [3.11 Answer:检核已启动](#311-answer检核已启动) + - [3.12 Answer:检核进行中](#312-answer检核进行中) + - [3.14 Code:提取查询参数](#314-code提取查询参数) + - [3.15 IF:查询方式](#315-if查询方式) + - [3.16 Tool:查询指定检核](#316-tool查询指定检核) + - [3.17 Tool:查询最近检核](#317-tool查询最近检核) + - [3.17A Tool:查询所有检核批次](#317a-tool查询所有检核批次) + - [3.18 Code:解析检核查询响应(两个节点)](#318-code解析检核查询响应两个节点) + - [3.19 LLM:生成结果说明(两个节点)](#319-llm生成结果说明两个节点) + - [3.20 Answer:返回查询结果(两个节点)](#320-answer返回查询结果两个节点) + - [3.21 Answer:引导提供查询条件](#321-answer引导提供查询条件) + - [3.22 Answer:能力说明](#322-answer能力说明) + - [3.23 Answer:兜底引导](#323-answer兜底引导) + - [3.24 Answer:错误兜底](#324-answer错误兜底) + - [3.25 Knowledge Retrieval:检索历史检核报告](#325-knowledge-retrieval检索历史检核报告) + - [3.26 LLM:生成历史报告回答](#326-llm生成历史报告回答) + - [3.27 Answer:返回历史查询结果](#327-answer返回历史查询结果) +4. [附录 A:OpenAPI 规范](#附录-aopenapi-规范) +5. [附录 B:错误码总表](#附录-b错误码总表) +6. [附录 C:发布验证用例](#附录-c发布验证用例) +7. [附录 D:相关代码](#附录-d相关代码) +8. [附录 E:HTTP 迁移与排错](#附录-ehttp-迁移与排错) + +--- + +## 1. 部署与前置配置 + +本节为画布搭建前的环境准备;**节点级配置均在 §3 按顺序维护**。 + +### 1.1 数据库迁移 + +```bash +cd backend +flask db upgrade +``` + +需已应用 文件检核知识库同步相关迁移(`kb_sync_enabled`、`kb_group_id` 等字段)。 + +### 1.2 环境变量 + +| 变量 | 必填 | 说明 | +| --- | --- | --- | +| `HXOPS_TOOLS_API_BASE` | 推荐 | Dify Tool 调用 hxops 的对外根地址(无尾斜杠),用于 OpenAPI、Excel 签名链接;未配置时回退 `PUBLIC_BASE_URL` | +| `FILE_CHECK_TOOLS_API_KEY` | 推荐 | Chatflow Tool 专用 token;未配置时回退 `INTEGRATION_API_KEY` | +| `INTEGRATION_API_KEY` | 二选一 | 与历史集成接口共用时可复用 | + +**注意**:token 仅放在 Dify Secret/Credential,不要写入前端或导出 YAML。 + +**HXOPS 对话 API**(`/api/chat/completions`):向 Dify 仅注入 **`task_id`**;`conversation_id` 由 Dify 系统变量提供。 +**进度卡片绑定**(服务端,不在 Dify 画布配置):`chat.py` 每轮登记 `chat_turn_registry`,Tool `run_file_check` 传 `user_message`(+ `task_id`)即可,后端推断 session/turn 并回写 `chat_logs.run_id`。 +**OpenAPI 工具托管**:Base URL 与 Bearer token 在 §1.4–§1.5 配置,画布内勿使用 HTTP Request 节点。 + +### 1.3 创建 Chatflow 应用 + +1. HXOPS 后端已部署且迁移已执行。 +2. Dify 控制台 → **创建应用** → 类型选 **Chatflow**(**不要**选 Agent)。 +3. 应用名称建议:`文件检核助手`。 +4. Dify 能访问 `HXOPS_TOOLS_API_BASE` 所指地址。 + +### 1.4 导入 OpenAPI 自定义工具 + +在 Dify **工具 → 自定义 → 创建自定义工具 → 从 OpenAPI 导入**(**不要**在 Chatflow 画布 HTTP Request 节点里导入)。 + +**方式 A — URL 导入(推荐)** + +```text +GET {HXOPS_TOOLS_API_BASE}/api/file-check/tools/openapi.json +``` + +该端点**无需鉴权**;响应中 `servers[0].url` 已按服务端 `HXOPS_TOOLS_API_BASE` 填充。换环境时重新 URL 导入或改工具 Server URL,**不必改 Chatflow 连线**。 + +**方式 B — 上传文件** + +1. 下载 [`docs/openapi/file_check_tools_openapi.json`](./openapi/file_check_tools_openapi.json)(或执行 `python backend/scripts/export_file_check_openapi.py`)。 +2. 若从仓库下载 JSON,把 `servers[0].url` 设为与部署环境 `HXOPS_TOOLS_API_BASE` 相同。 +3. 在 Dify 工具管理页上传 JSON。 + +**Chatflow 画布需绑定的 operationId** + +| operationId | Tool 节点建议名称 | 用途 | +| --- | --- | --- | +| `run_file_check` | `Tool:启动检核` | §3.8 发起检核 | +| `get_file_check_run` | `Tool:查询指定检核` | §3.16 按 run_id 查询 | +| `get_latest_file_check_run` | `Tool:查询最近检核` | §3.17 按 task_id 查最近一次 | +| `list_file_check_runs` | `Tool:查询所有检核批次` | §3.17A 批次列表 | + +`list_file_check_tasks` 仅运维调试(须传 `task_id`),不参与画布编排。`download_file_check_run_excel` 由查询结果中的 `excel.download_url` 提供,Chatflow 不直接调用。 + +### 1.5 配置 Tool Credential + +1. 打开 §1.4 导入的 OpenAPI 自定义工具 → **授权**。 +2. 类型:**Bearer Token** / **API Key**(与 OpenAPI `BearerAuth` 一致)。 +3. Token 值:与 `FILE_CHECK_TOOLS_API_KEY` **完全相同**(**不要**写 `Bearer ` 前缀,**不要**写 `${FILE_CHECK_TOOLS_API_KEY}` 占位符)。 +4. Chatflow 内 **Tool 节点只填业务参数**,不填 Authorization Header;鉴权由工具配置自动附加。 + +名称建议:`hxops_file_check_tool`(与工具集命名一致即可)。 + +### 1.6 绑定历史检核知识库(历史查询前置) + +历史查询(§3.25)依赖检核任务已配置 `kb_sync_enabled` 且报告已清洗并同步到 Dify Dataset。 + +| 步骤 | 操作 | +| --- | --- | +| 1 | HXOPS 排程/检核任务管理:为目标检核任务绑定 **知识库分组**(`kb_group_id`),启用 `kb_sync_enabled` | +| 2 | 确认该 `KbGroup` 已关联 **Dify Dataset**(`dify_dataset_id`),且 kb-worker 正常运行 | +| 3 | 执行一次检核并确认 `run.knowledge_base.sync_status == success`(可通过 §3.14–§3.20 实时查询分支查看) | +| 4 | Dify Chatflow → §3.25 **Knowledge Retrieval** 节点:选择与该 `KbGroup` 对应的 **知识库 / Dataset**(与 hxops 同步目标一致) | +| 5 | 发布前用附录 C 中「上周有哪些不合格」等话术验证历史分支能召回片段 | + +> 实时查询(批次状态、Excel 链接)仍只走 Tool API;知识库节点**不能**替代 `get_file_check_run` / `latest-run`。 + +### 1.7 发布前自检 + +```bash +# 启动检核(task_id 替换为当前环境 ScheduleTask.id) +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + -d '{"task_id":,"trigger_source":"dify_chatflow"}' \ + "$HXOPS_TOOLS_API_BASE/api/file-check/tools/tasks/run" +``` + +### 1.8 HXOPS Agent 进度能力配置 + +需要在 文件检核 Agent 的 `extra_config` 中配置通用进度能力: + +```json +{ + "capabilities": ["tool_run_progress"], + "tool_run_progress": { + "type": "file_check", + "schedule_task_id": 2, + "poll_interval_seconds": 2, + "lock_input_when_running": true + } +} +``` + +说明: + +- 前端只判断 `tool_run_progress` 能力,不判断 Agent 名称。 +- **`schedule_task_id` 必填**:与排程 `ScheduleTask.id` 一致;HXOPS 对话 API 将其作为 Dify `inputs.task_id` 注入。 +- 也可用别名 `task_id`(与 `schedule_task_id` 二选一,含义相同)。 +- **无需配置 `log_progress_url` / `detail_url_template`**:前端与后端按固定路径 + `schedule_task_id` / `run_id` 自动拼接轮询 URL。 +- **卡片标题**:优先使用 `ScheduleTask.name`(enrich 时写入 `tool_run_progress.title`);进度 API 返回的 `run.title` 亦来自排程名称。 +- `poll_interval_seconds` 默认 2 秒,前端限制在 1-30 秒。 +- 运行中若 `lock_input_when_running=true`,当前 Agent 对话输入、发送和附件上传会被锁定。 +- **进度卡片权威来源**:`chat.py` 登记 turn → Tool 启动时写入 `ScheduleRun.api_request_json` 绑定字段 → `message_end` 按 turn/query 匹配并写入 **`chat_logs.run_id`**。Dify 画布**无需**传递 `hxops_session_id` / `hxops_turn_id`。 +- **查询类分支**不调用启动检核 API,对应 `ChatLog` 无 `run_id`,不会出现进度条。 +- 纯问答/查询与「立即执行」由 LLM 路由到不同 **Tool** 节点区分,**不要**在前端或 Agent 配置里硬编码意图关键词。 + +### 1.9 新增检核类型(如 MSDS) + +| 步骤 | 操作 | +| --- | --- | +| 1 | 排程管理新建 `ScheduleTask` + 取数 SQL + Dify 检核 Workflow | +| 2 | 绑定知识库分组(若需历史查询),启用 `kb_sync_enabled` | +| 3 | 新建 Agent:与 RoHS 等 **共用同一** `dify_app_id` / Chatflow;`extra_config.tool_run_progress.schedule_task_id` = 新 task id | +| 4 | Chatflow §3.25 历史分支:按 `用户输入.task_id` 选择对应 Dataset(多 Agent 共用画布时须分支或 metadata 过滤) | +| 5 | 授权用户访问新 Agent;按 [附录 C](#附录-c发布验证用例) 冒烟 | + +### 1.10 生产切换说明 + +- **Breaking**:不保留 `/api/rohs-check` 及 `/api/workspace/rohs-check` 兼容路径;统一 `/api/file-check`。 +- 环境变量 `ROHS_TOOLS_API_KEY` 已更名为 `FILE_CHECK_TOOLS_API_KEY`(未配则回退 `INTEGRATION_API_KEY`)。 +- RoHS / MSDS 等 Agent **共用同一 Chatflow**;差异仅在 Agent `schedule_task_id` 与历史知识库 Dataset。 +- Dify:在**工具管理**重新 URL 导入 OpenAPI(§1.4),画布使用 **Tool 节点**(§3.8 起),**删除**旧 HTTP Request 检核节点。 +- Start:**不要**写死各环境 `task_id`(HXOPS 对话 API 注入);**不要**再配 `HXOPS_TOOLS_API_BASE` / `hxops_tool_api_token`(OpenAPI 工具 Credential 托管)。 + +--- + +## 2. 编排总览 + +**原则**:不使用 Agent 节点;使用 **LLM + IF + Tool + Code + Knowledge Retrieval + Answer**。实时检核走 OpenAPI Tool 节点;历史报告走知识库检索(§2.1、§3.25–§3.27)。 + +```mermaid +flowchart TD + A[用户输入] --> B[LLM: 意图识别] + B --> C{IF: 意图分类} + + C -->|run_check| G[Tool: 启动检核] + G --> G2[Code: 解析启动检核响应] + G2 --> I{IF: 启动是否成功} + I -->|ok=true| J[Answer: 检核已启动] + I -->|check_running| K[Answer: 检核进行中] + I -->|其他错误| L[Answer: 错误兜底] + + C -->|check_status| M[Code: 提取查询参数] + M --> N{IF: 查询方式} + N -->|by_run_id| O[Tool: 查询指定检核] + N -->|latest_by_task| P[Tool: 查询最近检核] + N -->|all_runs| Y[Tool: 查询所有检核批次] + N -->|missing| Q[Answer: 引导提供查询条件] + + O --> O2[Code: 解析指定检核查询响应] + O2 --> R1[LLM: 生成指定检核结果说明] + R1 --> S1[Answer: 返回指定检核结果] + P --> P2[Code: 解析最近检核查询响应] + P2 --> R2[LLM: 生成最近检核结果说明] + R2 --> S2[Answer: 返回最近检核结果] + Y --> Y2[Code: 解析所有检核批次响应] + Y2 --> Y3[Answer: 返回所有检核批次] + + C -->|history_report_query| V[Knowledge Retrieval: 检索历史检核报告] + V --> W[LLM: 生成历史报告回答] + W --> X[Answer: 返回历史查询结果] + + C -->|explain_capability| T[Answer: 能力说明] + C -->|other| U[Answer: 兜底引导] +``` + +| # | 节点类型 | 节点名 | 配置章节 | +| --- | --- | --- | --- | +| 1 | Start | 用户输入 | [§3.1](#31-用户输入) | +| 2 | LLM | 意图识别 | [§3.2](#32-llm意图识别) | +| 3 | IF | 意图分类 | [§3.3](#33-if意图分类) | +| 4 | Tool | 启动检核 | [§3.8](#38-tool异步启动检核) | +| 5 | Code | 解析启动检核响应 | [§3.9](#39-code解析启动检核响应) | +| 6 | IF | 启动结果分支 | [§3.10](#310-if启动结果分支) | +| 7 | Answer | 检核已启动 | [§3.11](#311-answer检核已启动) | +| 8 | Answer | 检核进行中 | [§3.12](#312-answer检核进行中) | +| 14 | Code | 提取查询参数 | [§3.14](#314-code提取查询参数) | +| 15 | IF | 查询方式 | [§3.15](#315-if查询方式) | +| 16 | Tool | 查询指定检核 | [§3.16](#316-tool查询指定检核) | +| 17 | Tool | 查询最近检核 | [§3.17](#317-tool查询最近检核) | +| 17A | Tool | 查询所有检核批次 | [§3.17A](#317a-tool查询所有检核批次) | +| 18a | Code | 解析指定检核查询响应 | [§3.18](#318-code解析检核查询响应两个节点) | +| 18b | Code | 解析最近检核查询响应 | [§3.18](#318-code解析检核查询响应两个节点) | +| 19a | LLM | 生成指定检核结果说明 | [§3.19](#319-llm生成结果说明两个节点) | +| 19b | LLM | 生成最近检核结果说明 | [§3.19](#319-llm生成结果说明两个节点) | +| 20a | Answer | 返回指定检核结果 | [§3.20](#320-answer返回查询结果两个节点) | +| 20b | Answer | 返回最近检核结果 | [§3.20](#320-answer返回查询结果两个节点) | +| 21 | Answer | 引导提供查询条件 | [§3.21](#321-answer引导提供查询条件) | +| 22 | Answer | 能力说明 | [§3.22](#322-answer能力说明) | +| 23 | Answer | 兜底引导 | [§3.23](#323-answer兜底引导) | +| 24 | Answer | 错误兜底 | [§3.24](#324-answer错误兜底) | +| 25 | Knowledge Retrieval | 检索历史检核报告 | [§3.25](#325-knowledge-retrieval检索历史检核报告) | +| 26 | LLM | 生成历史报告回答 | [§3.26](#326-llm生成历史报告回答) | +| 27 | Answer | 返回历史查询结果 | [§3.27](#327-answer返回历史查询结果) | + +### 2.1 查询边界 + +| 用户意图 | 数据来源 | Chatflow 路径 | 说明 | +| --- | --- | --- | --- | +| 发起一次新检核 | HXOPS Tool API | `run_check` → §3.8 → §3.9 → §3.10–§3.12 | Tool `run_file_check` 异步启动,不等待逐条判定 | +| 查询当前、最近或所有检核状态 | HXOPS Tool API | `check_status` → §3.14 到 §3.20 | 查询运行中 / 已完成 / 失败状态、统计、Excel 链接和知识库同步状态;“所有/全部”走批次列表 | +| 查询历史报告内容 | Dify 知识库 | `history_report_query` → §3.25 到 §3.27 | 只检索已同步入库的历史检核报告,不代表当前检核实时状态 | + +**关键约束**: + +- “最新一次检核状态 / 批次 ID 结果 / Excel 下载”必须走 HXOPS Tool API。 +- “历史异常 / 最近几次报告总结 / 某供应商或料号历史记录”必须走 Knowledge Retrieval。 +- 历史查询节点只负责查已入库报告;若最新检核尚未同步到知识库,应提示用户查询检核状态或稍后再查历史报告。 + +--- + +## 3. 按节点顺序配置(核心维护区) + +> 以下各节按画布执行顺序编号。**修改任一节点时,只改对应 §3.x 一节即可**,无需在文档其他章节查找碎片配置。 +> **Dify Tool 节点**固定出参为 `text`(String)、`json`(Array[Object] 或 Object)、`files`(本场景不用)。须紧接 **Code 解析响应** 节点,绑定 `tool_json` / `tool_text`,**不要**绑定 HTTP 的 `body`,也不要直接引用 Tool 节点复杂对象到 IF/LLM。 + +### 3.0 Dify 变量类型约定 + +- 下文 **Dify 类型** 指在 Dify 画布各节点 UI 中选择的数据类型(与 `docs/shipping_notice.md` §2.3.1 一致)。 +- **Code 节点**:入参变量名须与 `def main(...)` 参数名 **完全一致**;在 **输出变量** 页为 `return` 每个 key 声明类型。 +- **未执行分支**上的上游出参为空;本手册不建议把不同 Tool 分支强行汇入同一 Code,优先复制同配置节点分别接线。 +- 下游引用:`{{#节点名.变量名#}}`;IF 条件中 Boolean 与 `true` / `false` 比较(勿加引号)。 + +**本 Chatflow 常用 Dify 类型** + +| Dify 类型 | 用途 | +| --- | --- | +| **String** | 文本、JSON 字符串(`run_json` / `runs_json`)、ID、错误码 | +| **Boolean** | `ok`、各类是否判断 | +| **Number** | `confidence`(意图识别) | +| **Secret** | 历史 HTTP 方案曾在 Start 使用 `hxops_tool_api_token`;**当前 Tool 方案由 OpenAPI 工具 Credential 托管,Start 勿配** | +| **Array[Object]** | Tool 节点 `json` 出参;Knowledge Retrieval 检索片段列表(§3.25) | + +#### 3.0.1 Code 节点入参 / 出参总表 + +**Tool 响应解析共用 helper**(各 Code 节点可复制到 `main` 上方): + +```python +import json + +def _load_tool_json(tool_json, tool_text): + if isinstance(tool_json, list) and tool_json: + first = tool_json[0] + if isinstance(first, dict): + return first + if isinstance(tool_json, dict): + return tool_json + if isinstance(tool_text, str) and tool_text.strip(): + try: + data = json.loads(tool_text) + if isinstance(data, list) and data: + return data[0] if isinstance(data[0], dict) else {} + return data if isinstance(data, dict) else {} + except Exception: + return {} + return {} +``` + +| 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) | +| --- | --- | --- | +| `解析启动检核响应` | `tool_json` · **Array[Object]** 或 **Object** · 是 · `Tool:启动检核.json`;`tool_text` · **String** · 否 · 同上 `.text` | `ok` · **Boolean**;`error_code` / `message` / `run_id` / `run_no` / `run_status` / `task_name` / `started_at` · **String** | +| `提取查询参数` | `user_query` / `intent_run_id` / `intent_task_id` / `task_id` · **String** · `user_query` 与 `task_id` 是,其余否 · 见 §3.14 | `query_mode` · **String** · `by_run_id`/`latest_by_task`/`all_runs`/`missing`;`run_id` / `task_id` · **String** | +| `解析指定检核查询响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询指定检核.json` / `.text` | `ok` · **Boolean**;`error_code` / `message` · **String**;`run_json` · **String** | +| `解析最近检核查询响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询最近检核.json` / `.text` | 同上 | +| `解析所有检核批次响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询所有检核批次.json` / `.text` | `ok` · **Boolean**;`error_code` / `message` / `runs_json` / `count` · **String** | + +#### 3.0.2 LLM 节点输入变量配置方式 + +LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输入变量”是在 **Prompt 编辑器中插入上游变量**形成的。 + +配置步骤: + +1. 打开对应 LLM 节点。 +2. 在 **System Prompt** 或 **User Prompt** 中点击变量选择器,选择上游节点输出变量。 +3. Dify 会插入 `{{#节点名.变量名#}}` 形式的引用。 +4. 本手册各 LLM 小节中的“输入变量”表,表示这些变量必须在 Prompt 中被引用或通过节点上下文绑定;不是要求额外创建同名表单字段。 +5. 若该 LLM 节点开启结构化输出,还需要在节点的 **输出变量 / Structured Output** 中声明返回字段。 + +示例:`生成指定检核结果说明` 的 Prompt 中应引用: + +```text +用户问题: +{{#用户输入.query#}} + +检核批次 JSON: +{{#解析指定检核查询响应.run_json#}} +``` + +示例:`意图识别` 的 Prompt 中应引用: + +```text +用户问题: +{{#用户输入.query#}} + +文件检核任务 ID: +{{#用户输入.task_id#}} +``` + +> 注意:不要使用 `{{节点名.变量名}}`,必须使用 `{{#节点名.变量名#}}`。 + +#### 3.0.3 Knowledge / LLM 历史查询节点入参 / 出参总表 + +| 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) | +| --- | --- | --- | +| `检索历史检核报告` | `query` · **String** · 是 · `用户输入.query` | `result` · **Array[Object]**(或 Dify 版本的 `documents` / `content`) | +| `生成历史报告回答` | Prompt 引用 · `用户输入.query`;`检索历史检核报告.result`(或 Dify 实际出参名) | `text` · **String** | + +### 3.1 用户输入 + +> Dify 画布中 Start 节点**名称**设为 `用户输入`;下游引用格式为 `用户输入.<变量名>` 或 `{{#用户输入.<变量名>#}}`。 + +| 项 | 配置 | +| --- | --- | +| 类型 | Start | +| 节点名 | `用户输入` | +| 用户输入 | **开启** | +| 文件上传 | 关闭(文件检核不依赖对话附件) | +| 下一节点 | [§3.2 LLM:意图识别](#32-llm意图识别) | + +**系统传出**(Start 开启用户输入后自动可用) + +| 变量名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `sys.query` | String | 用户当轮话术 | +| `sys.conversation_id` | String | 会话 ID | + +**输入变量**(在 `用户输入` 节点「变量」页配置;`query` / `conversation_id` 绑定系统变量) + +| 变量名 | Dify 类型 | 必填 | 绑定 / 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `query` | String | 是 | `sys.query` | 用户话术 | +| `task_id` | String | 是 | HXOPS 注入或 Dify 直连调试手工填 | 检核任务 ID(`ScheduleTask.id`) | +| `conversation_id` | String | 否 | `sys.conversation_id` | 可选,传给 `run_file_check` | + +**传出(供下游引用)**:`用户输入.query` / `task_id` / `conversation_id` · String。 + +**无效变量(勿在 Start 配置、勿在 Prompt/IF/Tool 引用)** + +| 无效引用 | 原因 | +| --- | --- | +| `hxops_session_id` / `hxops_turn_id` | 由 HXOPS 内存注册表 + Tool API 推断,不必出现在 Dify | +| `用户输入.HXOPS_TOOLS_API_BASE` / `hxops_tool_api_token` | OpenAPI 工具已托管 Base URL 与 Bearer token | +| `用户输入.default_task_id` / `default_task_no` | 任务选择分支已移除 | +| `选择检核任务.*` / `解析检核任务列表响应.*` / `查询检核任务列表.*` | 历史任务选择分支,当前编排不存在 | +| `*.body`(HTTP 节点出参) | 已改用 Tool 节点的 `json` / `text` | +| `意图识别.task_no` | 意图结构化输出已不含 `task_no` | +| LLM 节点的 `user_query` / `retrieval_result` 入参名 | LLM 无 Code 式入参;仅在 Prompt 中引用 `用户输入.query` 等 | + +--- + +### 3.2 LLM:意图识别 + +**上游**:用户输入 + +**Prompt 引用变量**(在 Prompt 中插入,见 §3.0.2) + +| Dify 引用 | 说明 | +| --- | --- | +| `{{#用户输入.query#}}` | 用户当轮话术 | +| `{{#用户输入.task_id#}}` | 当前 Agent 绑定的检核任务 ID | + +**结构化输出**(LLM 节点开启 JSON / 结构化输出) + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `intent` | String | `run_check` / `check_status` / `history_report_query` / `explain_capability` / `other` | +| `task_id` | String | 用户话术中抽取的任务 ID;无则 `""`(通常用 Start 的 `task_id` 即可) | +| `run_id` | String | 检核批次 ID,无则 `""` | +| `confidence` | Number | 0–1 | + +**关键配置** + +| 配置项 | 值 | +| --- | --- | +| 输出格式 | 开启 JSON / Structured Output | +| `intent` / `task_id` / `run_id` 类型 | String | +| `confidence` 类型 | Number | + +> 如果没有开启结构化输出,LLM 可能只返回一段 JSON 文本,IF 节点拿不到 `意图识别.intent`,会直接进入兜底分支。 + +**System Prompt** + +```text +你是 文件检核助手的意图识别器。 +你的任务只有一个:把用户输入分类为固定 intent,并抽取 ID。 +请只返回 JSON,不要输出解释,不要用 markdown 代码块。 + +可选 intent: +- run_check:用户想发起 文件检核 +- check_status:用户想查询检核进度或结果 +- history_report_query:用户想查询历史检核报告、历史异常、供应商/料号历史记录或总结已入库报告 +- explain_capability:用户询问你能做什么 +- other:其他问题 + +优先级规则(必须按顺序判断): +1. 只要用户表达“现在要执行/启动/运行/开始/发起/跑一下/检核一下(文件)”,intent 必须是 run_check。 +2. 用户输入为“执行 文件检核”“启动 文件检核”“运行 文件检核”“开始 文件检核”“跑一下检核”“文件检核”时,intent 必须是 run_check,不要返回 other。 +3. 用户询问“状态/进度/检核批次 ID/run_id/下载 Excel/本次结果/最新一次结果/最近一次结果”时,intent 是 check_status。 +4. 用户询问“历史/上周/最近几次/某供应商/某料号/总结报告/历史异常/已入库报告”,且不是查询当前批次状态时,intent 是 history_report_query。 +5. 用户询问“你能做什么/有什么功能/怎么用”时,intent 是 explain_capability。 +6. 只有完全与 文件检核无关的问题,才允许 intent=other。 +7. 从用户话术中提取 task_id(检核任务 ID)、run_id(检核批次 ID,数字)。 +8. 如果用户说“最新一次/最近一次”且指执行状态或批次结果 → check_status;如果用户说“最近几次/历史报告/总结” → history_report_query。 + +强制示例: +- 用户输入:执行 文件检核 + 返回:{"intent":"run_check","task_id":"","run_id":"","confidence":0.99} +- 用户输入:文件检核 + 返回:{"intent":"run_check","task_id":"","run_id":"","confidence":0.95} +- 用户输入:启动 ID 12 的 文件检核 + 返回:{"intent":"run_check","task_id":"12","run_id":"","confidence":0.99} +- 用户输入:查询最新一次 文件检核结果 + 返回:{"intent":"check_status","task_id":"","run_id":"","confidence":0.95} +- 用户输入:上周有哪些不合格项 + 返回:{"intent":"history_report_query","task_id":"","run_id":"","confidence":0.95} + +返回格式: +{ + "intent": "run_check", + "task_id": "", + "run_id": "", + "confidence": 0.95 +} +``` + +**User Prompt** + +```text +用户问题: +{{#用户输入.query#}} + +文件检核任务 ID: +{{#用户输入.task_id#}} +``` + +**下游**:→ [§3.3 IF:意图分类](#33-if意图分类) + +--- + +### 3.3 IF:意图分类 + +**上游**:LLM 意图识别 + +**判定变量**:`意图识别.intent` · **String** + +| 条件 | 下一节点 | +| --- | --- | +| `意图识别.intent == "run_check"` | [§3.8 Tool:异步启动检核](#38-tool异步启动检核) | +| `意图识别.intent == "check_status"` | [§3.14 Code:提取查询参数](#314-code提取查询参数) | +| `意图识别.intent == "history_report_query"` | [§3.25 Knowledge Retrieval:检索历史检核报告](#325-knowledge-retrieval检索历史检核报告) | +| `意图识别.intent == "explain_capability"` | [§3.22 Answer:能力说明](#322-answer能力说明) | +| 默认 | [§3.23 Answer:兜底引导](#323-answer兜底引导) | + +--- + +### 3.8 Tool:异步启动检核 + +**上游**:IF 意图分类(`run_check` 分支) + +**工具**:OpenAPI action `run_file_check`(节点名建议 `Tool:启动检核`) + +**参数绑定** + +| 参数 | 类型 | 绑定 / 固定值 | +| --- | --- | --- | +| `task_id` | Number | `用户输入.task_id` | +| `trigger_source` | String | 固定 `dify_chatflow` | +| `conversation_id` | String | `用户输入.conversation_id`(可选) | +| `user_message` | String | `用户输入.query`(**必填**,用于 turn 注册表匹配) | + +> **不必**绑定 `hxops_session_id` / `hxops_turn_id`。HXOPS 在调用 Dify 前已登记本轮 turn;Tool API 通过 `user_message` 与注册表推断绑定(见 `chat_turn_registry.infer_bind_context_for_run_request`)。 +> **`task_no` 勿填**:OpenAPI 已移除该入参;若 Dify 仍显示,请重新 URL 导入 OpenAPI(§1.4)后删除节点上的 `task_no` 绑定。 + +**Tool 节点出参**(Dify 固定) + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `json` | Array[Object] | Tool API JSON 响应,Code 取首元素 | +| `text` | String | 文本兜底,Code 在 `json` 为空时 `json.loads` | +| `files` | Array[File] | 本场景不用 | + +**注意** + +- 已有检核进行中时 API 仍返回 **200**,body 为 `ok=false`、`error_code=check_running`,Code/IF 按业务字段分支。 +- 相关错误码见 [附录 B](#附录-b错误码总表):`task_id_required`、`task_not_found`、`check_running`。 + +**下游**:→ [§3.9 Code:解析启动检核响应](#39-code解析启动检核响应) + +--- + +### 3.9 Code:解析启动检核响应 + +**上游**:Tool 启动检核 + +**输入变量** + +| 变量名 | Dify 类型 | 必填 | 绑定来源 | +| --- | --- | --- | --- | +| `tool_json` | Array[Object] 或 Object | 是 | `Tool:启动检核.json` | +| `tool_text` | String | 否 | `Tool:启动检核.text` | + +**输出变量** + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `ok` | Boolean | API `ok` 字段 | +| `error_code` | String | 如 `check_running` / `task_not_found` | +| `message` | String | 提示或错误文案 | +| `run_id` | String | 检核批次 ID | +| `run_no` | String | 检核批次编号 | +| `run_status` | String | `running` / `success` / `failed` 等 | +| `task_name` | String | 检核任务名称 | +| `started_at` | String | ISO 时间字符串 | + +**完整 Python 代码** + +```python +import json + +def _load_tool_json(tool_json, tool_text): + if isinstance(tool_json, list) and tool_json: + first = tool_json[0] + if isinstance(first, dict): + return first + if isinstance(tool_json, dict): + return tool_json + if isinstance(tool_text, str) and tool_text.strip(): + try: + data = json.loads(tool_text) + if isinstance(data, list) and data: + return data[0] if isinstance(data[0], dict) else {} + return data if isinstance(data, dict) else {} + except Exception: + return {} + return {} + +def main(tool_json, tool_text) -> dict: + empty = { + "ok": False, "error_code": "invalid_response", "message": "", + "run_id": "", "run_no": "", "run_status": "", "task_name": "", "started_at": "", + } + data = _load_tool_json(tool_json, tool_text) + if not data: + empty["message"] = "无 Tool 响应" + return empty + run = data.get("run") or {} + return { + "ok": bool(data.get("ok")), + "error_code": str(data.get("error_code") or ""), + "message": str(data.get("message") or ""), + "run_id": str(run.get("run_id") or ""), + "run_no": str(run.get("run_no") or ""), + "run_status": str(run.get("status") or ""), + "task_name": str(run.get("task_name") or run.get("schedule_name") or ""), + "started_at": str(run.get("started_at") or ""), + } +``` + +**下游**:→ [§3.10 IF:启动结果分支](#310-if启动结果分支) + +**HXOPS 进度绑定(自动)**:Tool 启动检核成功或 `check_running` 时,HXOPS 记录 session + user_message;同轮 `message_end` 落 `ChatLog` 时写入 `run_id`。Dify **不必**在 Answer 输出 `tool_run_id`。 + +--- + +### 3.10 IF:启动结果分支 + +**上游**:Code 解析启动检核响应 + +**判定变量**:`解析启动检核响应.ok` · **Boolean**;`解析启动检核响应.error_code` · **String** + +| 条件 | 下一节点 | +| --- | --- | +| `解析启动检核响应.ok == true` | [§3.11 Answer:检核已启动](#311-answer检核已启动) | +| `解析启动检核响应.error_code == "check_running"` | [§3.12 Answer:检核进行中](#312-answer检核进行中) | +| 默认 | [§3.24 Answer:错误兜底](#324-answer错误兜底) | + +--- + +### 3.11 Answer:检核已启动 + +**上游**:IF 启动结果分支(`ok == true`) + +**引用变量**(均为 **String**):`解析启动检核响应.task_name` / `run_no` / `run_id` / `run_status` / `started_at` + +**回复模板** + +```text +已启动 文件检核:{{#解析启动检核响应.task_name#}} + +检核批次编号:{{#解析启动检核响应.run_no#}} +检核批次 ID:{{#解析启动检核响应.run_id#}} +当前状态:{{#解析启动检核响应.run_status#}} +启动时间:{{#解析启动检核响应.started_at#}} + +检核在后台异步执行。稍后你可以问: +「查询检核批次 ID {{#解析启动检核响应.run_id#}} 的结果」。 +``` + +--- + +### 3.12 Answer:检核进行中 + +**上游**:IF 启动结果分支(`error_code == "check_running"`) + +**引用变量**(均为 **String**):`解析启动检核响应.run_no` / `run_id` / `run_status` + +**回复模板** + +```text +该检核任务正在执行中,无法重复启动。 + +检核批次编号:{{#解析启动检核响应.run_no#}} +检核批次 ID:{{#解析启动检核响应.run_id#}} +当前状态:{{#解析启动检核响应.run_status#}} + +请稍后再查询结果,可以说: +「查询检核批次 ID {{#解析启动检核响应.run_id#}} 的结果」。 +``` + +--- + +### 3.14 Code:提取查询参数 + +**上游**:IF 意图分类(`check_status` 分支) + +**输入变量** + +| 变量名 | Dify 类型 | 必填 | 绑定来源 | +| --- | --- | --- | --- | +| `user_query` | String | 是 | `用户输入.query` | +| `intent_run_id` | String | 否 | `意图识别.run_id` | +| `intent_task_id` | String | 否 | `意图识别.task_id` | +| `task_id` | String | 是 | `用户输入.task_id` | + +**输出变量** + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `query_mode` | String | `by_run_id` / `latest_by_task` / `all_runs` / `missing` | +| `run_id` | String | 检核批次 ID;非 by_run_id 时为 `""` | +| `task_id` | String | 检核任务 ID | + +**完整 Python 代码** + +```python +import re + +def main(user_query, intent_run_id, intent_task_id, task_id) -> dict: + q = str(user_query or "") + run_id = str(intent_run_id or "").strip() + + all_keywords = ["所有", "全部", "全量", "列表", "历史记录", "执行记录", "所有文件检核结果", "全部文件检核结果", "all"] + if any(k in q for k in all_keywords): + tid = str(intent_task_id or task_id or "").strip() + return {"query_mode": "all_runs", "run_id": "", "task_id": tid} + + if not run_id: + m = re.search(r'(?:批次\s*ID|run[_\s-]*id|run_id)\s*[::]?\s*(\d+)', q, re.I) + if m: + run_id = m.group(1) + else: + m = re.search(r'查询\s*(\d+)\s*的', q) + if m: + run_id = m.group(1) + + if run_id: + return {"query_mode": "by_run_id", "run_id": run_id, "task_id": ""} + + latest_keywords = ["最新", "最近", "上一次", "上次", "latest"] + if any(k in q for k in latest_keywords): + tid = str(intent_task_id or task_id or "").strip() + if tid: + return {"query_mode": "latest_by_task", "run_id": "", "task_id": tid} + + tid = str(intent_task_id or task_id or "").strip() + if tid: + return {"query_mode": "latest_by_task", "run_id": "", "task_id": tid} + + return {"query_mode": "missing", "run_id": "", "task_id": ""} +``` + +**下游**:→ [§3.15 IF:查询方式](#315-if查询方式) + +--- + +### 3.15 IF:查询方式 + +**上游**:Code 提取查询参数 + +**判定变量**:`提取查询参数.query_mode` · **String** + +| 条件 | 下一节点 | +| --- | --- | +| `提取查询参数.query_mode == "by_run_id"` | [§3.16 Tool:查询指定检核](#316-tool查询指定检核) | +| `提取查询参数.query_mode == "latest_by_task"` | [§3.17 Tool:查询最近检核](#317-tool查询最近检核) | +| `提取查询参数.query_mode == "all_runs"` | [§3.17A Tool:查询所有检核批次](#317a-tool查询所有检核批次) | +| 默认 | [§3.21 Answer:引导提供查询条件](#321-answer引导提供查询条件) | + +--- + +### 3.16 Tool:查询指定检核 + +**上游**:IF 查询方式(`by_run_id` 分支) + +**工具**:`get_file_check_run`(节点名建议 `Tool:查询指定检核`) + +| 参数 | 类型 | 绑定 | +| --- | --- | --- | +| `run_id` | Number | `提取查询参数.run_id` | + +**下游**:→ [§3.18.1 Code:解析指定检核查询响应](#318-code解析检核查询响应两个节点) + +--- + +### 3.17 Tool:查询最近检核 + +**上游**:IF 查询方式(`latest_by_task` 分支) + +**工具**:`get_latest_file_check_run`(节点名建议 `Tool:查询最近检核`) + +| 参数 | 类型 | 绑定 | +| --- | --- | --- | +| `task_id` | Number | `提取查询参数.task_id` | + +**下游**:→ [§3.18.2 Code:解析最近检核查询响应](#318-code解析检核查询响应两个节点) + +--- + +### 3.17A Tool:查询所有检核批次 + +**上游**:IF 查询方式(`all_runs` 分支) + +**工具**:`list_file_check_runs`(节点名建议 `Tool:查询所有检核批次`) + +| 参数 | 类型 | 绑定 / 固定值 | +| --- | --- | --- | +| `task_id` | Number | `提取查询参数.task_id` | +| `limit` | Number | 固定 `50` | + +**下游**:→ [§3.18.3 Code:解析所有检核批次响应](#3183-code解析所有检核批次响应) + +--- + +### 3.18 Code:解析检核查询响应(两个节点) + +> 画布中不要把三路 Tool 强行汇入同一个 Code 节点。指定/最近复制同一段解析逻辑为两个 Code 节点;所有批次使用 §3.18.3。 + +#### 3.18.1 Code:解析指定检核查询响应 + +**上游**:Tool 查询指定检核 + +**输入变量** + +| 变量名 | Dify 类型 | 必填 | 绑定来源 | +| --- | --- | --- | --- | +| `tool_json` | Array[Object] 或 Object | 是 | `Tool:查询指定检核.json` | +| `tool_text` | String | 否 | `Tool:查询指定检核.text` | + +#### 3.18.2 Code:解析最近检核查询响应 + +**上游**:Tool 查询最近检核 + +**输入变量** + +| 变量名 | Dify 类型 | 必填 | 绑定来源 | +| --- | --- | --- | --- | +| `tool_json` | Array[Object] 或 Object | 是 | `Tool:查询最近检核.json` | +| `tool_text` | String | 否 | `Tool:查询最近检核.text` | + +**输出变量**(§3.18.1 / §3.18.2 相同) + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `ok` | Boolean | API `ok` 字段 | +| `error_code` | String | 如 `run_not_found` | +| `message` | String | 错误或提示文案 | +| `run_json` | String | `run` 对象 JSON 字符串,供 §3.19 LLM 解读 | + +**完整 Python 代码**(两个 Code 节点共用) + +```python +import json + +def _load_tool_json(tool_json, tool_text): + if isinstance(tool_json, list) and tool_json: + first = tool_json[0] + if isinstance(first, dict): + return first + if isinstance(tool_json, dict): + return tool_json + if isinstance(tool_text, str) and tool_text.strip(): + try: + data = json.loads(tool_text) + if isinstance(data, list) and data: + return data[0] if isinstance(data[0], dict) else {} + return data if isinstance(data, dict) else {} + except Exception: + return {} + return {} + +def main(tool_json, tool_text) -> dict: + empty = {"ok": False, "error_code": "invalid_response", "message": "", "run_json": "{}"} + data = _load_tool_json(tool_json, tool_text) + if not data: + empty["message"] = "无 Tool 响应" + return empty + run = data.get("run") or {} + return { + "ok": bool(data.get("ok")), + "error_code": str(data.get("error_code") or ""), + "message": str(data.get("message") or ""), + "run_json": json.dumps(run, ensure_ascii=False), + } +``` + +#### 3.18.3 Code:解析所有检核批次响应 + +**上游**:Tool 查询所有检核批次 + +**输入变量** + +| 变量名 | Dify 类型 | 必填 | 绑定来源 | +| --- | --- | --- | --- | +| `tool_json` | Array[Object] 或 Object | 是 | `Tool:查询所有检核批次.json` | +| `tool_text` | String | 否 | `Tool:查询所有检核批次.text` | + +**输出变量** + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `ok` | Boolean | API `ok` 字段 | +| `error_code` | String | 错误码 | +| `message` | String | 错误或提示文案 | +| `runs_json` | String | `runs` 数组 JSON 字符串 | +| `count` | String | 返回批次数 | + +**完整 Python 代码** + +```python +import json + +def _load_tool_json(tool_json, tool_text): + if isinstance(tool_json, list) and tool_json: + first = tool_json[0] + if isinstance(first, dict): + return first + if isinstance(tool_json, dict): + return tool_json + if isinstance(tool_text, str) and tool_text.strip(): + try: + data = json.loads(tool_text) + if isinstance(data, list) and data: + return data[0] if isinstance(data[0], dict) else {} + return data if isinstance(data, dict) else {} + except Exception: + return {} + return {} + +def main(tool_json, tool_text) -> dict: + empty = {"ok": False, "error_code": "invalid_response", "message": "", "runs_json": "[]", "count": "0"} + data = _load_tool_json(tool_json, tool_text) + if not data: + empty["message"] = "无 Tool 响应" + return empty + runs = data.get("runs") or [] + if not isinstance(runs, list): + runs = [] + return { + "ok": bool(data.get("ok")), + "error_code": str(data.get("error_code") or ""), + "message": str(data.get("message") or ""), + "runs_json": json.dumps(runs, ensure_ascii=False), + "count": str(data.get("count") if data.get("count") is not None else len(runs)), + } +``` + +**下游**:→ `Answer:返回所有检核批次` + +#### 3.18.4 Answer:返回所有检核批次 + +**模板** + +```text +共查询到 {{#解析所有检核批次响应.count#}} 条 文件检核执行记录: + +{{#解析所有检核批次响应.runs_json#}} + +如需查看某一笔详情,请继续问: +“查询检核批次 ID xxx 的结果”。 +``` + +**下游**: + +- `解析指定检核查询响应` → [§3.19 LLM:生成指定检核结果说明](#319-llm生成结果说明两个节点) +- `解析最近检核查询响应` → [§3.19 LLM:生成最近检核结果说明](#319-llm生成结果说明两个节点) + +--- + +### 3.19 LLM:生成结果说明(两个节点) + +> 画布中建立两个 LLM 节点,Prompt 完全相同,仅 Prompt 中 `run_json` 来源不同。 + +#### 3.19.1 LLM:生成指定检核结果说明 + +**上游**:Code 解析指定检核查询响应 + +**Prompt 引用变量** + +| Dify 引用 | 说明 | +| --- | --- | +| `{{#用户输入.query#}}` | 用户问题 | +| `{{#解析指定检核查询响应.run_json#}}` | 检核批次 JSON | + +#### 3.19.2 LLM:生成最近检核结果说明 + +**上游**:Code 解析最近检核查询响应 + +**Prompt 引用变量** + +| Dify 引用 | 说明 | +| --- | --- | +| `{{#用户输入.query#}}` | 用户问题 | +| `{{#解析最近检核查询响应.run_json#}}` | 检核批次 JSON | + +**输出变量** + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `text` | String | 自然语言检核结果说明(绑到 §3.20 Answer) | + +**System Prompt** + +```text +你是 文件检核助手。 +请根据 HXOPS 工具返回的检核结果回复用户,使用简洁中文。 + +输入 `run_json` 为检核批次 JSON 字符串;若为空对象或 ok=false,按 message / error_code 说明失败。 + +规则: +1. 不要自行判断物料是否合格。 +2. 只能解释 run_json 中的 status、统计、error_message、excel、knowledge_base。 +3. status=running:告诉用户仍在执行,建议稍后再查。 +4. status=success:说明已完成,列出 total/success/failed/skipped。 +5. status=partial_failed:提醒部分失败,建议下载 Excel 看明细。 +6. status=failed:说明失败原因(error_message)。 +7. 若 excel.download_url 存在,必须原样给出下载链接。 +8. 若 knowledge_base.enabled=true,简要说明 sync_status;若 failed 说明同步失败但不影响查结果。 +9. 不要编造没有返回的信息。 +10. 不要输出 token 或内部配置。 +``` + +**User Prompt** + +`生成指定检核结果说明` 使用: + +```text +用户问题: +{{#用户输入.query#}} + +检核批次 JSON: +{{#解析指定检核查询响应.run_json#}} +``` + +`生成最近检核结果说明` 使用: + +```text +用户问题: +{{#用户输入.query#}} + +检核批次 JSON: +{{#解析最近检核查询响应.run_json#}} +``` + +**下游**: + +- `生成指定检核结果说明` → [§3.20 Answer:返回指定检核结果](#320-answer返回查询结果两个节点) +- `生成最近检核结果说明` → [§3.20 Answer:返回最近检核结果](#320-answer返回查询结果两个节点) + +--- + +### 3.20 Answer:返回查询结果(两个节点) + +> 画布中建立两个 Answer 节点,模板相同,仅引用变量不同。 + +#### 3.20.1 Answer:返回指定检核结果 + +**上游**:LLM 生成指定检核结果说明 + +**引用变量**:`生成指定检核结果说明.text` · **String** + +**回复模板** + +```text +{{#生成指定检核结果说明.text#}} +``` + +#### 3.20.2 Answer:返回最近检核结果 + +**上游**:LLM 生成最近检核结果说明 + +**引用变量**:`生成最近检核结果说明.text` · **String** + +**回复模板** + +```text +{{#生成最近检核结果说明.text#}} +``` + +> 若 Dify 版本将 LLM 输出字段名不同,绑定该节点的文本输出即可;**不要**在此节点重复编写判定逻辑。 + +--- + +### 3.21 Answer:引导提供查询条件 + +**上游**:IF 查询方式(`missing` 分支) + +**回复模板** + +```text +请提供要查询的检核信息,例如: + +- 「查询检核批次 ID 88 的结果」 +- 「查询最新一次 文件检核结果」 +- 「查询 ID 12 任务最近一次检核」 +``` + +--- + +### 3.22 Answer:能力说明 + +**上游**:IF 意图分类(`explain_capability` 分支) + +**回复模板** + +```text +我是 文件检核助手,可以帮你: + +1. **发起检核** — 对后台配置的检核任务执行一批判定与写回 +2. **查询进度** — 查看检核批次状态、成功/失败统计 +3. **获取报告** — 提供检核结果 Excel 下载链接 +4. **知识库同步** — 告知检核报告是否已写入知识库 +5. **历史查询** — 基于已入库检核报告查询历史异常、供应商、料号或报告总结 + +你可以说: +- 「执行 文件检核」 +- 「查询检核批次 ID 88 的结果」 +- 「查询最新一次检核结果」 +- 「上周有哪些不合格项」 +- 「总结最近几次 文件检核异常」 +``` + +--- + +### 3.23 Answer:兜底引导 + +**上游**:IF 意图分类(默认分支) + +**回复模板** + +```text +抱歉,我没有理解你的需求。 + +我是 文件检核助手,可以帮你发起检核、查询检核结果、下载报告,也可以基于已入库的历史检核报告做查询和总结。 + +你可以说「你能做什么」了解详细功能,或直接说「执行 文件检核」「查询最新检核结果」「上周有哪些不合格项」。 +``` + +--- + +### 3.24 Answer:错误兜底 + +**上游**:IF 启动结果分支(非 `ok`、非 `check_running`) + +**引用变量**:`解析启动检核响应.message` · **String**;`解析启动检核响应.error_code` · **String** + +**回复模板** + +```text +检核启动失败:{{#解析启动检核响应.message#}} + +错误码:{{#解析启动检核响应.error_code#}} + +若问题持续,请联系管理员检查检核任务配置或 Tool API 鉴权。 +``` + +常见 `error_code` 见 [附录 B](#附录-b错误码总表)。 + +--- + +### 3.25 Knowledge Retrieval:检索历史检核报告 + +**上游**:IF 意图分类(`history_report_query` 分支) + +**用途**:从已同步到知识库的 文件检核报告中检索历史资料,用于回答“历史异常、供应商、料号、最近几次报告总结”等问题。该节点不用于查询当前检核执行状态。 + +**知识库选择** + +| 配置项 | 建议 | +| --- | --- | +| 知识库 | 选择 文件检核报告同步的目标知识库或数据集 | +| Query | `{{#用户输入.query#}}` | +| Top K | `5` 到 `10` | +| Score threshold | 建议 `0.3` 到 `0.5`,按实际召回效果调整 | +| Metadata filter | 若 Dify 支持,过滤 `source_type = schedule_run`(与 hxops `kb_sync` 清洗任务 payload 一致) | + +**检索输入** + +| 变量名 | Dify 类型 | 绑定来源 | +| --- | --- | --- | +| `query` | String | `用户输入.query` | + +**检索输出** + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `result` / `documents` | Array / String | Dify 知识库检索结果,按实际节点出参绑定到 §3.26 | + +**重要约束** + +- 该节点只查**已入库历史报告**,不代表当前检核是否完成。 +- 若知识库同步状态仍为 `queued` / `cleaning` / `syncing`,历史检索可能暂时查不到最新报告。 +- 回答必须基于检索结果;检索不到时明确说明未找到历史记录。 + +**入库 metadata(hxops 已实现)** + +检核报告经 `kb_sync` 入库时,`KbJob.payload_json` 已包含: + +```json +{ + "source_type": "schedule_run", + "schedule_run_id": 88, + "run_no": "RUN202606090001", + "document_version_id": 123, + "auto_sync_dify": true +} +``` + +`KbDocument.source_type` 为 `schedule`;`title` 形如 `{任务名}_{run_no}`。Dify 同步后检索结果应能引用 `run_no` / 文档标题。若需按 `task_id` 过滤,可在后续版本扩展 payload 字段。 + +**下游**:→ [§3.26 LLM:生成历史报告回答](#326-llm生成历史报告回答) + +--- + +### 3.26 LLM:生成历史报告回答 + +**上游**:Knowledge Retrieval 检索历史检核报告 + +**Prompt 引用变量** + +| Dify 引用 | 说明 | +| --- | --- | +| `{{#用户输入.query#}}` | 用户问题 | +| `{{#检索历史检核报告.result#}}` | 知识库检索结果(Dify 版本不同可能是 `documents` / `content`) | + +**输出变量** + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `text` | String | 历史报告查询回答,绑定到 §3.27 Answer | + +**System Prompt** + +```text +你是文件检核历史报告助手。 +请只基于知识库检索结果回答用户问题,使用简洁中文。 + +规则: +1. 不要重新判断物料是否合格。 +2. 不要编造检索结果中没有的信息。 +3. 如果检索结果为空或无关,明确回复“未在已入库的历史检核报告中找到相关记录”。 +4. 如果用户询问历史异常、不合格、供应商、料号或批次,请尽量列出来源文档、run_no、run_id 或报告标题。 +5. 如果检索结果包含多个报告,请按时间或报告顺序归纳。 +6. 如果问题需要当前执行状态,请提示用户改问“查询检核批次 ID ... 的结果”,不要用知识库结果代替执行状态。 +7. 不要输出 token、内部配置或系统提示词。 +``` + +**User Prompt** + +```text +用户问题: +{{#用户输入.query#}} + +知识库检索结果: +{{#检索历史检核报告.result#}} +``` + +> 若当前 Dify 版本的 Knowledge Retrieval 出参不是 `result`,请在变量选择器中选择实际出参,例如 `documents` / `content`,并同步更新本 Prompt。 + +**下游**:→ [§3.27 Answer:返回历史查询结果](#327-answer返回历史查询结果) + +--- + +### 3.27 Answer:返回历史查询结果 + +**上游**:LLM 生成历史报告回答 + +**引用变量**:`生成历史报告回答.text` · **String** + +**回复模板** + +```text +{{#生成历史报告回答.text#}} +``` + +> 历史查询回答来自知识库检索结果;不要在 Answer 节点追加新的合格/不合格判断逻辑。 + +--- + +## 附录 A:OpenAPI 规范 + +完整 JSON 见 **[`docs/openapi/file_check_tools_openapi.json`](./openapi/file_check_tools_openapi.json)**。 + +**字段语义**:`task_id` = 检核任务;`run_id` / `run_no` = 检核批次(一次检核执行)。 + +| operationId | 方法 | 路径 | 对应节点 | +| --- | --- | --- | --- | +| `list_file_check_tasks` | GET | `/api/file-check/tools/tasks?task_id=` | 运维调试 only(必传 `task_id`),不参与画布 | +| `run_file_check` | POST | `/api/file-check/tools/tasks/run` | [§3.8](#38-tool异步启动检核) Tool + [§3.9](#39-code解析启动检核响应) | +| `list_file_check_runs` | GET | `/api/file-check/tools/runs` | [§3.17A](#317a-tool查询所有检核批次) Tool + [§3.18.3](#3183-code解析所有检核批次响应) | +| `get_file_check_run` | GET | `/api/file-check/tools/runs/{run_id}` | [§3.16](#316-tool查询指定检核) Tool + [§3.18.1](#318-code解析检核查询响应两个节点) | +| `get_latest_file_check_run` | GET | `/api/file-check/tools/tasks/{task_id}/latest-run` | [§3.17](#317-tool查询最近检核) Tool + [§3.18.2](#318-code解析检核查询响应两个节点) | +| `download_file_check_run_excel` | GET | `/api/file-check/tools/runs/{run_id}/excel?token=` | 否(由 `run.excel.download_url` 提供) | + +**Excel 下载**:查询检核接口返回的 `run.excel.download_url` 含短期 JWT(**600 秒**);[§3.19](#319-llm生成结果说明两个节点) 须原样输出该 URL。 + +--- + +## 附录 B:错误码总表 + +| error_code | HTTP 状态 | 场景 | 涉及节点 | +| --- | --- | --- | --- | +| `missing_auth` | 401/503 | 未配 token | 所有 Tool(OpenAPI 工具 Credential) | +| `invalid_auth` | 401 | token 错误 | 所有 Tool | +| `task_not_found` | 404 | 检核任务不存在 | [§3.9](#39-code解析启动检核响应)、[§3.18](#318-code解析检核查询响应两个节点) | +| `check_running` | 200 | 检核进行中 | [§3.9](#39-code解析启动检核响应) → [§3.12](#312-answer检核进行中) | +| `run_not_found` | 404 | 检核批次不存在 | [§3.18](#318-code解析检核查询响应两个节点) | +| `excel_not_ready` | 409 | 报告未生成 | 查询分支(LLM 说明时提及) | + +--- + +## 附录 C:发布验证用例 + +| 用户输入 | 预期路径(§3 节点) | +| --- | --- | +| `执行 文件检核` | §3.3 → §3.8 → §3.9 → §3.11 | +| 检核进行中再次启动 | §3.8 200 + `check_running` → §3.9 → §3.12 | +| `查询检核批次 ID 88 的结果` | §3.14 → §3.16 → §3.18 → §3.19 → §3.20 | +| `查询最新一次 文件检核结果` | §3.14 → §3.17 → §3.18 → §3.19 → §3.20 | +| `查询所有文件检核结果` | §3.14 → §3.17A → §3.18.3 → 返回所有检核批次 | +| `上周有哪些不合格项` | §3.25 → §3.26 → §3.27 | +| `总结最近几次 文件检核异常` | §3.25 → §3.26 → §3.27 | +| `查询某供应商历史 文件检核报告` | §3.25 → §3.26 → §3.27 | +| `查询最新一次 文件检核状态` | 必须走 §3.14 → §3.17,不走知识库检索 | +| `最近几次检核报告总结` | 必须走 §3.25 → §3.26 → §3.27,不调用启动或状态 Tool API | +| `你能做什么` | §3.22 | +| 无法识别意图 | §3.23 | + +--- + +## 附录 D:相关代码 + +| 文件 | 说明 | +| --- | --- | +| `backend/app/api/file_check_tools.py` | 文件检核 Tool API | +| `backend/app/services/file_check.py` | 文件检核 Dify Workflow 调用 | +| `backend/app/services/file_check_tools/progress_paths.py` | 进度轮询 URL 常量(由 schedule_task_id / run_id 推导) | +| `backend/app/services/file_check_tools/task_resolver.py` | Agent enrich、schedule_task_id 解析 | +| 检核报告知识库同步 | 检核完成后由 `kb_sync` 服务写入知识库 | +| `docs/openapi/file_check_tools_openapi.json` | OpenAPI 规范(导出产物) | +| `backend/app/services/file_check_tools/openapi_base.json` | OpenAPI 源模板 | +| `backend/scripts/export_file_check_openapi.py` | OpenAPI 导出脚本 | + +--- + +## 附录 E:HTTP 迁移与排错 + +> 旧版画布若仍使用 **HTTP Request** 调 Tool API,按下列步骤一次性迁到 **OpenAPI Tool 节点**(§3.8–§3.17A)。新搭建直接按 §3 配置即可。 + +### E.1 HTTP → Tool 替换对照 + +| 删除(HTTP) | 新建(Tool) | operationId | +| --- | --- | --- | +| HTTP 异步启动检核 | Tool:启动检核 | `run_file_check` | +| HTTP 查询指定检核 | Tool:查询指定检核 | `get_file_check_run` | +| HTTP 查询最近检核 | Tool:查询最近检核 | `get_latest_file_check_run` | +| HTTP 查询所有检核批次 | Tool:查询所有检核批次 | `list_file_check_runs` | + +- 删除 HTTP 的 URL、Headers、Body;Tool 只填业务参数,鉴权走 §1.5 Credential。 +- Code 入参由 `body` 改为 `tool_json` + `tool_text`(见 §3.0.1、§3.9、§3.18)。 +- Start 删除 `HXOPS_TOOLS_API_BASE`、`hxops_tool_api_token`。 + +### E.2 常见错误 + +| 错误 | 现象 | 处理 | +| --- | --- | --- | +| Credential 填 `Bearer xxx` | 后端收到双重 Bearer,鉴权失败 | Credential 只填 token 本身 | +| Start 仍传 token / base | 变量冗余、易泄露 | 删除 Start 中 base/token | +| Tool 节点手写 Authorization | 与 OpenAPI Credential 冲突 | 仅使用工具授权 | +| Answer 直接引用 Tool 出参 | 字段路径不稳定 | 经 Code 扁平化后再引用 | +| 指定/最近查询共用一个 Code | 分支汇入变量来源混乱 | 复制为两个 Code 节点 | +| 历史报告改走 Tool API | 无法回答「上周异常」类问题 | 历史仍走 §3.25 知识库 | +| OpenAPI Server URL 错误 | 工具调用超时 / 404 | 确认与 `HXOPS_TOOLS_API_BASE` 一致 | + +### E.3 迁移后画布检查 + +- [ ] 不存在调用 `/api/file-check/tools/*` 的 HTTP Request 节点 +- [ ] 不存在手写 `Authorization` Header +- [ ] Start 无 Tool API token / base URL +- [ ] 四个 Tool + 对应 Code 解析节点已接线 +- [ ] Answer / Prompt 使用 `{{#节点名.变量名#}}` 格式 +- [ ] [附录 C](#附录-c发布验证用例) 用例全部通过 diff --git a/docs/funclist.md b/docs/funclist.md index e3950914..b66363d5 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -16,14 +16,21 @@ ## 2. 详细功能拆分 -### RoHS 文件检核 +### 文件检核(通用域) | 功能项 | 状态 | 说明 | | --- | --- | --- | -| RoHSCheckService 判定入口 | 已实现 | 检核执行链路统一调用,内部复用现有 Dify Workflow | -| Chatflow 发起与查询检核 | 已实现 | Tool API:查检核任务、启动检核、查检核批次、查最近检核、Excel 报告链接 | -| RoHS Chatflow 编排手册 | 已文档化 | 见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md) | +| FileCheckService 判定入口 | 已实现 | 检核执行链路统一调用 Dify Workflow(RoHS / MSDS 等按排程绑定不同 Workflow) | +| 文件检核 Chatflow Tool API | 已实现 | `/api/file-check/tools/*`:启动检核、查批次、Excel 报告链接 | +| 文件检核 Chatflow 编排手册 | 已文档化 | 见 [docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md) | | 检核报告同步知识库 | 已实现 | 检核 success / partial_failed 且生成 Excel 后同步到所选知识库分组 | +| 多 Agent 共用 Chatflow | 已实现 | RoHS / MSDS 等 Agent 共用同一 Dify Chatflow,`task_id` 由 Agent extra_config 注入 | + +### RoHS 文件检核(实例) + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| RoHS 排程检核 | 已实现 | 首个文件检核类型实例,复用通用 file_check 域 | ### F-01 本人假期查询 diff --git a/docs/openapi/file_check_tools_openapi.json b/docs/openapi/file_check_tools_openapi.json new file mode 100644 index 00000000..af271eaf --- /dev/null +++ b/docs/openapi/file_check_tools_openapi.json @@ -0,0 +1,724 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "HXOPS File Check Tool API", + "description": "文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://192.168.36.108:5052", + "description": "HXOPS_TOOLS_API_BASE" + } + ], + "security": [ + { + "BearerAuth": [] + }, + { + "IntegrationKey": [] + } + ], + "paths": { + "/api/file-check/tools/tasks": { + "get": { + "operationId": "list_file_check_tasks", + "summary": "查询指定文件检核任务", + "tags": [ + "File Check" + ], + "parameters": [ + { + "name": "task_id", + "in": "query", + "required": true, + "schema": { + "type": "integer", + "example": 12 + }, + "description": "检核任务 ID(Agent 绑定的 schedule_task_id)" + } + ], + "responses": { + "200": { + "description": "成功", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListTasksResponse" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/TaskNotFound" + }, + "503": { + "$ref": "#/components/responses/MissingAuth" + } + } + } + }, + "/api/file-check/tools/tasks/run": { + "post": { + "operationId": "run_file_check", + "summary": "异步启动 文件检核", + "tags": [ + "File Check" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunCheckRequest" + } + } + } + }, + "responses": { + "200": { + "description": "启动成功;或已有 文件检核进行中,返回 ok=false/error_code=check_running", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/RunCheckSuccessResponse" + }, + { + "$ref": "#/components/schemas/CheckRunningResponse" + } + ] + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/TaskNotFound" + } + } + } + }, + "/api/file-check/tools/runs": { + "get": { + "operationId": "list_file_check_runs", + "summary": "查询 文件检核批次列表", + "tags": [ + "File Check" + ], + "parameters": [ + { + "name": "task_id", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "example": 12 + }, + "description": "可选;指定检核任务 ID 时只返回该任务批次" + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 20 + }, + "description": "返回条数,最大 100" + } + ], + "responses": { + "200": { + "description": "成功", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListRunsResponse" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/TaskNotFound" + } + } + } + }, + "/api/file-check/tools/runs/{run_id}": { + "get": { + "operationId": "get_file_check_run", + "summary": "查询指定检核批次", + "tags": [ + "File Check" + ], + "parameters": [ + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "example": 88 + } + } + ], + "responses": { + "200": { + "description": "成功", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetRunResponse" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/RunNotFound" + } + } + } + }, + "/api/file-check/tools/tasks/{task_id}/latest-run": { + "get": { + "operationId": "get_latest_file_check_run", + "summary": "查询检核任务最近一次检核", + "tags": [ + "File Check" + ], + "parameters": [ + { + "name": "task_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "example": 12 + } + } + ], + "responses": { + "200": { + "description": "成功", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetRunResponse" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/RunNotFound" + } + } + } + }, + "/api/file-check/tools/runs/{run_id}/excel": { + "get": { + "operationId": "download_file_check_run_excel", + "summary": "下载检核报告 Excel(短期签名 token)", + "tags": [ + "File Check" + ], + "security": [], + "parameters": [ + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "example": 88 + } + }, + { + "name": "token", + "in": "query", + "required": true, + "description": "由 get_file_check_run 返回的 excel.download_url 中的 JWT,有效期 600 秒", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Excel 文件流", + "content": { + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "409": { + "$ref": "#/components/responses/ExcelNotReady" + } + } + } + } + }, + "components": { + "securitySchemes": { + "BearerAuth": { + "type": "http", + "scheme": "bearer", + "description": "FILE_CHECK_TOOLS_API_KEY 或 INTEGRATION_API_KEY" + }, + "IntegrationKey": { + "type": "apiKey", + "in": "header", + "name": "X-Integration-Key", + "description": "与 Bearer 二选一" + } + }, + "schemas": { + "TaskSummary": { + "type": "object", + "properties": { + "task_id": { + "type": "integer", + "example": 12 + }, + "task_no": { + "type": "string", + "example": "CHK202606090001" + }, + "name": { + "type": "string", + "example": "文件自动检核" + }, + "enabled": { + "type": "boolean" + }, + "last_status": { + "type": "string", + "nullable": true, + "example": "success" + }, + "last_run_at": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "next_run_at": { + "type": "string", + "format": "date-time", + "nullable": true + } + } + }, + "RunExcel": { + "type": "object", + "properties": { + "file_name": { + "type": "string", + "nullable": true, + "example": "RUN202606090001.xlsx" + }, + "file_size": { + "type": "integer", + "nullable": true, + "example": 45678 + }, + "download_url": { + "type": "string", + "nullable": true, + "example": "https://your-hxops-host/api/file-check/tools/runs/88/excel?token=..." + } + } + }, + "RunKnowledgeBase": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "sync_status": { + "type": "string", + "nullable": true, + "enum": [ + "skipped", + "queued", + "cleaning", + "syncing", + "ready", + "success", + "failed" + ] + }, + "group_id": { + "type": "integer", + "nullable": true + }, + "document_id": { + "type": "integer", + "nullable": true + }, + "document_version_id": { + "type": "integer", + "nullable": true + }, + "sync_job_id": { + "type": "integer", + "nullable": true + }, + "error_message": { + "type": "string", + "nullable": true + } + } + }, + "RunDetail": { + "type": "object", + "properties": { + "run_id": { + "type": "integer", + "example": 88 + }, + "run_no": { + "type": "string", + "example": "RUN202606090001" + }, + "task_id": { + "type": "integer", + "example": 12 + }, + "task_name": { + "type": "string", + "example": "文件自动检核" + }, + "status": { + "type": "string", + "enum": [ + "running", + "success", + "partial_failed", + "failed", + "queued", + "cancelled" + ] + }, + "total_count": { + "type": "integer" + }, + "success_count": { + "type": "integer" + }, + "failed_count": { + "type": "integer" + }, + "skipped_count": { + "type": "integer" + }, + "started_at": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "finished_at": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "duration_ms": { + "type": "integer", + "nullable": true + }, + "error_message": { + "type": "string", + "nullable": true + }, + "excel": { + "$ref": "#/components/schemas/RunExcel" + }, + "knowledge_base": { + "$ref": "#/components/schemas/RunKnowledgeBase" + } + } + }, + "ListTasksResponse": { + "type": "object", + "required": [ + "ok", + "tasks" + ], + "properties": { + "ok": { + "type": "boolean", + "example": true + }, + "tasks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TaskSummary" + } + } + } + }, + "RunCheckRequest": { + "type": "object", + "properties": { + "task_id": { + "type": "integer", + "example": 12 + }, + "trigger_source": { + "type": "string", + "default": "dify_chatflow" + }, + "conversation_id": { + "type": "string", + "nullable": true + }, + "user_message": { + "type": "string", + "nullable": true + } + }, + "required": [ + "task_id" + ], + "description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配" + }, + "RunCheckSuccessResponse": { + "type": "object", + "required": [ + "ok", + "message", + "run" + ], + "properties": { + "ok": { + "type": "boolean", + "example": true + }, + "message": { + "type": "string", + "example": "检核已启动" + }, + "run": { + "$ref": "#/components/schemas/RunDetail" + } + } + }, + "CheckRunningResponse": { + "type": "object", + "required": [ + "ok", + "error_code", + "message", + "run" + ], + "properties": { + "ok": { + "type": "boolean", + "example": false + }, + "error_code": { + "type": "string", + "example": "check_running" + }, + "message": { + "type": "string", + "example": "该检核任务正在执行中,请稍后查询结果" + }, + "run": { + "$ref": "#/components/schemas/RunDetail" + } + } + }, + "GetRunResponse": { + "type": "object", + "required": [ + "ok", + "run" + ], + "properties": { + "ok": { + "type": "boolean", + "example": true + }, + "run": { + "$ref": "#/components/schemas/RunDetail" + } + } + }, + "ListRunsResponse": { + "type": "object", + "required": [ + "ok", + "runs", + "count" + ], + "properties": { + "ok": { + "type": "boolean", + "example": true + }, + "count": { + "type": "integer", + "example": 2 + }, + "runs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RunDetail" + } + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "ok", + "error_code", + "message" + ], + "properties": { + "ok": { + "type": "boolean", + "example": false + }, + "error_code": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + }, + "responses": { + "Unauthorized": { + "description": "鉴权失败", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "missing_auth": { + "value": { + "ok": false, + "error_code": "missing_auth", + "message": "missing_auth" + } + }, + "invalid_auth": { + "value": { + "ok": false, + "error_code": "invalid_auth", + "message": "invalid_auth" + } + } + } + } + } + }, + "MissingAuth": { + "description": "服务端未配置 FILE_CHECK_TOOLS_API_KEY / INTEGRATION_API_KEY", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "example": { + "ok": false, + "error_code": "missing_auth", + "message": "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured" + } + } + } + }, + "BadRequest": { + "description": "请求参数无效", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "example": { + "ok": false, + "error_code": "invalid_request", + "message": "invalid_request" + } + } + } + }, + "TaskNotFound": { + "description": "检核任务不存在", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "example": { + "ok": false, + "error_code": "task_not_found", + "message": "task_not_found" + } + } + } + }, + "RunNotFound": { + "description": "检核批次不存在", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "example": { + "ok": false, + "error_code": "run_not_found", + "message": "run_not_found" + } + } + } + }, + "ExcelNotReady": { + "description": "Excel 尚未生成", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "example": { + "ok": false, + "error_code": "excel_not_ready", + "message": "excel_not_ready" + } + } + } + } + } + } +} \ No newline at end of file diff --git a/docs/tec.md b/docs/tec.md index 4c1028c7..3b1a54c8 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -10,13 +10,13 @@ ## 2. 现有可复用能力 -### 2.x RoHS 文件检核可复用能力 +### 2.x 文件检核(file_check)可复用能力 -- **产品语义**:对外统一为 RoHS 文件检核(发起、实时查询、报告、知识库同步、历史报告检索);Tool API 使用 `/api/rohs-check/tools/tasks` 与 `task_id` / `task_no` 字段;历史查询走 Dify Knowledge Retrieval(绑定检核报告同步的 Dataset);对外基地址由环境变量 `HXOPS_TOOLS_API_BASE` 配置。 -- 通过 `RoHSCheckService.evaluate()` 包装现有 Dify Workflow 调用,保持 `dify_result / dify_message` 输出兼容。 -- 新增 `/api/rohs-check/tools/*` 显式 HTTP Tool API,供 Dify Chatflow 发起检核、查询检核结果并返回 Excel 报告短期签名链接。 -- Chatflow 完整编排、Dify 逐步配置与 OpenAPI 导入见 **[docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)**;OpenAPI 规范见 **[docs/openapi/rohs_check_tools_openapi.json](openapi/rohs_check_tools_openapi.json)**(`python backend/scripts/export_rohs_check_openapi.py` 重新生成)。 -- 复用知识库 `KbDocument / KbDocumentVersion / KbJob` 清洗与 Dify 同步链路,将检核报告 Excel 作为独立文档入库。 +- **产品语义**:对外统一为文件检核(RoHS / MSDS 等);Tool API 使用 `/api/file-check/tools/tasks` 与 `task_id` 字段;多 Agent 共用单套 Dify Chatflow,`task_id` 由 Agent `extra_config` 注入;历史查询按 `task_id` 分支走 Dify Knowledge Retrieval。 +- 通过 `FileCheckService.evaluate()` 调用排程绑定的 Dify Workflow,保持 `dify_result / dify_message` 输出兼容。 +- `/api/file-check/tools/*` 显式 HTTP Tool API,供 Chatflow 发起检核、查询结果并返回 Excel 短期签名链接。 +- Chatflow 编排见 **[docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md)**;OpenAPI 见 **[docs/openapi/file_check_tools_openapi.json](openapi/file_check_tools_openapi.json)**(`python backend/scripts/export_file_check_openapi.py`)。 +- 复用知识库清洗与 Dify 同步链路,将检核报告 Excel 入库。 ### 2.1 已有聊天路由能力 diff --git a/frontend/src/features/chat/composables/useToolRunProgress.ts b/frontend/src/features/chat/composables/useToolRunProgress.ts index 6df74c69..b54c615e 100644 --- a/frontend/src/features/chat/composables/useToolRunProgress.ts +++ b/frontend/src/features/chat/composables/useToolRunProgress.ts @@ -1,5 +1,5 @@ import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue'; -import { buildLogProgressUrl } from '../utils/toolRunProgressConfig'; +import { buildFileCheckLogProgressUrl } from '../utils/toolRunProgressConfig'; import { getToolRunProgress, type ToolRunProgress } from '../api/toolRunProgress.api'; import type { ToolRunProgressMatchSource } from '../types/tool-run-progress.types'; @@ -124,10 +124,11 @@ export function useToolRunProgress( return fetchProgressUrl(sessionUrl, silent); } const taskId = Number(cfg.schedule_task_id ?? cfg.task_id); - const sessionId = String(cfg.session_id || '').trim(); - if (!Number.isFinite(taskId) || taskId <= 0 || !sessionId) return null; - const fallbackUrl = buildLogProgressUrl('/api/workspace/rohs-check/runs/for-log', taskId, Number(cfg.chat_log_id)); - return fetchProgressUrl(fallbackUrl, silent); + const chatLogId = Number(cfg.chat_log_id); + if (!Number.isFinite(taskId) || taskId <= 0 || !Number.isFinite(chatLogId) || chatLogId <= 0) { + return null; + } + return fetchProgressUrl(buildFileCheckLogProgressUrl(taskId, chatLogId), silent); }; const refresh = async () => { diff --git a/frontend/src/features/chat/page/useChatPageToolRun.ts b/frontend/src/features/chat/page/useChatPageToolRun.ts index 51d7539f..a7bf487e 100644 --- a/frontend/src/features/chat/page/useChatPageToolRun.ts +++ b/frontend/src/features/chat/page/useChatPageToolRun.ts @@ -1,6 +1,6 @@ /** - * 对话页:Agent tool_run_progress 能力轮询(RoHS 等异步任务进度卡片)。 + * 对话页:Agent tool_run_progress 能力轮询(文件检核等异步任务进度卡片)。 * 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。 @@ -24,22 +24,14 @@ import { assistantMessageHasError, - buildLogProgressUrl, - + buildFileCheckDetailUrl, + buildFileCheckLogProgressUrl, collectAssistantProgressTargets, - getChatLogIdFromMessage, - getRunIdFromMessage, - isRunningToolRunStatus, - - resolveLogProgressBaseUrl, - resolveScheduleTaskId, - resolveMessageAnchorKey, - } from '../utils/toolRunProgressConfig'; @@ -132,28 +124,12 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) { - const resolveDetailUrl = (runId: number) => { - - const template = String(rawToolRunConfig.value?.detail_url_template || '').trim(); - - if (!template) return ''; - - return template.replace('{run_id}', encodeURIComponent(String(runId))); - - }; - - + const resolveDetailUrl = (runId: number) => buildFileCheckDetailUrl(runId); const resolveForLogUrl = (chatLogId: number) => { - const taskId = boundScheduleTaskId.value; - if (!taskId) return ''; - - const base = resolveLogProgressBaseUrl(rawToolRunConfig.value || {}); - - return buildLogProgressUrl(base, taskId, chatLogId); - + return buildFileCheckLogProgressUrl(taskId, chatLogId); }; diff --git a/frontend/src/features/chat/types/chat.types.ts b/frontend/src/features/chat/types/chat.types.ts index 443b7931..74ffce0b 100644 --- a/frontend/src/features/chat/types/chat.types.ts +++ b/frontend/src/features/chat/types/chat.types.ts @@ -22,7 +22,7 @@ export interface ChatMessage { retriever_resources?: RetrieverResource[]; attribution_parts?: string[]; chat_log_id?: number; - /** RoHS 等异步任务批次 ID(按轮问答绑定) */ + /** 文件检核等异步任务批次 ID(按轮问答绑定) */ run_id?: number; payload?: unknown; local_id?: string; diff --git a/frontend/src/features/chat/utils/toolRunProgressConfig.ts b/frontend/src/features/chat/utils/toolRunProgressConfig.ts index 7decfe1a..51819839 100644 --- a/frontend/src/features/chat/utils/toolRunProgressConfig.ts +++ b/frontend/src/features/chat/utils/toolRunProgressConfig.ts @@ -2,7 +2,7 @@ * features/chat/utils/toolRunProgressConfig.ts * 用途:解析 Agent tool_run_progress 配置;构建 for-log / detail 轮询 URL。 * 依赖:ToolRunProgressConfig、ChatMessage。 - * 逻辑:进度卡片由 ChatLog.run_id(按轮问答)驱动;执行中与已完成批次均展示。 + * 逻辑:文件检核进度 URL 由 schedule_task_id + chat_log_id/run_id 推导,无需 Agent 配置 log_progress_url。 */ import type { ToolRunProgressConfig } from '../composables/useToolRunProgress'; import type { ChatMessage } from '../types/chat.types'; @@ -11,8 +11,13 @@ export interface ResolvedToolRunProgressOptions { empty_poll_max: number; } +/** 文件检核 for-log 轮询路径(固定;query 带 task_id、chat_log_id) */ +export const FILE_CHECK_LOG_PROGRESS_PATH = '/api/workspace/file-check/runs/for-log'; + +/** 文件检核 detail 轮询路径模板(固定;{run_id} 替换为批次 ID) */ +export const FILE_CHECK_DETAIL_PATH_TEMPLATE = '/api/workspace/file-check/runs/{run_id}'; + const DEFAULT_EMPTY_POLL_MAX = 30; -const DEFAULT_LOG_PROGRESS_URL = '/api/workspace/rohs-check/runs/for-log'; export function resolveToolRunProgressOptions( raw: Record | ToolRunProgressConfig | null | undefined, @@ -46,10 +51,19 @@ export function resolveScheduleTaskId(cfg: ToolRunProgressConfig | null | undefi return Number.isFinite(id) && id > 0 ? id : null; } -export function resolveLogProgressBaseUrl(cfg: ToolRunProgressConfig): string { - const logUrl = String(cfg.log_progress_url || cfg.session_progress_url || '').trim(); - if (logUrl) return logUrl.split('?')[0] || logUrl; - return DEFAULT_LOG_PROGRESS_URL; +/** + * 文件检核 for-log 基路径;不读 Agent 配置,避免运维维护 URL。 + */ +export function resolveFileCheckLogProgressPath(): string { + return FILE_CHECK_LOG_PROGRESS_PATH; +} + +/** + * 按 run_id 生成文件检核 detail 轮询 URL。 + */ +export function buildFileCheckDetailUrl(runId: number): string { + if (!Number.isFinite(runId) || runId <= 0) return ''; + return FILE_CHECK_DETAIL_PATH_TEMPLATE.replace('{run_id}', encodeURIComponent(String(runId))); } export function buildLogProgressUrl( @@ -68,6 +82,15 @@ export function buildLogProgressUrl( return qs ? `${path}?${qs}` : path; } +export function buildFileCheckLogProgressUrl(taskId: number, chatLogId: number): string { + return buildLogProgressUrl(resolveFileCheckLogProgressPath(), taskId, chatLogId); +} + +/** @deprecated 仅兼容旧调用;新逻辑请用 buildFileCheckLogProgressUrl */ +export function resolveLogProgressBaseUrl(_cfg?: ToolRunProgressConfig): string { + return resolveFileCheckLogProgressPath(); +} + export function getRunIdFromMessage(msg: ChatMessage | null | undefined): number | null { const runId = Number(msg?.run_id); return Number.isFinite(runId) && runId > 0 ? runId : null;