feat(rohs-check): 新增 RoHS 对话轮次注册与检核批次绑定功能
This commit is contained in:
1 parent
9cba517bff
commit
fa0cdee8df
20 files changed
+1050
-201
No files matched your search
@@ -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