feat(file-check): 新增文件检核相关 API 和工具,替换 RoHS 检核功能
This commit is contained in:
1 parent
fa0cdee8df
commit
24310b63b3
35 files changed
+3066
-659
No files matched your search
@@ -56,10 +56,10 @@ def create_app(config_name='default'):
|
||||
from app.api.schedule_admin import schedule_admin_bp
|
||||
from app.api.workspace_schedule import workspace_schedule_bp
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
|
||||
from app.api.workspace_rohs_check import workspace_rohs_check_bp
|
||||
from app.api.workspace_file_check import workspace_file_check_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.rohs_check_tools import rohs_check_bp
|
||||
from app.api.file_check_tools import file_check_bp
|
||||
from app.api.speech import speech_bp
|
||||
|
||||
# 聊天相关接口
|
||||
@@ -77,10 +77,10 @@ def create_app(config_name='default'):
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_rohs_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(rohs_check_bp, url_prefix='/api/rohs-check')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
|
||||
+21
-18
@@ -1084,6 +1084,7 @@ def chat_completions():
|
||||
name=getattr(agent, 'name', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
@@ -1174,31 +1175,33 @@ def chat_completions():
|
||||
else:
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.rohs_check_tools.dify_inputs import (
|
||||
build_dify_chat_inputs as build_rohs_dify_chat_inputs,
|
||||
is_rohs_check_chat_agent,
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
|
||||
from app.services.shipping_notice.dify_inputs import (
|
||||
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
|
||||
is_shipping_notice_chat_agent,
|
||||
)
|
||||
declares_file_check = agent_declares_file_check_progress(agent_proxy)
|
||||
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
|
||||
if is_shipping_notice_chat_agent(agent_proxy):
|
||||
dify_inputs = build_shipping_dify_chat_inputs()
|
||||
elif is_rohs_check_chat_agent(agent_proxy):
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
|
||||
elif declares_file_check or is_file_check_agent:
|
||||
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
|
||||
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
|
||||
if is_file_check_agent:
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_rohs_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
dify_inputs = build_rohs_dify_chat_inputs(
|
||||
hxops_session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
)
|
||||
register_file_check_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
@@ -1206,7 +1209,7 @@ def chat_completions():
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id if is_rohs_check_chat_agent(agent_proxy) else None,
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""
|
||||
backend/app/api/rohs_check_tools.py
|
||||
文件用途:RoHS Chatflow 显式 HTTP Tool API。
|
||||
backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 Chatflow 显式 HTTP Tool API。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,25 +16,24 @@ from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_rohs_check import serialize_rohs_judgement
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
|
||||
rohs_check_bp = Blueprint("rohs_check_tools", __name__)
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_ROHS_GLOBAL_LOCK_KEY = 8700000000
|
||||
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("ROHS_TOOLS_API_KEY")
|
||||
current_app.config.get("FILE_CHECK_TOOLS_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or current_app.config.get("SECRET_KEY")
|
||||
or "default-secret"
|
||||
@@ -48,19 +50,19 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[rohs-tool] download token validation failed: %s", exc)
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
configured = str(
|
||||
current_app.config.get("ROHS_TOOLS_API_KEY")
|
||||
current_app.config.get("FILE_CHECK_TOOLS_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
"FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
@@ -100,7 +102,7 @@ def _tool_error_code(exc: AppError) -> str:
|
||||
return exc.code
|
||||
|
||||
|
||||
@rohs_check_bp.errorhandler(AppError)
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
@@ -114,39 +116,28 @@ def _public_base_url() -> str:
|
||||
return resolve_HXOPS_TOOLS_API_BASE()
|
||||
|
||||
|
||||
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
|
||||
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 _acquire_rohs_start_lock() -> None:
|
||||
"""Serialize RoHS start checks across processes when PostgreSQL is used."""
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY})
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "rohs_check_excel",
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/rohs-check/tools/runs/{run.id}/excel?token={token}"
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@rohs_check_bp.before_request
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
@@ -166,7 +157,7 @@ def _serialize_tool_run(run: ScheduleRun) -> dict:
|
||||
"success_count": payload["success_count"],
|
||||
"failed_count": payload["failed_count"],
|
||||
"skipped_count": payload["skipped_count"],
|
||||
"judgement": serialize_rohs_judgement(payload),
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
@@ -204,41 +195,37 @@ def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None)
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
if not _is_rohs_check_task(task):
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_rohs_tasks():
|
||||
rows = ScheduleTask.query.order_by(ScheduleTask.created_at.desc()).all()
|
||||
tasks = []
|
||||
for task in rows:
|
||||
if not _is_rohs_check_task(task):
|
||||
continue
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks.append({
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
})
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_rohs_bind_payload(data: dict | None) -> dict:
|
||||
"""
|
||||
规范化启动检核 Body 中的绑定字段,兼容 Chatflow 漏传 hxops_session_id 的场景。
|
||||
|
||||
核心逻辑:若 hxops_session_id 为空但 conversation_id 实为 HXOPS session_id,则自动补齐。
|
||||
"""
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
@@ -254,25 +241,19 @@ def _normalize_rohs_bind_payload(data: dict | None) -> dict:
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_rohs_bind_payload(data: dict | None) -> dict:
|
||||
"""
|
||||
合并规范化与 turn 注册表推断,得到可用于 ChatLog 绑定的启动检核 Body。
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
核心逻辑:Dify HTTP 漏传 hxops_turn_id / hxops_session_id 时,从 HXOPS 侧登记轮次补齐。
|
||||
"""
|
||||
from app.services.rohs_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_rohs_bind_payload(data)
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
"""写入 ScheduleRun 绑定上下文,并同步 turn 注册表。"""
|
||||
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.rohs_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
@@ -280,31 +261,29 @@ def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_rohs_check():
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_rohs_bind_payload(request.get_json(silent=True) or {})
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_rohs_start_lock()
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.all()
|
||||
.first()
|
||||
)
|
||||
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
|
||||
if existing:
|
||||
_record_rohs_run_bind(existing, data)
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[rohs-tool-perf] run_rohs_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
@@ -333,7 +312,7 @@ def run_rohs_check():
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_rohs_run_bind(run, data)
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
@@ -348,7 +327,7 @@ def run_rohs_check():
|
||||
try:
|
||||
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
||||
except Exception as exc:
|
||||
current_app.logger.error("[rohs-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == "running":
|
||||
r.status = "failed"
|
||||
@@ -356,12 +335,12 @@ def run_rohs_check():
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
threading.Thread(target=_background, daemon=True, name=f"rohs-check-run-{run_id}").start()
|
||||
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[rohs-tool-perf] run_rohs_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
@@ -370,16 +349,16 @@ def run_rohs_check():
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_rohs_run(run_id: int):
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_rohs_runs():
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_runs():
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
raw_limit = request.args.get("limit", default=20, type=int)
|
||||
limit = max(1, min(int(raw_limit or 20), 100))
|
||||
@@ -389,12 +368,12 @@ def list_rohs_runs():
|
||||
else:
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
||||
runs = [_serialize_tool_run(row) for row in rows if _is_rohs_check_task(row.task)]
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_rohs_run_excel(run_id: int):
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
@@ -413,8 +392,8 @@ def download_rohs_run_excel(run_id: int):
|
||||
)
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_rohs_run(task_id: int):
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
@@ -422,6 +401,6 @@ def get_latest_rohs_run(task_id: int):
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def rohs_openapi_spec():
|
||||
return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -1624,11 +1624,9 @@ def get_agent_details(id):
|
||||
raise ForbiddenError('Access denied')
|
||||
extra_config = agent.extra_config or {}
|
||||
if isinstance(extra_config, dict):
|
||||
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
|
||||
from app.services.rohs_check_tools.task_resolver import enrich_tool_run_progress_extra
|
||||
from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check
|
||||
|
||||
if is_rohs_check_chat_agent(agent):
|
||||
extra_config = enrich_tool_run_progress_extra(extra_config)
|
||||
extra_config = enrich_agent_extra_if_file_check(agent)
|
||||
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
|
||||
|
||||
dify_parameters = None
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。
|
||||
逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
@@ -5,14 +12,12 @@ from io import BytesIO
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
from app.errors import NotFoundError, UnauthorizedError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.rohs_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_rohs_check_bp = Blueprint("workspace_rohs_check", __name__)
|
||||
|
||||
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
@@ -22,21 +27,12 @@ def _require_user():
|
||||
return user
|
||||
|
||||
|
||||
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
|
||||
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 serialize_rohs_judgement(payload: dict) -> dict:
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
judgement = response_summary.get("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), dict) else {}
|
||||
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),
|
||||
@@ -76,14 +72,14 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"title": payload.get("schedule_name") or "RoHS 文件检核",
|
||||
"title": payload.get("schedule_name") or "",
|
||||
"status": payload["status"],
|
||||
"total_count": total,
|
||||
"processed_count": processed,
|
||||
"success_count": success,
|
||||
"failed_count": failed,
|
||||
"skipped_count": skipped,
|
||||
"judgement": serialize_rohs_judgement(payload),
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"current_step": serialize_current_step(payload),
|
||||
"progress_percent": percent,
|
||||
"started_at": payload.get("started_at"),
|
||||
@@ -93,7 +89,7 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": f"/api/workspace/rohs-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
"download_url": f"/api/workspace/file-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
@@ -106,8 +102,8 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
}
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/for-log", methods=["GET"])
|
||||
def workspace_rohs_run_for_log():
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
@@ -125,16 +121,16 @@ def workspace_rohs_run_for_log():
|
||||
})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/for-session", methods=["GET"])
|
||||
def workspace_rohs_run_for_session():
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
|
||||
def workspace_rohs_active_run():
|
||||
"""查询当前进行中的 RoHS 检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
conversation_id = str(request.args.get("conversation_id") or "").strip()
|
||||
@@ -146,13 +142,11 @@ def workspace_rohs_active_run():
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
# 已按 schedule_task_id 过滤;不再比对 conversation_id(HXOPS session_id ≠ Dify sys.conversation_id)
|
||||
run = next((row for row in rows if _is_rohs_check_task(row.task)), None)
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((
|
||||
row for row in rows
|
||||
if _is_rohs_check_task(row.task)
|
||||
and (
|
||||
if (
|
||||
not conversation_id
|
||||
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
|
||||
)
|
||||
@@ -160,25 +154,21 @@ def workspace_rohs_active_run():
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_rohs_run_detail(run_id: int):
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_file_check_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not _is_rohs_check_task(run.task):
|
||||
raise ForbiddenError("Forbidden")
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_rohs_run_excel(run_id: int):
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_file_check_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not _is_rohs_check_task(run.task):
|
||||
raise ForbiddenError("Forbidden")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("excel_not_found")
|
||||
return send_file(
|
||||
@@ -109,14 +109,14 @@ class Config:
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
# RoHS 检核 Chatflow Tool API
|
||||
ROHS_TOOLS_API_KEY = os.getenv('ROHS_TOOLS_API_KEY')
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOLS_API_KEY = os.getenv('FILE_CHECK_TOOLS_API_KEY')
|
||||
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
|
||||
@@ -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)
|
||||
+14
-34
@@ -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()
|
||||
+5
-11
@@ -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
|
||||
|
||||
+10
-18
@@ -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",␍
|
||||
]␍
|
||||
␍
|
||||
+51
-37
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -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",
|
||||
]
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user