469 lines
18 KiB
Python
469 lines
18 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any, Callable
|
|
|
|
from flask import current_app, has_app_context
|
|
|
|
from app.services.file_check import FileCheckService, build_no_dify_agent_result, empty_judgement_stats, increment_judgement_stats
|
|
|
|
try:
|
|
import pyodbc # type: ignore
|
|
except Exception: # pragma: no cover
|
|
pyodbc = None
|
|
|
|
|
|
def _connect(conn_str: str):
|
|
if pyodbc is None:
|
|
raise RuntimeError("pyodbc is not installed")
|
|
return pyodbc.connect(conn_str, timeout=_sql_timeout_seconds())
|
|
|
|
|
|
def _sql_timeout_seconds() -> int:
|
|
if not has_app_context():
|
|
return 15
|
|
try:
|
|
value = int(current_app.config.get("SRM_SQLSERVER_TIMEOUT", 15) or 15)
|
|
except Exception:
|
|
value = 15
|
|
return max(1, value)
|
|
|
|
|
|
def _apply_cursor_timeout(cursor) -> None:
|
|
try:
|
|
cursor.timeout = _sql_timeout_seconds()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]:
|
|
conn = _connect(conn_str)
|
|
try:
|
|
cur = conn.cursor()
|
|
_apply_cursor_timeout(cur)
|
|
if params:
|
|
cur.execute(sql, params)
|
|
else:
|
|
cur.execute(sql)
|
|
cols = [c[0] for c in cur.description]
|
|
rows = cur.fetchall()
|
|
return [{cols[i]: row[i] for i in range(len(cols))} for row in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
|
|
conn = _connect(conn_str)
|
|
try:
|
|
cur = conn.cursor()
|
|
_apply_cursor_timeout(cur)
|
|
cur.execute(sql, params)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def _derive_dify_result_and_message(data: dict[str, Any]) -> tuple[str, str]:
|
|
dify_result = str(data.get("dify_result")).strip()
|
|
dify_message = str(data.get("dify_message")).strip()
|
|
if dify_result not in {"合格", "不合格", "人工判定"}:
|
|
dify_message = (dify_message + " | 返回值异常:" + dify_result).strip(" |")
|
|
dify_result = "人工判定"
|
|
return dify_result, dify_message
|
|
|
|
|
|
def _build_record_text(
|
|
item: dict[str, Any],
|
|
alias_order: list[str],
|
|
header_labels: dict[str, str],
|
|
detail_rows: list[dict[str, Any]] | None = None,
|
|
detail_alias_order: list[str] | None = None,
|
|
) -> str:
|
|
lines: list[str] = []
|
|
for key in alias_order:
|
|
label = header_labels.get(key, key)
|
|
value = item.get(key)
|
|
text = "" if value is None else str(value)
|
|
lines.append(f"{label}: {text}")
|
|
if detail_rows and detail_alias_order:
|
|
lines.append("成分明细:")
|
|
for idx, dr in enumerate(detail_rows, 1):
|
|
detail_parts: list[str] = []
|
|
for dk in detail_alias_order:
|
|
dl = header_labels.get(dk, dk)
|
|
dv = dr.get(dk)
|
|
detail_parts.append(f"{dl}: {'' if dv is None else str(dv)}")
|
|
lines.append(f" [{idx}] " + ", ".join(detail_parts))
|
|
return "\n".join(lines)
|
|
|
|
|
|
RecordBuilder = Callable[[str, dict[str, Any], str], tuple[str, str | None]]
|
|
WritebackFunc = Callable[..., None]
|
|
PreDifyFunc = Callable[[str, dict[str, Any], str], dict[str, Any] | None]
|
|
|
|
_MAX_STEP_LOGS_PER_ROW = 200
|
|
_MAX_DIFY_RESPONSE_LEN = 4000
|
|
|
|
|
|
def _ts() -> str:
|
|
return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
|
|
|
|
|
|
def _make_step(
|
|
step: str,
|
|
status: str,
|
|
started_at: str,
|
|
finished_at: str,
|
|
row_id: str | None = None,
|
|
**extra: Any,
|
|
) -> dict[str, Any]:
|
|
entry: dict[str, Any] = {
|
|
"step": step,
|
|
"status": status,
|
|
"started_at": started_at,
|
|
"finished_at": finished_at,
|
|
"duration_ms": int((datetime.fromisoformat(finished_at) - datetime.fromisoformat(started_at)).total_seconds() * 1000),
|
|
}
|
|
if row_id:
|
|
entry["row_id"] = row_id
|
|
entry.update(extra)
|
|
return entry
|
|
|
|
|
|
def _step_label(step: str) -> str:
|
|
return {
|
|
"fetch_srm": "查询待检数据",
|
|
"pre_dify": "查询成分明细",
|
|
"call_dify": "调用 Dify 判定",
|
|
"writeback_srm": "写回 SRM",
|
|
"completed": "处理完成",
|
|
}.get(step, step)
|
|
|
|
|
|
def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
|
|
if len(s) <= max_len:
|
|
return s
|
|
return s[:max_len] + f"...[truncated, total {len(s)} chars]"
|
|
|
|
|
|
def _serialize_dify_inputs_for_log(inputs: dict[str, Any]) -> dict[str, Any]:
|
|
"""Log Dify request inputs; keep system_prompt intact for audit."""
|
|
out: dict[str, Any] = {}
|
|
for k, v in inputs.items():
|
|
if k == "system_prompt":
|
|
out[k] = str(v)
|
|
else:
|
|
out[k] = _truncate_str(str(v), 500)
|
|
return out
|
|
|
|
|
|
def _run_check_job_loop(
|
|
*,
|
|
conn_str: str,
|
|
run_no: str,
|
|
agent,
|
|
user: str,
|
|
wait_seconds: int,
|
|
run_id: int | None,
|
|
fetch_fn: Callable[[str], list[dict[str, Any]]],
|
|
build_record_fn: RecordBuilder,
|
|
writeback_fn: WritebackFunc,
|
|
writeback_sql: str = "",
|
|
row_id_key: str,
|
|
log_prefix: str,
|
|
fetch_sql: str = "",
|
|
max_rows: int = 0,
|
|
pre_dify_fn: PreDifyFunc | None = None,
|
|
dify_system_prompt: str = "",
|
|
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]:
|
|
from app.services.schedule.scheduler_service import is_run_cancelled
|
|
|
|
use_dify = agent is not None
|
|
if use_dify and not getattr(agent, "dify_api_key", None):
|
|
raise RuntimeError("dify_agent_id is set, but Dify api key is missing")
|
|
|
|
step_logs: list[dict[str, Any]] = []
|
|
details: list[dict[str, Any]] = []
|
|
success_count = 0
|
|
failed_count = 0
|
|
skipped_count = 0
|
|
judgement_stats = empty_judgement_stats()
|
|
current_step: dict[str, Any] | None = None
|
|
all_errors: list[str] = []
|
|
|
|
def _save_progress(total: int | None = None) -> None:
|
|
if run_id is None:
|
|
return
|
|
try:
|
|
from app import db
|
|
from app.models import ScheduleRun
|
|
|
|
progress_run = db.session.get(ScheduleRun, run_id)
|
|
if not progress_run or progress_run.status != "running":
|
|
return
|
|
if total is not None:
|
|
progress_run.total_count = max(0, int(total))
|
|
progress_run.success_count = success_count
|
|
progress_run.failed_count = failed_count
|
|
progress_run.skipped_count = skipped_count
|
|
summary = dict(progress_run.response_summary_json or {})
|
|
summary["file_judgement"] = dict(judgement_stats)
|
|
if current_step:
|
|
summary["current_step"] = dict(current_step)
|
|
progress_run.response_summary_json = summary
|
|
db.session.commit()
|
|
except Exception as progress_exc:
|
|
if current_app:
|
|
current_app.logger.warning("[%s] save progress failed run_id=%s error=%s", log_prefix, run_id, progress_exc)
|
|
|
|
def _set_current_step(step: str, row_id: str | None = None, total: int | None = None) -> None:
|
|
nonlocal current_step
|
|
current_step = {
|
|
"step": step,
|
|
"label": _step_label(step),
|
|
"row_id": row_id,
|
|
"started_at": _ts(),
|
|
"processed_count": success_count + failed_count + skipped_count,
|
|
"success_count": success_count,
|
|
"failed_count": failed_count,
|
|
"skipped_count": skipped_count,
|
|
}
|
|
_save_progress(total=total)
|
|
|
|
t0 = _ts()
|
|
try:
|
|
_set_current_step("fetch_srm")
|
|
rows = fetch_fn(conn_str)
|
|
if max_rows > 0:
|
|
rows = rows[:max_rows]
|
|
_save_progress(total=len(rows))
|
|
step_logs.append(_make_step(
|
|
"fetch_srm",
|
|
"success",
|
|
t0, _ts(),
|
|
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "row_count": len(rows)},
|
|
))
|
|
except Exception as fetch_exc:
|
|
step_logs.append(_make_step(
|
|
"fetch_srm",
|
|
"failed",
|
|
t0, _ts(),
|
|
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "error": str(fetch_exc)},
|
|
))
|
|
raise
|
|
|
|
for row in rows:
|
|
if run_id is not None and is_run_cancelled(run_id):
|
|
item = dict(row)
|
|
item.update({
|
|
"dify_result": "人工判定",
|
|
"dify_message": "排程已被删除,执行中断",
|
|
"writeback_srm": False,
|
|
"writeback_err": "排程已被删除,执行中断",
|
|
})
|
|
skipped_count += 1
|
|
details.append(item)
|
|
_save_progress()
|
|
continue
|
|
|
|
item = dict(row)
|
|
row_id_value = str(row.get(row_id_key, ""))
|
|
|
|
if pre_dify_fn:
|
|
t_pre = _ts()
|
|
try:
|
|
_set_current_step("pre_dify", row_id_value)
|
|
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
|
except Exception as pre_exc:
|
|
pre_result = {
|
|
"dify_result": "人工判定",
|
|
"dify_message": f"pre_dify执行异常:{pre_exc}",
|
|
"writeback_srm": False,
|
|
"writeback_err": str(pre_exc),
|
|
}
|
|
step_logs.append(_make_step("pre_dify", "failed", t_pre, _ts(), row_id=row_id_value, detail={"error": str(pre_exc)}))
|
|
|
|
if pre_result is not None:
|
|
item.update(pre_result)
|
|
failed_count += 1
|
|
all_errors.append(pre_result.get("writeback_err", ""))
|
|
details.append(item)
|
|
_save_progress()
|
|
continue
|
|
|
|
record_text, attachment_url = build_record_fn(conn_str, item, row_id_value)
|
|
|
|
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:
|
|
dify_inputs = {
|
|
"run_no": run_no,
|
|
"record": record_text,
|
|
"attachment_url": attachment_url,
|
|
}
|
|
prompt = str(dify_system_prompt or "").strip()
|
|
if prompt:
|
|
dify_inputs["system_prompt"] = prompt
|
|
t_dify = _ts()
|
|
try:
|
|
_set_current_step("call_dify", row_id_value)
|
|
dify_res = FileCheckService.evaluate(
|
|
agent=agent,
|
|
run_no=run_no,
|
|
record=record_text,
|
|
attachment_url=attachment_url,
|
|
system_prompt=prompt,
|
|
user=user,
|
|
timeout=(5, max(300, int(wait_seconds))),
|
|
)
|
|
except Exception as dify_exc:
|
|
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
|
"request": {
|
|
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
|
"agent_id": getattr(agent, "id", None),
|
|
},
|
|
"error": str(dify_exc),
|
|
}))
|
|
raise
|
|
|
|
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
|
|
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(
|
|
"[%s] %s=%s dify_result=%s dify_message=%s",
|
|
log_prefix, log_prefix, row_id_value, dify_result, dify_message,
|
|
)
|
|
|
|
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
|
"request": {
|
|
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
|
"agent_id": getattr(agent, "id", None),
|
|
},
|
|
"response": {
|
|
"provider": dify_res.get("provider") if isinstance(dify_res, dict) else None,
|
|
"dify_result": dify_result,
|
|
"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:
|
|
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
|
|
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))
|
|
t_wb = _ts()
|
|
try:
|
|
_set_current_step("writeback_srm", row_id_value)
|
|
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
|
step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={
|
|
"sql": _truncate_str(wb_sql, 500),
|
|
"params": [str(p) for p in wb_params],
|
|
}))
|
|
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"),
|
|
})
|
|
if dify_ok:
|
|
success_count += 1
|
|
except Exception as wb_exc:
|
|
if current_app:
|
|
current_app.logger.error("[%s] writeback failed %s=%s error=%s", log_prefix, log_prefix, row_id_value, wb_exc)
|
|
step_logs.append(_make_step("writeback_srm", "failed", t_wb, _ts(), row_id=row_id_value, detail={
|
|
"sql": _truncate_str(wb_sql, 500),
|
|
"params": [str(p) for p in wb_params],
|
|
"error": str(wb_exc),
|
|
}))
|
|
item.update({
|
|
"dify_result": dify_result,
|
|
"dify_message": dify_message,
|
|
"writeback_srm": False,
|
|
"writeback_err": str(wb_exc),
|
|
})
|
|
if dify_ok:
|
|
failed_count += 1
|
|
all_errors.append(f"writeback {log_prefix}={row_id_value}: {wb_exc}")
|
|
except Exception as exc:
|
|
dify_result = "人工判定"
|
|
dify_message = f"执行异常:{exc}"
|
|
item.update({
|
|
"dify_result": dify_result,
|
|
"dify_message": dify_message,
|
|
"writeback_srm": False,
|
|
"writeback_err": str(exc),
|
|
})
|
|
failed_count += 1
|
|
all_errors.append(str(exc))
|
|
t_wb2 = _ts()
|
|
try:
|
|
_set_current_step("writeback_srm", row_id_value)
|
|
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
|
step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"}))
|
|
item["writeback_srm"] = True
|
|
except Exception as wb_exc:
|
|
step_logs.append(_make_step("writeback_srm", "failed", t_wb2, _ts(), row_id=row_id_value, detail={"error": str(wb_exc), "note": "fallback writeback also failed"}))
|
|
item["writeback_srm"] = False
|
|
item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}"
|
|
|
|
details.append(item)
|
|
_save_progress()
|
|
|
|
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
|
|
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
|
|
|
|
_set_current_step("completed")
|
|
total_count = success_count + failed_count + skipped_count
|
|
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs
|