feat(file-check): 新增文件检核相关 API 和工具,替换 RoHS 检核功能

This commit is contained in:
hugo committed 2026-06-16 09:28:37 +08:00
1 parent fa0cdee8df
commit 24310b63b3
35 files changed
+3066 -659

No files matched your search

+8 -8
View File
@@ -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,
@@ -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 {
@@ -0,0 +1 @@
"""文件检核 Chatflow 工具包。"""
@@ -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)
@@ -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()
@@ -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
@@ -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",
]
@@ -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": "<ScheduleTask.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",␍
]␍
␍
@@ -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"
}
}
}
@@ -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")
@@ -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",
]
@@ -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",
]
Whitespace-only changes.
@@ -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()
@@ -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",
]
@@ -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",
]
+3 -3
View File
@@ -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,