""" backend/app/services/rohs_check.py 文件用途:RoHS 文件检核统一判定入口,当前适配现有 Dify Workflow。 """ from __future__ import annotations from typing import Any from app.services.dify import DifyService VALID_ROHS_RESULTS = {"合格", "不合格", "人工判定"} class RoHSCheckService: """Wrap RoHS judgement behind a stable backend interface.""" 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]: 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: return { "dify_result": "人工判定", "dify_message": f"Dify执行失败:{exc}", "provider": cls.PROVIDER, "workflow_run_id": None, "error": str(exc), } 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]: 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 {} 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 = data.get("workflow_run_id") if isinstance(data, dict) else None status = data.get("status") if isinstance(data, dict) else None error = data.get("error") if isinstance(data, dict) else None if status == "failed" or (error and not output_data): return { "dify_result": "人工判定", "dify_message": f"Dify执行失败:{error or f'status={status}'}", "workflow_run_id": workflow_run_id, "error": str(error or ""), "raw_outputs": output_data, } if dify_result not in VALID_ROHS_RESULTS: bad_value = dify_result or "空" extra = f" | {dify_message}" if dify_message else "" return { "dify_result": "人工判定", "dify_message": f"返回值异常:{bad_value}{extra}", "workflow_run_id": workflow_run_id, "error": None, "raw_outputs": output_data, } return { "dify_result": dify_result, "dify_message": dify_message, "workflow_run_id": workflow_run_id, "error": None, "raw_outputs": output_data, }