feat(rohs-check): 新增 RoHS 对话轮次注册与检核批次绑定功能
This commit is contained in:
1 parent
9cba517bff
commit
fa0cdee8df
20 files changed
+1050
-201
No files matched your search
@@ -1186,6 +1186,15 @@ def chat_completions():
|
||||
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
|
||||
|
||||
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,
|
||||
|
||||
@@ -889,12 +889,24 @@ def submit_document_clean(document_id: int):
|
||||
raise ValidationError('当前文档暂无可清洗版本')
|
||||
|
||||
latest_clean_job = _latest_job_for_version(version.id, 'clean')
|
||||
if latest_clean_job and latest_clean_job.status in ('queued', 'running'):
|
||||
if latest_clean_job and latest_clean_job.status == 'running':
|
||||
payload = _serialize_job(latest_clean_job)
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['message'] = latest_clean_job.message or '清洗任务已在处理中'
|
||||
payload['queue_result'] = 'already_running'
|
||||
payload['message'] = latest_clean_job.message or '清洗任务正在执行中'
|
||||
return jsonify(payload), 202
|
||||
if latest_clean_job and latest_clean_job.status == 'queued':
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job
|
||||
|
||||
_ok, _message = run_clean_job(latest_clean_job.id)
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(KbJob, latest_clean_job.id)
|
||||
payload = _serialize_job(refreshed) if refreshed else {'id': latest_clean_job.id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'inline_on_manual'
|
||||
payload['message'] = (refreshed.message if refreshed else None) or _message or '清洗任务已执行'
|
||||
status_code = 200 if refreshed and refreshed.status == 'success' else 202
|
||||
return jsonify(payload), status_code
|
||||
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
|
||||
@@ -233,11 +233,58 @@ def list_rohs_tasks():
|
||||
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,则自动补齐。
|
||||
"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
return payload
|
||||
conversation_id = str(payload.get("conversation_id") or "").strip()
|
||||
if not conversation_id:
|
||||
return payload
|
||||
from app.models import ChatSession
|
||||
|
||||
session = ChatSession.query.filter_by(session_id=conversation_id).first()
|
||||
if session:
|
||||
payload["hxops_session_id"] = conversation_id
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_rohs_bind_payload(data: dict | None) -> dict:
|
||||
"""
|
||||
合并规范化与 turn 注册表推断,得到可用于 ChatLog 绑定的启动检核 Body。
|
||||
|
||||
核心逻辑: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)
|
||||
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
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
if turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_rohs_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
perf_started = time.perf_counter()
|
||||
data = request.get_json(silent=True) or {}
|
||||
data = _prepare_rohs_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
@@ -252,9 +299,7 @@ def run_rohs_check():
|
||||
)
|
||||
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
|
||||
if existing:
|
||||
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
|
||||
merge_chat_log_bind_context(existing, data)
|
||||
_record_rohs_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)
|
||||
@@ -288,9 +333,7 @@ def run_rohs_check():
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
_record_rohs_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
@@ -16,6 +16,12 @@ 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 (
|
||||
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
|
||||
|
||||
|
||||
@@ -92,6 +98,9 @@ def resolve_run_id_for_chat_log(
|
||||
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:
|
||||
req = _req(run)
|
||||
bind_turn = str(req.get("bind_turn_id") or req.get("hxops_turn_id") or "").strip()
|
||||
@@ -131,6 +140,10 @@ def resolve_run_id_for_chat_log(
|
||||
if bind_at and bind_at >= cutoff and run.status == "running":
|
||||
return int(run.id)
|
||||
|
||||
registry_run_id = resolve_run_id_by_session_query(session_key, query_key)
|
||||
if registry_run_id:
|
||||
return registry_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",
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
services/rohs_check_tools/chat_turn_registry.py
|
||||
|
||||
用途:RoHS 对话轮次与检核批次的内存注册表(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
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
_REGISTRY_TTL = timedelta(hours=2)
|
||||
_MAX_ENTRIES = 500
|
||||
|
||||
|
||||
def _normalize_text(text: str | None) -> str:
|
||||
"""折叠空白,便于 query / user_message 对齐。"""
|
||||
return re.sub(r"\s+", " ", str(text or "").strip())
|
||||
|
||||
|
||||
@dataclass
|
||||
class RohsChatTurn:
|
||||
"""单轮 RoHS 对话的绑定上下文。"""
|
||||
|
||||
turn_id: str
|
||||
session_id: str
|
||||
user_id: int
|
||||
agent_id: int
|
||||
query: str
|
||||
created_at: datetime
|
||||
run_id: int | None = None
|
||||
|
||||
|
||||
_lock = Lock()
|
||||
_turns_by_id: dict[str, RohsChatTurn] = {}
|
||||
|
||||
|
||||
def _prune_locked(now: datetime | None = None) -> None:
|
||||
"""清理过期或超量的轮次记录。"""
|
||||
current = now or datetime.utcnow()
|
||||
cutoff = current - _REGISTRY_TTL
|
||||
expired = [key for key, item in _turns_by_id.items() if item.created_at < cutoff]
|
||||
for key in expired:
|
||||
_turns_by_id.pop(key, None)
|
||||
if len(_turns_by_id) <= _MAX_ENTRIES:
|
||||
return
|
||||
ordered = sorted(_turns_by_id.items(), key=lambda pair: pair[1].created_at)
|
||||
overflow = len(_turns_by_id) - _MAX_ENTRIES
|
||||
for key, _ in ordered[:overflow]:
|
||||
_turns_by_id.pop(key, None)
|
||||
|
||||
|
||||
def register_rohs_chat_turn(
|
||||
*,
|
||||
turn_id: str,
|
||||
session_id: str,
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
query: str,
|
||||
) -> None:
|
||||
"""
|
||||
登记本轮 RoHS 对话上下文(chat API 在调用 Dify 前执行)。
|
||||
|
||||
Args:
|
||||
turn_id: 本轮唯一标识(hxops_turn_id)。
|
||||
session_id: ChatSession.session_id。
|
||||
user_id: 当前用户 ID。
|
||||
agent_id: 当前 Agent ID。
|
||||
query: 用户输入原文。
|
||||
"""
|
||||
turn_key = str(turn_id or "").strip()
|
||||
session_key = str(session_id or "").strip()
|
||||
if not turn_key or not session_key:
|
||||
return
|
||||
item = RohsChatTurn(
|
||||
turn_id=turn_key,
|
||||
session_id=session_key,
|
||||
user_id=int(user_id),
|
||||
agent_id=int(agent_id),
|
||||
query=str(query or ""),
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
with _lock:
|
||||
_turns_by_id[turn_key] = item
|
||||
_prune_locked()
|
||||
|
||||
|
||||
def attach_run_to_turn(turn_id: str, run_id: int) -> bool:
|
||||
"""
|
||||
将检核批次 ID 关联到已登记轮次。
|
||||
|
||||
Returns:
|
||||
是否成功关联。
|
||||
"""
|
||||
turn_key = str(turn_id or "").strip()
|
||||
if not turn_key or run_id <= 0:
|
||||
return False
|
||||
with _lock:
|
||||
item = _turns_by_id.get(turn_key)
|
||||
if not item:
|
||||
return False
|
||||
item.run_id = int(run_id)
|
||||
return True
|
||||
|
||||
|
||||
def resolve_run_id_by_turn(turn_id: str | None) -> int | None:
|
||||
"""按 turn_id 读取已关联的检核批次 ID。"""
|
||||
turn_key = str(turn_id or "").strip()
|
||||
if not turn_key:
|
||||
return None
|
||||
with _lock:
|
||||
item = _turns_by_id.get(turn_key)
|
||||
if not item or not item.run_id or item.run_id <= 0:
|
||||
return None
|
||||
return int(item.run_id)
|
||||
|
||||
|
||||
def infer_bind_context_for_run_request(data: dict[str, Any] | None) -> dict[str, str]:
|
||||
"""
|
||||
为启动检核 HTTP Body 推断缺失的 hxops_session_id / hxops_turn_id。
|
||||
|
||||
核心逻辑:Dify HTTP 常漏传绑定字段时,用近期未绑定轮次 + query 模糊匹配补齐。
|
||||
|
||||
Args:
|
||||
data: 启动检核请求 Body。
|
||||
|
||||
Returns:
|
||||
可合并进 Body 的绑定字段 dict(可能为空)。
|
||||
"""
|
||||
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()
|
||||
if session_id and turn_id:
|
||||
return {}
|
||||
|
||||
user_message = _normalize_text(payload.get("user_message"))
|
||||
now = datetime.utcnow()
|
||||
recent_cutoff = now - timedelta(minutes=15)
|
||||
|
||||
with _lock:
|
||||
_prune_locked(now)
|
||||
candidates = [
|
||||
item for item in _turns_by_id.values()
|
||||
if item.created_at >= recent_cutoff
|
||||
]
|
||||
|
||||
if turn_id and not session_id:
|
||||
matched = next((item for item in candidates if item.turn_id == turn_id), None)
|
||||
if matched:
|
||||
return {"hxops_session_id": matched.session_id, "hxops_turn_id": matched.turn_id}
|
||||
|
||||
if session_id and not turn_id:
|
||||
scoped = [item for item in candidates if item.session_id == session_id]
|
||||
if user_message:
|
||||
exact = next(
|
||||
(item for item in scoped if _normalize_text(item.query) == user_message),
|
||||
None,
|
||||
)
|
||||
if exact:
|
||||
return {"hxops_session_id": exact.session_id, "hxops_turn_id": exact.turn_id}
|
||||
unbound = [item for item in scoped if not item.run_id]
|
||||
if len(unbound) == 1:
|
||||
item = unbound[0]
|
||||
return {"hxops_session_id": item.session_id, "hxops_turn_id": item.turn_id}
|
||||
|
||||
if not session_id and not turn_id:
|
||||
if user_message:
|
||||
exact = next(
|
||||
(item for item in candidates if _normalize_text(item.query) == user_message and not item.run_id),
|
||||
None,
|
||||
)
|
||||
if exact:
|
||||
return {"hxops_session_id": exact.session_id, "hxops_turn_id": exact.turn_id}
|
||||
unbound = [item for item in candidates if not item.run_id]
|
||||
if len(unbound) == 1:
|
||||
item = unbound[0]
|
||||
return {"hxops_session_id": item.session_id, "hxops_turn_id": item.turn_id}
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
def resolve_run_id_by_session_query(
|
||||
session_id: str | None,
|
||||
query: str | None,
|
||||
) -> int | None:
|
||||
"""按 session_id + query 从注册表读取已关联 run_id。"""
|
||||
session_key = str(session_id or "").strip()
|
||||
query_key = _normalize_text(query)
|
||||
if not session_key:
|
||||
return None
|
||||
now = datetime.utcnow()
|
||||
recent_cutoff = now - timedelta(minutes=15)
|
||||
with _lock:
|
||||
candidates = [
|
||||
item for item in _turns_by_id.values()
|
||||
if item.session_id == session_key and item.created_at >= recent_cutoff and item.run_id
|
||||
]
|
||||
if query_key:
|
||||
exact = next((item for item in candidates if _normalize_text(item.query) == query_key), None)
|
||||
if exact and exact.run_id:
|
||||
return int(exact.run_id)
|
||||
if len(candidates) == 1 and candidates[0].run_id:
|
||||
return int(candidates[0].run_id)
|
||||
return None
|
||||
|
||||
|
||||
def clear_registry_for_tests() -> None:
|
||||
"""测试专用:清空注册表。"""
|
||||
with _lock:
|
||||
_turns_by_id.clear()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"attach_run_to_turn",
|
||||
"clear_registry_for_tests",
|
||||
"infer_bind_context_for_run_request",
|
||||
"register_rohs_chat_turn",
|
||||
"resolve_run_id_by_session_query",
|
||||
"resolve_run_id_by_turn",
|
||||
]
|
||||
@@ -69,26 +69,39 @@ def resolve_default_rohs_schedule_task_id() -> int | None:
|
||||
|
||||
def enrich_tool_run_progress_extra(extra_config: dict | None) -> dict:
|
||||
"""
|
||||
为 RoHS Agent 的 extra_config 补全 tool_run_progress.schedule_task_id(若缺失)。
|
||||
为 RoHS Agent 的 extra_config 补全 tool_run_progress 能力与默认轮询配置。
|
||||
|
||||
核心逻辑:RoHS 对话 Agent 自动挂载 tool_run_progress 能力,避免漏配 capabilities 导致进度卡片不显示。
|
||||
|
||||
Returns:
|
||||
新的 extra_config 副本;无变更时返回原 dict 浅拷贝。
|
||||
新的 extra_config 副本。
|
||||
"""
|
||||
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 = 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(tool_cfg):
|
||||
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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user