feat(file-check): 新增历史检核报告检索功能及相关 API

This commit is contained in:
hugo committed 2026-06-16 13:32:00 +08:00
1 parent 29a7704d46
commit f6fe56f205
16 files changed
+1060 -163

No files matched your search

@@ -0,0 +1,235 @@
"""
services/file_check_tools/history_search_service.py
用途:按 task_id 解析检核任务绑定的知识库 Dataset,调用 Dify 检索 API 供 Chatflow 历史查询。
依赖:ScheduleTask、KbGroup、KbDifySyncService、errors。
逻辑:file_check_tools.search_file_check_history 路由调用本模块;Dify 画布仅调 Tool,不绑 Knowledge Retrieval。
"""
from __future__ import annotations
import re
from typing import Any
from app import db
from app.errors import NotFoundError, ServiceUnavailableError, ValidationError
from app.models import KbGroup, ScheduleTask
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncError, KbDifySyncService
DEFAULT_TOP_K = 5
MAX_TOP_K = 20
MIN_TOP_K = 1
DEFAULT_SCORE_THRESHOLD = 0.3
def _normalize_query(raw: str | None) -> str:
return str(raw or "").strip()
def _normalize_top_k(raw: int | str | None) -> int:
try:
value = int(raw if raw is not None else DEFAULT_TOP_K)
except (TypeError, ValueError):
value = DEFAULT_TOP_K
return max(MIN_TOP_K, min(value, MAX_TOP_K))
def _normalize_score_threshold(raw: float | int | str | None) -> float:
try:
value = float(raw if raw is not None else DEFAULT_SCORE_THRESHOLD)
except (TypeError, ValueError):
value = DEFAULT_SCORE_THRESHOLD
return max(0.0, min(value, 1.0))
def resolve_history_kb_context(task: ScheduleTask) -> tuple[KbGroup, str]:
"""
解析检核任务对应的知识库分组与 Dify Dataset ID。
核心逻辑:task.kb_sync_enabled + kb_group_id → KbGroup.dify_dataset_id。
Args:
task: 已存在的 ScheduleTask。
Returns:
(KbGroup, dify_dataset_id) 元组。
Raises:
ValidationError: 未启用知识库同步或未绑定分组 / Dataset。
NotFoundError: 知识库分组不存在或已停用。
"""
if not bool(getattr(task, "kb_sync_enabled", False)):
raise ValidationError("kb_not_configured")
group_id = getattr(task, "kb_group_id", None)
if not group_id:
raise ValidationError("kb_not_configured")
group = db.session.get(KbGroup, int(group_id))
if not group or not group.is_active:
raise NotFoundError("kb_group_not_found")
dataset_id = str(group.dify_dataset_id or "").strip()
if not dataset_id:
raise ValidationError("kb_dataset_not_bound")
return group, dataset_id
def _extract_run_no(document_name: str | None, metadata: dict | None) -> str | None:
meta = metadata if isinstance(metadata, dict) else {}
run_no = str(meta.get("run_no") or "").strip()
if run_no:
return run_no
title = str(document_name or "").strip()
if not title:
return None
if "_" in title:
suffix = title.rsplit("_", 1)[-1].strip()
if suffix:
return suffix
match = re.search(r"RUN[\w-]+", title, flags=re.I)
return match.group(0) if match else None
def _segment_content(record: dict[str, Any]) -> str:
segment = record.get("segment") if isinstance(record.get("segment"), dict) else {}
for key in ("content", "sign_content", "answer"):
text = str(segment.get(key) or record.get(key) or "").strip()
if text:
return text
return ""
def _segment_score(record: dict[str, Any]) -> float | None:
for key in ("score",):
raw = record.get(key)
if raw is None and isinstance(record.get("segment"), dict):
raw = record["segment"].get("score")
if raw is None:
continue
try:
return float(raw)
except (TypeError, ValueError):
continue
return None
def _segment_document_meta(record: dict[str, Any]) -> dict[str, Any]:
segment = record.get("segment") if isinstance(record.get("segment"), dict) else {}
document = record.get("document") if isinstance(record.get("document"), dict) else {}
document_name = (
segment.get("document_name")
or document.get("name")
or record.get("document_name")
or record.get("title")
)
metadata = segment.get("metadata") or document.get("metadata") or record.get("metadata") or {}
if not isinstance(metadata, dict):
metadata = {}
return {
"document_id": segment.get("document_id") or document.get("id") or record.get("document_id"),
"document_title": str(document_name or "").strip() or None,
"run_no": _extract_run_no(str(document_name or ""), metadata),
"metadata": metadata,
}
def normalize_retrieve_records(payload: dict[str, Any] | None) -> list[dict[str, Any]]:
"""
将 Dify Dataset retrieve 响应规范为 Chatflow / LLM 可用的片段列表。
Args:
payload: Dify `/datasets/{id}/retrieve` 原始 JSON。
Returns:
含 content、score、document_title、run_no 等字段的 dict 列表。
"""
data = payload if isinstance(payload, dict) else {}
records = data.get("records")
if not isinstance(records, list):
records = data.get("data") if isinstance(data.get("data"), list) else []
segments: list[dict[str, Any]] = []
for item in records:
if not isinstance(item, dict):
continue
content = _segment_content(item)
if not content:
continue
meta = _segment_document_meta(item)
segments.append({
"content": content,
"score": _segment_score(item),
"document_id": meta.get("document_id"),
"document_title": meta.get("document_title"),
"run_no": meta.get("run_no"),
"metadata": meta.get("metadata") or {},
})
return segments
def search_file_check_history(
*,
task_id: int,
query: str,
top_k: int | None = None,
score_threshold: float | None = None,
) -> dict[str, Any]:
"""
按检核任务 ID 检索已同步至 Dify 的历史检核报告片段。
核心逻辑:ScheduleTask → KbGroup → dify_dataset_id → Dify retrieve API。
Args:
task_id: ScheduleTask.id(Agent 绑定的 schedule_task_id)。
query: 用户自然语言检索问题。
top_k: 返回片段数,默认 5,最大 20。
score_threshold: 相似度阈值,默认 0.3。
Returns:
含 task_id、task_name、count、segments 的 dict。
Raises:
NotFoundError: 检核任务或知识库分组不存在。
ValidationError: query 为空、知识库未配置或 Dataset 未绑定。
ServiceUnavailableError: Dify 检索失败或未配置。
"""
normalized_query = _normalize_query(query)
if not normalized_query:
raise ValidationError("query_required")
task = db.session.get(ScheduleTask, int(task_id))
if not task:
raise NotFoundError("task_not_found")
group, dataset_id = resolve_history_kb_context(task)
effective_top_k = _normalize_top_k(top_k)
effective_threshold = _normalize_score_threshold(score_threshold)
service = KbDifySyncService()
try:
raw = service.retrieve_dataset(
dataset_id=dataset_id,
query=normalized_query,
top_k=effective_top_k,
score_threshold=effective_threshold,
)
except KbDifySyncError as exc:
raise ServiceUnavailableError("dify_retrieve_failed") from exc
segments = normalize_retrieve_records(raw if isinstance(raw, dict) else {})
return {
"task_id": task.id,
"task_name": task.name,
"kb_group_id": group.id,
"kb_group_name": group.name,
"dify_dataset_id": dataset_id,
"query": normalized_query,
"count": len(segments),
"segments": segments,
}
__all__ = [
"DEFAULT_SCORE_THRESHOLD",
"DEFAULT_TOP_K",
"MAX_TOP_K",
"normalize_retrieve_records",
"resolve_history_kb_context",
"search_file_check_history",
]
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "HXOPS File Check Tool API",
"description": "文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
"description": "文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告、检索历史检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
"version": "1.0.0"
},
"servers": [
@@ -239,6 +239,50 @@
}
}
},
"/api/file-check/tools/history/search": {
"post": {
"operationId": "search_file_check_history",
"summary": "检索历史检核报告",
"description": "按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset,返回语义检索片段;供 Chatflow history_report_query 分支调用。",
"tags": [
"File Check"
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HistorySearchRequest"
}
}
}
},
"responses": {
"200": {
"description": "成功(count=0 表示未命中片段)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HistorySearchResponse"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
}
}
},
"/api/file-check/tools/runs/{run_id}/excel": {
"get": {
"operationId": "download_file_check_run_excel",
@@ -596,6 +640,121 @@
}
}
},
"HistorySearchRequest": {
"type": "object",
"required": [
"task_id",
"query"
],
"properties": {
"task_id": {
"type": "integer",
"example": 12,
"description": "检核任务 ID(Agent 绑定的 schedule_task_id)"
},
"query": {
"type": "string",
"example": "上周有哪些不合格项",
"description": "用户自然语言检索问题"
},
"top_k": {
"type": "integer",
"minimum": 1,
"maximum": 20,
"default": 5,
"description": "返回片段数,默认 5"
},
"score_threshold": {
"type": "number",
"minimum": 0,
"maximum": 1,
"default": 0.3,
"description": "相似度阈值,默认 0.3"
}
}
},
"HistorySearchSegment": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "检索片段正文"
},
"score": {
"type": "number",
"nullable": true,
"description": "相似度分数"
},
"document_id": {
"type": "string",
"nullable": true
},
"document_title": {
"type": "string",
"nullable": true,
"example": "RoHS检核_RUN202606090001"
},
"run_no": {
"type": "string",
"nullable": true,
"example": "RUN202606090001"
},
"metadata": {
"type": "object",
"additionalProperties": true
}
}
},
"HistorySearchResponse": {
"type": "object",
"required": [
"ok",
"task_id",
"query",
"count",
"segments"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"task_id": {
"type": "integer",
"example": 12
},
"task_name": {
"type": "string",
"example": "RoHS 文件检核"
},
"kb_group_id": {
"type": "integer",
"example": 3
},
"kb_group_name": {
"type": "string",
"example": "RoHS 检核报告"
},
"dify_dataset_id": {
"type": "string",
"example": "ds-uuid"
},
"query": {
"type": "string",
"example": "上周有哪些不合格项"
},
"count": {
"type": "integer",
"example": 2
},
"segments": {
"type": "array",
"items": {
"$ref": "#/components/schemas/HistorySearchSegment"
}
}
}
},
"ErrorResponse": {
"type": "object",
"required": [