feat(schedule):cron支持图形,RoHS检核增加进度显示
This commit is contained in:
1 parent
6d0e78be81
commit
f5aac9c893
46 files changed
+1987
-221
No files matched your search
@@ -0,0 +1,188 @@
|
||||
"""
|
||||
services/rohs_check_tools/chat_log_run_binding.py
|
||||
|
||||
用途:将 RoHS 检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。
|
||||
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
|
||||
逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
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 _normalize_bind_text(text: str | None) -> str:
|
||||
"""折叠空白,便于 user_message 与 ChatLog.query 对齐。"""
|
||||
return re.sub(r"\s+", " ", str(text or "").strip())
|
||||
|
||||
|
||||
def merge_chat_log_bind_context(run: ScheduleRun | None, data: dict[str, Any] | None) -> None:
|
||||
"""
|
||||
在 ScheduleRun 上记录本轮问答的绑定上下文,供 ChatLog 落库时匹配。
|
||||
|
||||
Args:
|
||||
run: 新建或复用的检核批次。
|
||||
data: 启动检核 HTTP Body。
|
||||
"""
|
||||
if not run:
|
||||
return
|
||||
payload = data if isinstance(data, dict) else {}
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
turn_id = str(payload.get("hxops_turn_id") or "").strip()
|
||||
user_message = str(payload.get("user_message") or "").strip()
|
||||
if not session_id and not turn_id and not user_message:
|
||||
return
|
||||
|
||||
req = dict(run.api_request_json or {}) if isinstance(run.api_request_json, dict) else {}
|
||||
if session_id:
|
||||
req["bind_session_id"] = session_id
|
||||
req["hxops_session_id"] = session_id
|
||||
if turn_id:
|
||||
req["bind_turn_id"] = turn_id
|
||||
req["hxops_turn_id"] = turn_id
|
||||
if user_message:
|
||||
req["bind_user_message"] = user_message
|
||||
req["user_message"] = user_message
|
||||
if payload.get("conversation_id"):
|
||||
req["conversation_id"] = payload.get("conversation_id")
|
||||
req["bind_requested_at"] = datetime.utcnow().isoformat()
|
||||
run.api_request_json = req
|
||||
|
||||
|
||||
def resolve_run_id_for_chat_log(
|
||||
*,
|
||||
session_id: str | None = None,
|
||||
query: str | None = None,
|
||||
turn_id: str | None = None,
|
||||
) -> int | None:
|
||||
"""
|
||||
匹配本轮问答应对绑定的 RoHS 检核批次 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。
|
||||
"""
|
||||
session_key = str(session_id or "").strip()
|
||||
turn_key = str(turn_id or "").strip()
|
||||
query_key = _normalize_bind_text(query)
|
||||
|
||||
rows = (
|
||||
ScheduleRun.query.order_by(ScheduleRun.id.desc())
|
||||
.limit(120)
|
||||
.all()
|
||||
)
|
||||
|
||||
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:
|
||||
for run in rohs_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:
|
||||
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"))
|
||||
if bind_session == session_key and bind_query == query_key:
|
||||
return int(run.id)
|
||||
|
||||
if session_key and query_key:
|
||||
for run in rohs_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"))
|
||||
if bind_session == session_key and bind_query and (
|
||||
query_key in bind_query or bind_query in query_key
|
||||
):
|
||||
return int(run.id)
|
||||
|
||||
if session_key:
|
||||
cutoff = datetime.utcnow() - timedelta(minutes=15)
|
||||
for run in rohs_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:
|
||||
continue
|
||||
bind_at_raw = str(req.get("bind_requested_at") or run.started_at or "")
|
||||
try:
|
||||
bind_at = datetime.fromisoformat(bind_at_raw.replace("Z", ""))
|
||||
except ValueError:
|
||||
bind_at = run.started_at
|
||||
if bind_at and bind_at >= cutoff and run.status == "running":
|
||||
return int(run.id)
|
||||
|
||||
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",
|
||||
turn_key or None,
|
||||
session_key or None,
|
||||
len(query_key),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool:
|
||||
"""
|
||||
回写已有 ChatLog.run_id(workflow_finished 二次绑定)。
|
||||
|
||||
Returns:
|
||||
是否成功更新。
|
||||
"""
|
||||
if not chat_log_id or not run_id or run_id <= 0:
|
||||
return False
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
if not log:
|
||||
return False
|
||||
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):
|
||||
return False
|
||||
log.run_id = run_id
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
def bind_run_id_to_chat_log(*, chat_log: ChatLog | None, run_id: int | None) -> bool:
|
||||
"""
|
||||
将检核批次 ID 写入 ChatLog.run_id。
|
||||
|
||||
Returns:
|
||||
是否成功写入并提交。
|
||||
"""
|
||||
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):
|
||||
return False
|
||||
chat_log.run_id = run_id
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
__all__ = [
|
||||
"bind_run_id_to_chat_log",
|
||||
"merge_chat_log_bind_context",
|
||||
"resolve_run_id_for_chat_log",
|
||||
"update_chat_log_run_id",
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
services/rohs_check_tools/chat_log_run_resolver.py
|
||||
|
||||
用途:按 ChatLog.run_id 解析 RoHS 检核进度(按轮问答)。
|
||||
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
|
||||
逻辑:由 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(
|
||||
*,
|
||||
task_id: int,
|
||||
chat_log_id: int,
|
||||
) -> ScheduleRun | None:
|
||||
"""
|
||||
查询某条问答记录绑定的 RoHS 检核批次。
|
||||
|
||||
Args:
|
||||
task_id: ScheduleTask.id。
|
||||
chat_log_id: ChatLog.id。
|
||||
|
||||
Returns:
|
||||
绑定的 ScheduleRun,或 None。
|
||||
"""
|
||||
if chat_log_id <= 0 or task_id <= 0:
|
||||
return None
|
||||
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
if not log or not log.run_id:
|
||||
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)
|
||||
):
|
||||
return run
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"find_run_for_chat_log",
|
||||
]
|
||||
@@ -4,14 +4,27 @@ 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() -> dict[str, str]:
|
||||
"""Build Dify chat API inputs for RoHS Chatflow HTTP nodes."""
|
||||
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")
|
||||
@@ -23,12 +36,24 @@ def build_dify_chat_inputs() -> dict[str, str]:
|
||||
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",
|
||||
]
|
||||
@@ -0,0 +1,101 @@
|
||||
"""
|
||||
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.schedule_task_id(若缺失)。
|
||||
|
||||
Returns:
|
||||
新的 extra_config 副本;无变更时返回原 dict 浅拷贝。
|
||||
"""
|
||||
extra = dict(extra_config or {})
|
||||
tool_cfg = extra.get("tool_run_progress")
|
||||
if not isinstance(tool_cfg, dict):
|
||||
return extra
|
||||
|
||||
merged = dict(tool_cfg)
|
||||
merged.setdefault("log_progress_url", "/api/workspace/rohs-check/runs/for-log")
|
||||
merged.setdefault("detail_url_template", "/api/workspace/rohs-check/runs/{run_id}")
|
||||
|
||||
if not resolve_schedule_task_id_from_mapping(tool_cfg):
|
||||
task_id = resolve_default_rohs_schedule_task_id()
|
||||
if task_id:
|
||||
merged["schedule_task_id"] = task_id
|
||||
|
||||
extra["tool_run_progress"] = merged
|
||||
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",
|
||||
]
|
||||
Reference in new issue
Block a user