refactor(file-check): 增强文件检核服务,新增可靠性元信息与错误分类

This commit is contained in:
hugo committed 2026-07-06 14:50:59 +08:00
1 parent f72c1c9f0e
commit 090281835a
14 files changed
+1093 -151

No files matched your search

+12 -1
View File
@@ -37,7 +37,18 @@ def serialize_file_judgement(payload: dict) -> dict:
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), 'manual_count': int(judgement.get('manual_count') or 0), 'dify_error_count': int(judgement.get('dify_error_count') or 0), 'invalid_result_count': int(judgement.get('invalid_result_count') or 0)}
return {
'qualified_count': int(judgement.get('qualified_count') or 0),
'unqualified_count': int(judgement.get('unqualified_count') or 0),
'manual_count': int(judgement.get('manual_count') or 0),
'dify_error_count': int(judgement.get('dify_error_count') or 0),
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
'business_manual_count': int(judgement.get('business_manual_count') or 0),
'system_error_count': int(judgement.get('system_error_count') or 0),
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
}
def serialize_current_step(payload: dict) -> dict | None:
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
+232 -63
View File
@@ -324,6 +324,116 @@ class DifyService:
}
return data
@staticmethod
def _classify_workflow_request_exception(exc: Exception) -> tuple[str, bool]:
"""
将 Workflow HTTP/网络异常归类为 error_type,并判断是否可重试。
502/503/504 与连接/读超时视为可恢复;400/401/403 不重试。
"""
if isinstance(exc, requests.exceptions.ConnectTimeout):
return "connect_timeout", True
if isinstance(exc, requests.exceptions.ReadTimeout):
return "read_timeout", True
if isinstance(exc, requests.exceptions.ConnectionError):
return "connection_error", True
if isinstance(exc, requests.exceptions.HTTPError):
status = int(getattr(getattr(exc, "response", None), "status_code", 0) or 0)
if status in (502, 503, 504):
return f"http_{status}", True
if status in (400, 401, 403):
return f"http_{status}", False
return f"http_{status}", False
return "request_error", False
@staticmethod
def _attach_workflow_reliability_meta(
result: dict[str, Any],
*,
poll_used: bool = False,
retry_count: int = 0,
error_type: str | None = None,
workflow_run_id: str | None = None,
) -> dict[str, Any]:
"""在 Dify Workflow 响应上附加网关侧可靠性元信息(poll/重试/错误类型)。"""
out = dict(result) if isinstance(result, dict) else {}
if workflow_run_id and not out.get("workflow_run_id"):
out["workflow_run_id"] = workflow_run_id
out["_workflow_poll_used"] = bool(poll_used)
out["_workflow_retry_count"] = max(0, int(retry_count))
if error_type:
out["_workflow_error_type"] = error_type
return out
@staticmethod
def _consume_workflow_stream(
*,
url: str,
headers: dict[str, str],
payload: dict[str, Any],
timeout: tuple[int, int],
state: dict[str, Any],
) -> dict[str, Any]:
"""
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
state 在解析过程中写入 workflow_run_id / result,供断连后补偿使用。
"""
result: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
if not resp.ok:
body = resp.text[:2000]
if current_app:
current_app.logger.error(
"[workflow-streaming] dify error status=%s url=%s body=%s",
resp.status_code, url, body,
)
resp.raise_for_status()
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
if not line.startswith("data:"):
continue
raw = line[len("data:"):].strip()
if not raw:
continue
try:
evt = json.loads(raw)
except json.JSONDecodeError:
continue
event_type = evt.get("event", "")
if event_type == "workflow_started":
run_id = (evt.get("data") or {}).get("workflow_run_id")
state["workflow_run_id"] = run_id
if current_app:
current_app.logger.info(
"[workflow-streaming] started run_id=%s",
run_id,
)
elif event_type == "workflow_finished":
result = evt.get("data") or {}
state["result"] = result
if current_app:
current_app.logger.info(
"[workflow-streaming] finished status=%s error=%s",
result.get("status"),
result.get("error"),
)
elif event_type == "error":
err_msg = evt.get("message") or str(evt)
if current_app:
current_app.logger.error(
"[workflow-streaming] dify stream error: %s",
err_msg,
)
raise RuntimeError(f"Dify workflow error: {err_msg}")
return result
@staticmethod
def run_workflow_streaming(
*,
@@ -332,6 +442,10 @@ class DifyService:
user: str = "system",
timeout: tuple[int, int] = (5, 300),
) -> dict[str, Any]:
"""
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
对可恢复网络错误最多重试 1 次;返回体附带 _workflow_* 可靠性元信息。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_workflow_url(base_url)
@@ -344,6 +458,12 @@ class DifyService:
"response_mode": "streaming",
"user": str(user or "system"),
}
max_wait = timeout[1] if isinstance(timeout, tuple) else 300
max_attempts = 2
retry_count = 0
poll_used = False
last_error_type: str | None = None
last_workflow_run_id: str | None = None
if current_app:
current_app.logger.info(
@@ -354,86 +474,135 @@ class DifyService:
)
result: dict[str, Any] = {}
workflow_run_id: str | None = None
stream_state: dict[str, Any] = {"workflow_run_id": None, "result": {}}
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
if not resp.ok:
body = resp.text[:2000]
for attempt in range(max_attempts):
try:
result = DifyService._consume_workflow_stream(
url=url,
headers=headers,
payload=payload,
timeout=timeout,
state=stream_state,
)
workflow_run_id = stream_state.get("workflow_run_id")
if workflow_run_id:
last_workflow_run_id = workflow_run_id
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
if not result and workflow_run_id:
poll_used = True
if current_app:
current_app.logger.error(
"[workflow-streaming] dify error status=%s url=%s body=%s",
resp.status_code, url, body,
current_app.logger.warning(
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
workflow_run_id,
)
resp.raise_for_status()
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=True,
retry_count=retry_count,
error_type=poll_error_type or "stream_closed_early",
workflow_run_id=workflow_run_id,
)
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
if not line.startswith("data:"):
continue
raw = line[len("data:"):].strip()
if not raw:
continue
try:
evt = json.loads(raw)
except json.JSONDecodeError:
continue
event_type = evt.get("event", "")
if event_type == "workflow_started":
workflow_run_id = (evt.get("data") or {}).get("workflow_run_id")
if current_app:
current_app.logger.info(
"[workflow-streaming] started run_id=%s",
workflow_run_id,
)
elif event_type == "workflow_finished":
result = evt.get("data") or {}
if current_app:
current_app.logger.info(
"[workflow-streaming] finished status=%s error=%s",
result.get("status"),
result.get("error"),
)
elif event_type == "error":
err_msg = evt.get("message") or str(evt)
if current_app:
current_app.logger.error(
"[workflow-streaming] dify stream error: %s",
err_msg,
)
raise RuntimeError(f"Dify workflow error: {err_msg}")
except requests.exceptions.RequestException as exc:
if result:
if current_app:
current_app.logger.info(
"[workflow-streaming] connection dropped but result already captured",
"[workflow-streaming] attempt=%s finished run_id=%s retry_count=%s",
attempt + 1,
workflow_run_id,
retry_count,
)
elif workflow_run_id:
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=False,
retry_count=retry_count,
workflow_run_id=workflow_run_id,
)
except requests.exceptions.RequestException as exc:
error_type, retryable = DifyService._classify_workflow_request_exception(exc)
last_error_type = error_type
workflow_run_id = stream_state.get("workflow_run_id")
partial_result = stream_state.get("result") or {}
if workflow_run_id:
last_workflow_run_id = workflow_run_id
if current_app:
current_app.logger.warning(
"[workflow-streaming] connection dropped, polling result for run_id=%s",
"[workflow-streaming] attempt=%s error_type=%s retryable=%s run_id=%s err=%s",
attempt + 1,
error_type,
retryable,
workflow_run_id,
exc,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=timeout[1] if isinstance(timeout, tuple) else 300,
)
else:
if partial_result:
if current_app:
current_app.logger.info(
"[workflow-streaming] connection dropped but result already captured run_id=%s",
workflow_run_id,
)
return DifyService._attach_workflow_reliability_meta(
partial_result,
poll_used=False,
retry_count=retry_count,
error_type=error_type,
workflow_run_id=workflow_run_id,
)
if workflow_run_id:
poll_used = True
if current_app:
current_app.logger.warning(
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
workflow_run_id,
error_type,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=True,
retry_count=retry_count,
error_type=poll_error_type or error_type,
workflow_run_id=workflow_run_id,
)
if retryable and attempt < max_attempts - 1:
retry_count += 1
if current_app:
current_app.logger.info(
"[workflow-streaming] retrying attempt=%s error_type=%s",
attempt + 2,
error_type,
)
continue
if current_app:
current_app.logger.error(
"[workflow-streaming] request error (no run_id): %s",
"[workflow-streaming] request failed (no run_id) error_type=%s err=%s",
error_type,
exc,
)
raise
return result if isinstance(result, dict) else {}
return DifyService._attach_workflow_reliability_meta(
result if isinstance(result, dict) else {},
poll_used=poll_used,
retry_count=retry_count,
error_type=last_error_type,
workflow_run_id=last_workflow_run_id,
)
@staticmethod
def _poll_workflow_result(
+259 -16
View File
@@ -7,12 +7,180 @@ backend/app/services/file_check.py
"""
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 调用与结果规范化。"""
@@ -44,7 +212,7 @@ class FileCheckService:
timeout: HTTP 超时 (connect, read) 秒。
Returns:
含 dify_result、dify_message、workflow_run_id 等字段的 dict。
含 dify_result、dify_message、workflow_run_id 及可靠性/分类元信息的 dict。
"""
inputs: dict[str, Any] = {
"run_no": run_no,
@@ -63,12 +231,20 @@ class FileCheckService:
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)
@@ -77,40 +253,107 @@ class FileCheckService:
@staticmethod
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
"""将 Dify Workflow 输出规范为合格/不合格/人工判定。"""
"""将 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 {}
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 = data.get("workflow_run_id") if isinstance(data, dict) else None
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 {
"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,
}
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_message": f"返回值异常:{bad_value}{extra}",
"workflow_run_id": workflow_run_id,
"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,
"workflow_run_id": workflow_run_id,
"error": None,
"raw_outputs": output_data,
**reliability_fields,
"manual_reason_type": None,
"is_system_error": False,
"user_action_hint": None,
}
+13 -1
View File
@@ -32,7 +32,19 @@ def export_schedule_result_excel(
header_labels = header_labels or {}
detail_alias_order = detail_alias_order or []
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
exec_result_order = [
"dify_result",
"dify_message",
"workflow_run_id",
"dify_error_type",
"dify_retry_count",
"dify_poll_used",
"manual_reason_type",
"is_system_error",
"user_action_hint",
"writeback_srm",
"writeback_err",
]
sql_headers: list[str] = []
detail_headers: list[str] = []
+46 -24
View File
@@ -5,7 +5,7 @@ from typing import Any, Callable
from flask import current_app, has_app_context
from app.services.file_check import FileCheckService
from app.services.file_check import FileCheckService, build_no_dify_agent_result, empty_judgement_stats, increment_judgement_stats
try:
import pyodbc # type: ignore
@@ -187,13 +187,7 @@ def _run_check_job_loop(
success_count = 0
failed_count = 0
skipped_count = 0
judgement_stats = {
"qualified_count": 0,
"unqualified_count": 0,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
}
judgement_stats = empty_judgement_stats()
current_step: dict[str, Any] | None = None
all_errors: list[str] = []
@@ -302,6 +296,13 @@ def _run_check_job_loop(
dify_ok = False
dify_result = "人工判定"
dify_message = ""
workflow_run_id = None
dify_error_type = None
dify_retry_count = 0
dify_poll_used = False
manual_reason_type = None
is_system_error = False
user_action_hint = None
try:
if use_dify:
@@ -337,21 +338,20 @@ def _run_check_job_loop(
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
dify_error_type = dify_res.get("error_type") if isinstance(dify_res, dict) else None
dify_retry_count = dify_res.get("retry_count") if isinstance(dify_res, dict) else None
dify_poll_used = dify_res.get("poll_used") if isinstance(dify_res, dict) else None
manual_reason_type = dify_res.get("manual_reason_type") if isinstance(dify_res, dict) else None
is_system_error = bool(dify_res.get("is_system_error")) if isinstance(dify_res, dict) else False
user_action_hint = dify_res.get("user_action_hint") if isinstance(dify_res, dict) else None
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
dify_ok = True
if dify_result == "合格":
judgement_stats["qualified_count"] += 1
elif dify_result == "不合格":
judgement_stats["unqualified_count"] += 1
else:
judgement_stats["manual_count"] += 1
if dify_error:
judgement_stats["dify_error_count"] += 1
raw_outputs = dify_res.get("raw_outputs") if isinstance(dify_res, dict) else None
if dify_result == "人工判定" and isinstance(raw_outputs, dict) and not dify_error:
raw_result = str(raw_outputs.get("dify_result") or raw_outputs.get("result") or "").strip()
if raw_result and raw_result not in {"合格", "不合格", "人工判定"}:
judgement_stats["invalid_result_count"] += 1
increment_judgement_stats(
judgement_stats,
dify_result=dify_result,
manual_reason_type=manual_reason_type,
is_system_error=is_system_error,
)
if current_app:
current_app.logger.info(
@@ -370,13 +370,28 @@ def _run_check_job_loop(
"dify_message": _truncate_str(dify_message),
"workflow_run_id": workflow_run_id,
"error": dify_error,
"error_type": dify_error_type,
"retry_count": dify_retry_count,
"poll_used": dify_poll_used,
"manual_reason_type": manual_reason_type,
"is_system_error": is_system_error,
"user_action_hint": user_action_hint,
},
}))
else:
dify_result = "人工判定"
dify_message = "未配置 Agent ID,跳过 Dify"
no_agent = build_no_dify_agent_result()
dify_result = no_agent["dify_result"]
dify_message = no_agent["dify_message"]
manual_reason_type = no_agent["manual_reason_type"]
is_system_error = no_agent["is_system_error"]
user_action_hint = no_agent["user_action_hint"]
dify_ok = True
judgement_stats["manual_count"] += 1
increment_judgement_stats(
judgement_stats,
dify_result=dify_result,
manual_reason_type=manual_reason_type,
is_system_error=is_system_error,
)
wb_sql = writeback_sql
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
@@ -391,6 +406,13 @@ def _run_check_job_loop(
item.update({
"dify_result": dify_result,
"dify_message": dify_message,
"workflow_run_id": workflow_run_id,
"dify_error_type": dify_error_type,
"dify_retry_count": dify_retry_count,
"dify_poll_used": dify_poll_used,
"manual_reason_type": manual_reason_type,
"is_system_error": is_system_error,
"user_action_hint": user_action_hint,
"writeback_srm": True,
"writeback_err": item.get("writeback_err"),
})
@@ -41,7 +41,7 @@ from app.services.shipping_notice.inventory_upload import (
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
from app.services.shipping_notice.tool_common import (
log_task_action_event,
log_task_event,
@@ -271,15 +271,18 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
db.session.commit()
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(
task,
column_meta=meta,
extra_data={
"warnings": [
t("workflow.decision.mapping_missing_reservation_warning", lang=lang),
],
},
lang=lang or None,
warning = t("workflow.decision.mapping_missing_reservation_warning", lang=lang)
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message=warning,
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
human_options=ui.human_options,
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
+5 -1
View File
@@ -462,4 +462,8 @@ def resolve_lang(payload: dict[str, Any] | None = None) -> str:
def t(key: str, *, lang: str | None = None) -> str:
"""按语言键查找 i18n 文案;未命中时回退 zh 或原 key。"""
resolved = normalize_lang(lang) if lang else "zh"
return _MESSAGES.get(resolved, {}).get(key) or _MESSAGES["zh"].get(key) or key
if key in _MESSAGES.get(resolved, {}):
return _MESSAGES[resolved][key]
if key in _MESSAGES["zh"]:
return _MESSAGES["zh"][key]
return key