""" backend/app/services/file_check.py 用途:文件检核统一判定入口,调用 ScheduleTask 绑定的 Dify Workflow。 依赖:DifyService.run_workflow_streaming。 逻辑:由 schedule/srm_service 检核循环逐条调用;RoHS/MSDS 等差异在 Workflow 与排程 SQL 配置。 """ from __future__ import annotations import re from typing import Any import requests from app.services.dify import DifyService VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"} MANUAL_REASON_BUSINESS_UNCERTAIN = "business_uncertain" MANUAL_REASON_DIFY_TIMEOUT = "dify_timeout" MANUAL_REASON_POLL_TIMEOUT = "poll_timeout" MANUAL_REASON_DIFY_FAILED = "dify_failed" MANUAL_REASON_INVALID_OUTPUT = "invalid_workflow_output" MANUAL_REASON_ATTACHMENT_FAILED = "attachment_read_failed" MANUAL_REASON_NO_DIFY_AGENT = "no_dify_agent" SYSTEM_MANUAL_REASON_TYPES = { MANUAL_REASON_DIFY_TIMEOUT, MANUAL_REASON_POLL_TIMEOUT, MANUAL_REASON_DIFY_FAILED, MANUAL_REASON_INVALID_OUTPUT, MANUAL_REASON_ATTACHMENT_FAILED, } _GATEWAY_TIMEOUT_ERROR_TYPES = { "read_timeout", "connect_timeout", "connection_error", "stream_closed_early", } _ATTACHMENT_FAIL_PATTERN = re.compile( r"附件.{0,8}读取失败|读取附件失败|无法读取附件|attachment.{0,12}read.{0,8}fail|attachment_read_failed", re.IGNORECASE, ) def _extract_workflow_reliability_meta(workflow_result: dict[str, Any] | None) -> dict[str, Any]: """从 Dify Workflow 原始响应提取网关侧可靠性元信息。""" data = workflow_result if isinstance(workflow_result, dict) else {} workflow_run_id = data.get("workflow_run_id") or data.get("id") return { "workflow_run_id": workflow_run_id, "poll_used": bool(data.get("_workflow_poll_used")), "retry_count": int(data.get("_workflow_retry_count") or 0), "error_type": data.get("_workflow_error_type"), } def _classify_evaluate_exception(exc: Exception) -> tuple[str, bool]: """将 evaluate 层异常映射为 error_type 与是否可重试。""" if isinstance(exc, requests.exceptions.RequestException): return DifyService._classify_workflow_request_exception(exc) return "evaluate_error", False def _gateway_error_to_manual_reason(error_type: str | None) -> str: """将网关 error_type 映射为 manual_reason_type。""" normalized = str(error_type or "").strip().lower() if normalized == "poll_timeout": return MANUAL_REASON_POLL_TIMEOUT if normalized in _GATEWAY_TIMEOUT_ERROR_TYPES: return MANUAL_REASON_DIFY_TIMEOUT return MANUAL_REASON_DIFY_FAILED def _detect_attachment_read_failure(*texts: str | None) -> bool: """根据 Dify 返回文案判断是否附件读取失败。""" combined = " ".join(str(t or "") for t in texts if t) if not combined.strip(): return False if _ATTACHMENT_FAIL_PATTERN.search(combined): return True lowered = combined.lower() return "attachment_read_failed" in lowered or "附件读取失败" in combined def user_action_hint_for_manual_reason(manual_reason_type: str | None) -> str | None: """按 manual_reason_type 返回给业务人员的操作建议。""" hints = { MANUAL_REASON_BUSINESS_UNCERTAIN: "AI 无法给出明确结论,请人工复核材料后至 SRM 审核或驳回", MANUAL_REASON_DIFY_TIMEOUT: "系统调用 Dify 超时,请稍后重试或联系运维排查网络/代理", MANUAL_REASON_POLL_TIMEOUT: "系统补偿查询 Dify 结果超时,请稍后重试或凭 workflow_run_id 对账", MANUAL_REASON_DIFY_FAILED: "Dify Workflow 执行失败,请查看 dify_message 或联系运维", MANUAL_REASON_INVALID_OUTPUT: "Dify 返回格式不符合约定,请检查 Workflow 输出节点", MANUAL_REASON_ATTACHMENT_FAILED: "附件读取失败,请检查 SRM 附件链接或文件是否可访问", MANUAL_REASON_NO_DIFY_AGENT: "未配置 Dify Agent,请在排程管理中绑定后重新检核", } if not manual_reason_type: return None return hints.get(manual_reason_type) def build_manual_classification( manual_reason_type: str | None, *, is_system_error: bool | None = None, ) -> dict[str, Any]: """构建 manual_reason_type / is_system_error / user_action_hint 三元组。""" reason = str(manual_reason_type or "").strip() or None system = ( bool(is_system_error) if is_system_error is not None else bool(reason and reason in SYSTEM_MANUAL_REASON_TYPES) ) return { "manual_reason_type": reason, "is_system_error": system, "user_action_hint": user_action_hint_for_manual_reason(reason), } def build_no_dify_agent_result() -> dict[str, Any]: """未配置 Dify Agent 时的标准判定结果。""" classification = build_manual_classification(MANUAL_REASON_NO_DIFY_AGENT, is_system_error=False) return { "dify_result": "人工判定", "dify_message": "未配置 Agent ID,跳过 Dify", **classification, } def increment_judgement_stats( stats: dict[str, Any], *, dify_result: str, manual_reason_type: str | None = None, is_system_error: bool = False, ) -> None: """ 按单条判定结果累加批次 judgement 统计。 manual_count 仍表示所有「人工判定」条数;新增字段区分业务与系统原因。 """ result = str(dify_result or "").strip() if result == "合格": stats["qualified_count"] = int(stats.get("qualified_count") or 0) + 1 return if result == "不合格": stats["unqualified_count"] = int(stats.get("unqualified_count") or 0) + 1 return stats["manual_count"] = int(stats.get("manual_count") or 0) + 1 reason = str(manual_reason_type or "").strip() if reason == MANUAL_REASON_BUSINESS_UNCERTAIN: stats["business_manual_count"] = int(stats.get("business_manual_count") or 0) + 1 if is_system_error: stats["system_error_count"] = int(stats.get("system_error_count") or 0) + 1 stats["dify_error_count"] = int(stats.get("dify_error_count") or 0) + 1 if reason in (MANUAL_REASON_DIFY_TIMEOUT, MANUAL_REASON_POLL_TIMEOUT): stats["dify_timeout_count"] = int(stats.get("dify_timeout_count") or 0) + 1 if reason == MANUAL_REASON_INVALID_OUTPUT: stats["invalid_output_count"] = int(stats.get("invalid_output_count") or 0) + 1 stats["invalid_result_count"] = int(stats.get("invalid_result_count") or 0) + 1 if reason == MANUAL_REASON_ATTACHMENT_FAILED: stats["attachment_error_count"] = int(stats.get("attachment_error_count") or 0) + 1 def empty_judgement_stats() -> dict[str, int]: """文件检核批次 judgement 统计初始值。""" return { "qualified_count": 0, "unqualified_count": 0, "manual_count": 0, "dify_error_count": 0, "invalid_result_count": 0, "business_manual_count": 0, "system_error_count": 0, "dify_timeout_count": 0, "invalid_output_count": 0, "attachment_error_count": 0, } class FileCheckService: """文件检核 Dify Workflow 调用与结果规范化。""" PROVIDER = "dify_workflow" @classmethod def evaluate( cls, *, agent, run_no: str, record: str, attachment_url: str | None = None, system_prompt: str | None = None, 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, "attachment_url": attachment_url, } prompt = str(system_prompt or "").strip() if prompt: inputs["system_prompt"] = prompt try: workflow_result = DifyService.run_workflow_streaming( agent=agent, inputs=inputs, user=user, timeout=timeout, ) except Exception as exc: error_type, retryable = _classify_evaluate_exception(exc) manual_reason = _gateway_error_to_manual_reason(error_type) classification = build_manual_classification(manual_reason, is_system_error=True) return { "dify_result": "人工判定", "dify_message": f"Dify执行失败:{exc}", "provider": cls.PROVIDER, "workflow_run_id": None, "error": str(exc), "error_type": error_type, "retryable": retryable, "retry_count": 0, "poll_used": False, **classification, } normalized = cls.normalize_workflow_result(workflow_result) normalized["provider"] = cls.PROVIDER return normalized @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 {} reliability = _extract_workflow_reliability_meta(data) outputs_container = data.get("outputs") if isinstance(outputs_container, dict): nested = outputs_container.get("output") output_data = nested if isinstance(nested, dict) else outputs_container else: output_data = {} dify_result = str(output_data.get("dify_result") or output_data.get("result") or "").strip() dify_message = str(output_data.get("dify_message") or output_data.get("message") or "").strip() workflow_run_id = reliability.get("workflow_run_id") status = data.get("status") if isinstance(data, dict) else None error = data.get("error") if isinstance(data, dict) else None gateway_error_type = reliability.get("error_type") reliability_fields = { "workflow_run_id": workflow_run_id, "poll_used": reliability.get("poll_used"), "retry_count": reliability.get("retry_count"), "error_type": gateway_error_type, "retryable": None, } def _with_classification(payload: dict[str, Any], manual_reason_type: str) -> dict[str, Any]: classification = build_manual_classification(manual_reason_type) return {**payload, **reliability_fields, **classification} if _detect_attachment_read_failure(dify_message, str(error or ""), str(output_data.get("error") or "")): return _with_classification( { "dify_result": "人工判定", "dify_message": dify_message or f"Dify执行失败:{error or '附件读取失败'}", "error": str(error or "attachment_read_failed"), "raw_outputs": output_data, }, MANUAL_REASON_ATTACHMENT_FAILED, ) if not output_data and not dify_result and gateway_error_type == "poll_timeout": return _with_classification( { "dify_result": "人工判定", "dify_message": "Dify执行失败:poll 超时未获取最终结果", "error": "poll_timeout", "raw_outputs": output_data, }, MANUAL_REASON_POLL_TIMEOUT, ) if gateway_error_type in _GATEWAY_TIMEOUT_ERROR_TYPES and not output_data and not dify_result: return _with_classification( { "dify_result": "人工判定", "dify_message": f"Dify执行失败:{gateway_error_type}", "error": str(gateway_error_type), "raw_outputs": output_data, }, MANUAL_REASON_DIFY_TIMEOUT, ) if status == "failed" or (error and not output_data): return _with_classification( { "dify_result": "人工判定", "dify_message": f"Dify执行失败:{error or f'status={status}'}", "error": str(error or ""), "raw_outputs": output_data, }, MANUAL_REASON_DIFY_FAILED, ) if dify_result not in VALID_FILE_CHECK_RESULTS: bad_value = dify_result or "空" extra = f" | {dify_message}" if dify_message else "" return _with_classification( { "dify_result": "人工判定", "dify_message": f"返回值异常:{bad_value}{extra}", "error": None, "raw_outputs": output_data, }, MANUAL_REASON_INVALID_OUTPUT, ) if dify_result == "人工判定": return { "dify_result": dify_result, "dify_message": dify_message, "error": None, "raw_outputs": output_data, **reliability_fields, **build_manual_classification(MANUAL_REASON_BUSINESS_UNCERTAIN, is_system_error=False), } return { "dify_result": dify_result, "dify_message": dify_message, "error": None, "raw_outputs": output_data, **reliability_fields, "manual_reason_type": None, "is_system_error": False, "user_action_hint": None, }