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

+32
View File
@@ -87,6 +87,11 @@ def _tool_error_code(exc: AppError) -> str:
"run_not_found",
"excel_not_ready",
"kb_sync_failed",
"query_required",
"kb_not_configured",
"kb_group_not_found",
"kb_dataset_not_bound",
"dify_retrieve_failed",
}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
@@ -401,6 +406,33 @@ def get_latest_file_check_run(task_id: int):
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
@file_check_bp.route("/tools/history/search", methods=["POST"])
def search_file_check_history():
"""
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
"""
data = request.get_json(silent=True) or {}
raw_task_id = data.get("task_id")
try:
task_id = int(raw_task_id)
except (TypeError, ValueError):
raise ValidationError("task_id_invalid")
if task_id <= 0:
raise ValidationError("task_id_invalid")
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
result = run_history_search(
task_id=task_id,
query=str(data.get("query") or ""),
top_k=data.get("top_k"),
score_threshold=data.get("score_threshold"),
)
return jsonify({"ok": True, **result})
@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()))
@@ -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": [
@@ -198,6 +198,47 @@ class KbDifySyncService:
json=payload,
)
def retrieve_dataset(
self,
*,
dataset_id: str,
query: str,
top_k: int = 5,
score_threshold: float | None = 0.3,
) -> dict:
"""
调用 Dify Dataset 检索 API,供文件检核历史查询 Tool 使用。
Args:
dataset_id: Dify Dataset UUID。
query: 检索问题。
top_k: 返回片段数(1–20)。
score_threshold: 相似度阈值;为 None 时不启用阈值过滤。
Returns:
Dify retrieve 原始 JSON(含 records)。
"""
normalized_query = str(query or '').strip()
if not normalized_query:
raise KbDifySyncError('检索 query 不能为空')
normalized_top_k = max(1, min(int(top_k or 5), 20))
retrieval_model: dict[str, object] = {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': normalized_top_k,
}
if score_threshold is None:
retrieval_model['score_threshold_enabled'] = False
retrieval_model['score_threshold'] = None
else:
retrieval_model['score_threshold_enabled'] = True
retrieval_model['score_threshold'] = max(0.0, min(float(score_threshold), 1.0))
payload = {
'query': normalized_query,
'retrieval_model': retrieval_model,
}
return self._request('POST', f'/datasets/{dataset_id}/retrieve', json=payload)
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
+1
View File
@@ -157,6 +157,7 @@ def sync_schedule_run_excel_to_kb(
"document_version_id": version.id,
"source_file_name": source_file_name,
"source_type": "schedule_run",
"schedule_task_id": task.id,
"schedule_run_id": run.id,
"run_no": run.run_no,
"auto_sync_dify": True,
+105
View File
@@ -1428,3 +1428,108 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
assert chat_log_id
log = db.session.get(ChatLog, chat_log_id)
assert log.run_id == run_id
def test_history_search_normalizes_dify_records():
from app.services.file_check_tools.history_search_service import normalize_retrieve_records
payload = normalize_retrieve_records({
'records': [
{
'score': 0.91,
'segment': {
'content': 'Pb 超标',
'document_name': 'RoHS检核_RUN202606090001',
'metadata': {'run_no': 'RUN202606090001'},
},
},
],
})
assert len(payload) == 1
assert payload[0]['content'] == 'Pb 超标'
assert payload[0]['run_no'] == 'RUN202606090001'
assert payload[0]['document_title'] == 'RoHS检核_RUN202606090001'
def test_history_search_tool_requires_query(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/file-check/tools/history/search',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'query': ' '},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'query_required'
def test_history_search_tool_requires_kb_config(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/file-check/tools/history/search',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'query': '上周有哪些不合格'},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'kb_not_configured'
def test_history_search_tool_success(app, client, monkeypatch):
from app.models import KbGroup
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
group = KbGroup(name='RoHS KB Search', is_active=True, dify_dataset_id='ds-search-001')
db.session.add(group)
db.session.flush()
task.kb_sync_enabled = True
task.kb_group_id = group.id
db.session.commit()
task_id = task.id
def _fake_retrieve(self, **kwargs):
assert kwargs['dataset_id'] == 'ds-search-001'
assert kwargs['query'] == '上周有哪些不合格'
return {
'records': [
{
'score': 0.88,
'segment': {
'content': '供应商 A 铅含量不合格',
'document_name': f'RoHS 自动检核_RUN-TEST-001',
},
},
],
}
monkeypatch.setattr(
'app.services.knowledge_cleaning.dify_sync_service.KbDifySyncService.retrieve_dataset',
_fake_retrieve,
)
res = client.post(
'/api/file-check/tools/history/search',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'query': '上周有哪些不合格', 'top_k': 3},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['task_id'] == task_id
assert data['count'] == 1
assert data['segments'][0]['content'] == '供应商 A 铅含量不合格'
assert data['dify_dataset_id'] == 'ds-search-001'
+1 -1
View File
@@ -25,7 +25,7 @@
### 3.x 文件检核(file_check)补充需求
- **核心目标**:提供通用文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。
- **通用域**:`FileCheckService` + `/api/file-check` Tool API + 单套 Dify Chatflow「文件检核助手」;RoHS、MSDS 等差异仅在排程 SQL、`task_id` 与判定 Workflow。
- **通用域**:`FileCheckService` + `/api/file-check` Tool API + 单套 Dify Chatflow「文件检核助手」;RoHS、MSDS 等差异仅在排程 SQL、`task_id` 与判定 Workflow;历史检索走 `search_file_check_history` Tool,按运行时 `task_id` 解析 Dataset。
- **多 Agent**:RoHS / MSDS 等工作台 Agent 共用同一 `dify_app_id`,HXOPS 按 `extra_config.tool_run_progress.schedule_task_id` 注入 `task_id`。
- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 历史分支按 `task_id` 选择知识库 Dataset。
- Dify Chatflow 编排与 OpenAPI 导入见 [docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md)。
+270 -109
View File
@@ -1,4 +1,4 @@
> **通用化说明**:本手册适用于 RoHS、MSDS 等所有文件检核类型。多个 Agent 共用同一 Dify Chatflow;HXOPS 按 Agent `extra_config.tool_run_progress.schedule_task_id` 注入不同 `task_id`。历史查询按 `task_id` 分支选择知识库 Dataset。
> **通用化说明**:本手册适用于 RoHS、MSDS 等所有文件检核类型。多个 Agent 共用同一 Dify Chatflow;HXOPS 按 Agent `extra_config.tool_run_progress.schedule_task_id` 注入不同 `task_id`。历史查询通过 Tool API `search_file_check_history` 按运行时 `task_id` 解析 Dataset,画布无需 Knowledge Retrieval 节点。
> **唯一文档**:编排、OpenAPI Tool 配置、部署、Agent 配置、验证与排错 **均在本文件**;勿再维护 `rohs_chatflow_*` 或 `ops/file_check_deploy_migration.md`。
# 文件检核 Chatflow — 完整手册
@@ -15,14 +15,14 @@
2. **查询检核** — 查看检核进度、统计摘要、失败原因
3. **获取报告** — 下载检核结果 Excel
4. **知识库同步** — 查看检核报告是否已入库
5. **历史查询** — 基于已同步知识库检索历史检核报告、异常、供应商或料号记录
5. **历史查询** — 通过 Tool API 检索已同步知识库中的历史检核报告、异常、供应商或料号记录
**关于执行方式**:无论是定时触发、后台批量还是对话中即时发起,对用户统一称为 **检核**。当前一期由 HXOPS 后台检核任务承载执行,Chatflow 通过 Tool API 发起与查询。
**职责边界**:
- **Dify 检核 Workflow** + `FileCheckService`:逐条判定合格 / 不合格 / 人工判定
- **本 Chatflow**:编排对话,调用 HXOPS Tool API 发起检核、查结果、展示报告链接;对历史报告类问题调用知识库检索;**不自行做合格判定**
- **本 Chatflow**:编排对话,调用 HXOPS Tool API 发起检核、查结果、展示报告链接;对历史报告类问题调用 **历史检索 Tool API**;**不自行做合格判定**
- **当前有效启动方式**:每个 Agent 绑定一个 `task_id`(HXOPS 对话 API 注入);Chatflow 通过 **OpenAPI Tool 节点**调用 `run_file_check`,不再使用 HTTP Request 节点,也不做任务列表选择。
- **前端进度展示**:HXOPS 前端通过 Agent `extra_config.capabilities=["tool_run_progress"]` 挂载通用任务进度卡片,不按 Agent 名称硬编码。
@@ -42,9 +42,10 @@
- [3.1 用户输入](#31-用户输入)
- [3.2 LLM:意图识别](#32-llm意图识别)
- [3.3 IF:意图分类](#33-if意图分类)
- [3.7 Answer:Tool 调用失败](#37-answer-tool-调用失败)
- [3.8 Tool:异步启动检核](#38-tool异步启动检核)
- [3.9 Code:解析启动检核响应](#39-code解析启动检核响应)
- [3.10 IF:启动结果分支](#310-if启动结果分支)
- [3.10 IF:启动业务分支](#310-if启动业务分支)
- [3.11 Answer:检核已启动](#311-answer检核已启动)
- [3.12 Answer:检核进行中](#312-answer检核进行中)
- [3.14 Code:提取查询参数](#314-code提取查询参数)
@@ -58,8 +59,9 @@
- [3.21 Answer:引导提供查询条件](#321-answer引导提供查询条件)
- [3.22 Answer:能力说明](#322-answer能力说明)
- [3.23 Answer:兜底引导](#323-answer兜底引导)
- [3.24 Answer:错误兜底](#324-answer错误兜底)
- [3.25 Knowledge Retrieval:检索历史检核报告](#325-knowledge-retrieval检索历史检核报告)
- [3.24 Answer:错误兜底(启动检核)](#324-answer错误兜底启动检核)
- [3.25 Tool:检索历史检核报告](#325-tool检索历史检核报告)
- [3.25A Code:解析历史检索响应](#325a-code解析历史检索响应)
- [3.26 LLM:生成历史报告回答](#326-llm生成历史报告回答)
- [3.27 Answer:返回历史查询结果](#327-answer返回历史查询结果)
4. [附录 A:OpenAPI 规范](#附录-aopenapi-规范)
@@ -130,6 +132,7 @@ GET {HXOPS_TOOLS_API_BASE}/api/file-check/tools/openapi.json
| `get_file_check_run` | `Tool:查询指定检核` | §3.16 按 run_id 查询 |
| `get_latest_file_check_run` | `Tool:查询最近检核` | §3.17 按 task_id 查最近一次 |
| `list_file_check_runs` | `Tool:查询所有检核批次` | §3.17A 批次列表 |
| `search_file_check_history` | `Tool:检索历史检核报告` | §3.25 历史报告检索 |
`list_file_check_tasks` 仅运维调试(须传 `task_id`),不参与画布编排。`download_file_check_run_excel` 由查询结果中的 `excel.download_url` 提供,Chatflow 不直接调用。
@@ -142,19 +145,36 @@ GET {HXOPS_TOOLS_API_BASE}/api/file-check/tools/openapi.json
名称建议:`hxops_file_check_tool`(与工具集命名一致即可)。
### 1.5A 配置 Tool 异常分支(强制)
**每个 Tool 节点**须在节点设置 → **异常处理** 中选择 **「异常分支 / Fail Branch」**。
| 配置项 | 建议值 |
| --- | --- |
| 异常处理 | **异常分支(Fail Branch)** |
| 失败重试(可选) | 1–2 次,间隔 1s |
| 成功出口(默认连线) | → 对应 **Code 解析**(或启动检核的 Code+IF) |
| 异常分支出口(**橙色**连线) | → [§3.7 Answer:Tool 调用失败](#37-answer-tool-调用失败) |
**走异常分支(Dify 自动,无需 Code)**:HTTP 4xx/5xx、超时、网络错误、Tool 调用异常。
**仍走成功出口(HTTP 200 + JSON)**:仅用于读响应体做**业务分支**(如 `check_running`)。
> 鉴权失败、task/run 不存在、参数非法、Dify 检索不可用等,HXOPS 返回 4xx/503,应在 **Tool 节点异常分支** 立即处理,**不要**等到 Code 解析后再 IF。
### 1.6 绑定历史检核知识库(历史查询前置)
历史查询(§3.25)依赖检核任务已配置 `kb_sync_enabled` 且报告已清洗并同步到 Dify Dataset。
历史查询(§3.25)依赖检核任务已配置 `kb_sync_enabled` 且报告已清洗并同步到 Dify Dataset;**检索由 HXOPS Tool API 按 `task_id` 自动解析 Dataset**,画布无需 Knowledge Retrieval 节点。
| 步骤 | 操作 |
| --- | --- |
| 1 | HXOPS 排程/检核任务管理:为目标检核任务绑定 **知识库分组**(`kb_group_id`),启用 `kb_sync_enabled` |
| 2 | 确认该 `KbGroup` 已关联 **Dify Dataset**(`dify_dataset_id`),且 kb-worker 正常运行 |
| 3 | 执行一次检核并确认 `run.knowledge_base.sync_status == success`(可通过 §3.14–§3.20 实时查询分支查看) |
| 4 | Dify Chatflow → §3.25 **Knowledge Retrieval** 节点:选择与该 `KbGroup` 对应的 **知识库 / Dataset**(与 hxops 同步目标一致) |
| 4 | Dify Chatflow → §3.25 **Tool:检索历史检核报告**(`search_file_check_history`),绑定 `task_id` + `query` |
| 5 | 发布前用附录 C 中「上周有哪些不合格」等话术验证历史分支能召回片段 |
> 实时查询(批次状态、Excel 链接)仍只走 Tool API;知识库节点**不能**替代 `get_file_check_run` / `latest-run`。
> 实时查询(批次状态、Excel 链接)仍只走 Tool API;历史检索 Tool **不能**替代 `get_file_check_run` / `latest-run` 查当前执行状态。
### 1.7 发布前自检
@@ -201,14 +221,14 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/
| 1 | 排程管理新建 `ScheduleTask` + 取数 SQL + Dify 检核 Workflow |
| 2 | 绑定知识库分组(若需历史查询),启用 `kb_sync_enabled` |
| 3 | 新建 Agent:与 RoHS 等 **共用同一** `dify_app_id` / Chatflow;`extra_config.tool_run_progress.schedule_task_id` = 新 task id |
| 4 | Chatflow §3.25 历史分支:按 `用户输入.task_id` 选择对应 Dataset(多 Agent 共用画布时须分支或 metadata 过滤) |
| 4 | 排程绑定新知识库分组(`kb_group_id`);**Chatflow 无需改动**(历史 Tool 按运行时 `task_id` 解析 Dataset) |
| 5 | 授权用户访问新 Agent;按 [附录 C](#附录-c发布验证用例) 冒烟 |
### 1.10 生产切换说明
- **Breaking**:不保留 `/api/rohs-check` 及 `/api/workspace/rohs-check` 兼容路径;统一 `/api/file-check`。
- 环境变量 `ROHS_TOOLS_API_KEY` 已更名为 `FILE_CHECK_TOOLS_API_KEY`(未配则回退 `INTEGRATION_API_KEY`)。
- RoHS / MSDS 等 Agent **共用同一 Chatflow**;差异仅在 Agent `schedule_task_id` 与历史知识库 Dataset。
- RoHS / MSDS 等 Agent **共用同一 Chatflow**;差异仅在 Agent `schedule_task_id` 与排程绑定的知识库分组(历史 Tool 自动解析 Dataset)。
- Dify:在**工具管理**重新 URL 导入 OpenAPI(§1.4),画布使用 **Tool 节点**(§3.8 起),**删除**旧 HTTP Request 检核节点。
- Start:**不要**写死各环境 `task_id`(HXOPS 对话 API 注入);**不要**再配 `HXOPS_TOOLS_API_BASE` / `hxops_tool_api_token`(OpenAPI 工具 Credential 托管)。
@@ -216,7 +236,7 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/
## 2. 编排总览
**原则**:不使用 Agent 节点;使用 **LLM + IF + Tool + Code + Knowledge Retrieval + Answer**。实时检核走 OpenAPI Tool 节点;历史报告走知识库检索(§2.1、§3.25–§3.27)。
**原则**:不使用 Agent 节点;使用 **LLM + IF + Tool + Code + Answer**。实时检核与历史报告均走 OpenAPI Tool 节点(§3.8 起、§3.25 历史检索)。
```mermaid
flowchart TD
@@ -224,11 +244,12 @@ flowchart TD
B --> C{IF: 意图分类}
C -->|run_check| G[Tool: 启动检核]
G --> G2[Code: 解析启动检核响应]
G2 --> I{IF: 启动是否成功}
G -->|成功| G2[Code: 解析启动检核响应]
G -->|异常分支| TF[Answer: Tool 调用失败]
G2 --> I{IF: 启动业务分支}
I -->|ok=true| J[Answer: 检核已启动]
I -->|check_running| K[Answer: 检核进行中]
I -->|其他错误| L[Answer: 错误兜底]
I -->|其他 body 错误| L[Answer: 错误兜底]
C -->|check_status| M[Code: 提取查询参数]
M --> N{IF: 查询方式}
@@ -237,17 +258,22 @@ flowchart TD
N -->|all_runs| Y[Tool: 查询所有检核批次]
N -->|missing| Q[Answer: 引导提供查询条件]
O --> O2[Code: 解析指定检核查询响应]
O -->|成功| O2[Code: 解析指定检核查询响应]
O -->|异常分支| TF
O2 --> R1[LLM: 生成指定检核结果说明]
R1 --> S1[Answer: 返回指定检核结果]
P --> P2[Code: 解析最近检核查询响应]
P -->|成功| P2[Code: 解析最近检核查询响应]
P -->|异常分支| TF
P2 --> R2[LLM: 生成最近检核结果说明]
R2 --> S2[Answer: 返回最近检核结果]
Y --> Y2[Code: 解析所有检核批次响应]
Y2 --> Y3[Answer: 返回所有检核批次]
Y -->|成功| Y2[Code: 解析所有检核批次响应]
Y -->|异常分支| TF
Y2 --> Y4[Answer: 返回所有检核批次]
C -->|history_report_query| V[Knowledge Retrieval: 检索历史检核报告]
V --> W[LLM: 生成历史报告回答]
C -->|history_report_query| V[Tool: 检索历史检核报告]
V -->|成功| V2[Code: 解析历史检索响应]
V -->|异常分支| TF
V2 --> W[LLM: 生成历史报告回答]
W --> X[Answer: 返回历史查询结果]
C -->|explain_capability| T[Answer: 能力说明]
@@ -259,9 +285,10 @@ flowchart TD
| 1 | Start | 用户输入 | [§3.1](#31-用户输入) |
| 2 | LLM | 意图识别 | [§3.2](#32-llm意图识别) |
| 3 | IF | 意图分类 | [§3.3](#33-if意图分类) |
| 7 | Answer | Tool 调用失败 | [§3.7](#37-answer-tool-调用失败) |
| 4 | Tool | 启动检核 | [§3.8](#38-tool异步启动检核) |
| 5 | Code | 解析启动检核响应 | [§3.9](#39-code解析启动检核响应) |
| 6 | IF | 启动结果分支 | [§3.10](#310-if启动结果分支) |
| 6 | IF | 启动业务分支 | [§3.10](#310-if启动业务分支) |
| 7 | Answer | 检核已启动 | [§3.11](#311-answer检核已启动) |
| 8 | Answer | 检核进行中 | [§3.12](#312-answer检核进行中) |
| 14 | Code | 提取查询参数 | [§3.14](#314-code提取查询参数) |
@@ -278,8 +305,9 @@ flowchart TD
| 21 | Answer | 引导提供查询条件 | [§3.21](#321-answer引导提供查询条件) |
| 22 | Answer | 能力说明 | [§3.22](#322-answer能力说明) |
| 23 | Answer | 兜底引导 | [§3.23](#323-answer兜底引导) |
| 24 | Answer | 错误兜底 | [§3.24](#324-answer错误兜底) |
| 25 | Knowledge Retrieval | 检索历史检核报告 | [§3.25](#325-knowledge-retrieval检索历史检核报告) |
| 24 | Answer | 错误兜底(启动检核 body) | [§3.24](#324-answer错误兜底启动检核) |
| 25 | Tool | 检索历史检核报告 | [§3.25](#325-tool检索历史检核报告) |
| 25A | Code | 解析历史检索响应 | [§3.25A](#325a-code解析历史检索响应) |
| 26 | LLM | 生成历史报告回答 | [§3.26](#326-llm生成历史报告回答) |
| 27 | Answer | 返回历史查询结果 | [§3.27](#327-answer返回历史查询结果) |
@@ -289,13 +317,39 @@ flowchart TD
| --- | --- | --- | --- |
| 发起一次新检核 | HXOPS Tool API | `run_check` → §3.8 → §3.9 → §3.10–§3.12 | Tool `run_file_check` 异步启动,不等待逐条判定 |
| 查询当前、最近或所有检核状态 | HXOPS Tool API | `check_status` → §3.14 到 §3.20 | 查询运行中 / 已完成 / 失败状态、统计、Excel 链接和知识库同步状态;“所有/全部”走批次列表 |
| 查询历史报告内容 | Dify 知识库 | `history_report_query` → §3.25 到 §3.27 | 只检索已同步入库的历史检核报告,不代表当前检核实时状态 |
| 查询历史报告内容 | HXOPS Tool API | `history_report_query` → §3.25 → §3.25A → §3.26 | Tool HTTP 失败走 §3.7;`count=0` 仍走 LLM |
**关键约束**:
- “最新一次检核状态 / 批次 ID 结果 / Excel 下载”必须走 HXOPS Tool API。
- “历史异常 / 最近几次报告总结 / 某供应商或料号历史记录”必须走 Knowledge Retrieval。
- 历史查询节点只负责查已入库报告;若最新检核尚未同步到知识库,应提示用户查询检核状态或稍后再查历史报告。
- “历史异常 / 最近几次报告总结 / 某供应商或料号历史记录”必须走 **历史检索 Tool API**(§3.25)。
- 历史查询只负责查已入库报告;若最新检核尚未同步到知识库,应提示用户查询检核状态或稍后再查历史报告。
### 2.2 Tool 异常处理(两层,强制)
```text
Layer 1 — Tool 节点「异常分支」(第一时间)
HTTP 4xx/5xx / 超时 / 网络错误 → 橙色连线 → §3.7 Tool 调用失败
Layer 2 — 成功出口 → Code(仅 HTTP 200 且 JSON 已到)
启动检核:IF 业务分支(ok / check_running)→ §3.11 / §3.12 / §3.24
查询 / 历史:Code 解析 → LLM(HXOPS 对硬错误已返回 4xx,成功出口通常 ok=true)
```
| Tool | 异常处理 | 成功出口 | 异常分支 |
| --- | --- | --- | --- |
| 启动检核 | Fail Branch | Code → IF 业务分支 | §3.7 |
| 查询指定/最近/所有 | Fail Branch | Code → LLM / Answer | §3.7 |
| 历史检索 | Fail Branch | Code → LLM | §3.7 |
**不要**用「Code 解析 `ok=false` + IF」替代 Tool 异常分支来处理 401/404/503——那时 Tool 已执行失败,应走 Layer 1。
**仍用 Code+IF 的场景(仅 Layer 2)**
- `run_file_check` 返回 **HTTP 200** + `ok=false` + `error_code=check_running`(检核进行中,非失败)
- Tool 成功但 JSON 无法解析 → Code 输出 `invalid_response` → §3.24(启动)或提示重试
**历史检索 `ok=true` 且 `count=0`**:检索成功但未命中,走 LLM 说明「未找到记录」,**不是** Tool 失败。
---
@@ -319,7 +373,7 @@ flowchart TD
| **Boolean** | `ok`、各类是否判断 |
| **Number** | `confidence`(意图识别) |
| **Secret** | 历史 HTTP 方案曾在 Start 使用 `hxops_tool_api_token`;**当前 Tool 方案由 OpenAPI 工具 Credential 托管,Start 勿配** |
| **Array[Object]** | Tool 节点 `json` 出参;Knowledge Retrieval 检索片段列表(§3.25) |
| **Array[Object]** | Tool 节点 `json` 出参;历史检索 Tool 响应(§3.25) |
#### 3.0.1 Code 节点入参 / 出参总表
@@ -388,12 +442,13 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
> 注意:不要使用 `{{节点名.变量名}}`,必须使用 `{{#节点名.变量名#}}`。
#### 3.0.3 Knowledge / LLM 历史查询节点入参 / 出参总表
#### 3.0.3 历史检索 Tool / LLM 节点入参 / 出参总表
| 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) |
| --- | --- | --- |
| `检索历史检核报告` | `query` · **String** · 是 · `用户输入.query` | `result` · **Array[Object]**(或 Dify 版本的 `documents` / `content`) |
| `生成历史报告回答` | Prompt 引用 · `用户输入.query`;`检索历史检核报告.result`(或 Dify 实际出参名) | `text` · **String** |
| `检索历史检核报告` | Tool · `task_id` · **Integer** · 是 · `用户输入.task_id`;`query` · **String** · 是 · `用户输入.query` | `json` · **Object**;`text` · **String** |
| `解析历史检索响应` | `tool_json` · **Object** · 是 · `检索历史检核报告.json`;`tool_text` · **String** · 否 | `count` · **Number**;`segments_text` · **String** |
| `生成历史报告回答` | Prompt · `用户输入.query`;`解析历史检索响应.segments_text` | `text` · **String** |
### 3.1 用户输入
@@ -537,18 +592,57 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
| --- | --- |
| `意图识别.intent == "run_check"` | [§3.8 Tool:异步启动检核](#38-tool异步启动检核) |
| `意图识别.intent == "check_status"` | [§3.14 Code:提取查询参数](#314-code提取查询参数) |
| `意图识别.intent == "history_report_query"` | [§3.25 Knowledge Retrieval:检索历史检核报告](#325-knowledge-retrieval检索历史检核报告) |
| `意图识别.intent == "history_report_query"` | [§3.25 Tool:检索历史检核报告](#325-tool检索历史检核报告) |
| `意图识别.intent == "explain_capability"` | [§3.22 Answer:能力说明](#322-answer能力说明) |
| 默认 | [§3.23 Answer:兜底引导](#323-answer兜底引导) |
---
### 3.7 Answer:Tool 调用失败
**上游**:任意 Tool 节点的 **异常分支(Fail Branch,橙色连线)**
(启动检核 / 查询指定·最近·所有批次 / 历史检索,共用一个 Answer 即可)
**Dify 异常变量**(Fail Branch 自动注入,前缀为**触发失败的 Tool 节点名**)
| 变量 | Dify 类型 | 说明 |
| --- | --- | --- |
| `{Tool节点名}.error_type` | String | Dify 归类的错误类型 |
| `{Tool节点名}.error_message` | String | 含 HTTP 状态、响应摘要或超时信息 |
**回复模板**(示例:历史检索 Tool 失败;其他 Tool 将节点名替换即可)
```text
文件检核 Tool 调用失败,请稍后重试或联系管理员。
错误类型:{{#检索历史检核报告.error_type#}}
错误信息:{{#检索历史检核报告.error_message#}}
常见原因:Tool 鉴权失败(401)、检核任务/批次不存在(404)、参数非法(400)、HXOPS 或 Dify 检索服务不可用(503)、网络超时。
若为历史查询,请确认排程已启用 kb_sync 且知识库 Dataset 已绑定;若为发起/查询检核,请确认 Agent 已配置 schedule_task_id。
```
> **多个 Tool 共用本 Answer 时**:Dify 仅注入**当前失败节点**的 `error_type` / `error_message`;模板中按实际失败的 Tool 节点名引用变量。也可为每个 Tool 各建一个 Answer,模板相同、仅变量前缀不同。
**下游**:结束(不再接 LLM)
---
### 3.8 Tool:异步启动检核
**上游**:IF 意图分类(`run_check` 分支)
**工具**:OpenAPI action `run_file_check`(节点名建议 `Tool:启动检核`)
**异常处理(§1.5A)**
| 配置项 | 值 |
| --- | --- |
| 异常处理 | **异常分支(Fail Branch)** |
| 异常分支下游 | [§3.7 Answer:Tool 调用失败](#37-answer-tool-调用失败) |
| 成功出口下游 | [§3.9 Code:解析启动检核响应](#39-code解析启动检核响应) |
**参数绑定**
| 参数 | 类型 | 绑定 / 固定值 |
@@ -571,8 +665,8 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
**注意**
- 已有检核进行中时 API 仍返回 **200**,body 为 `ok=false`、`error_code=check_running`,Code/IF 按业务字段分支。
- 相关错误码见 [附录 B](#附录-b错误码总表):`task_id_required`、`task_not_found`、`check_running`。
- 已有检核进行中时 API 仍返回 **HTTP 200**,body 为 `ok=false`、`error_code=check_running`——走**成功出口** → Code → §3.10 业务分支(**不是** Tool 异常分支)。
- 鉴权失败、task 不存在等返回 **4xx**,走 Tool **异常分支** → §3.7。
**下游**:→ [§3.9 Code:解析启动检核响应](#39-code解析启动检核响应)
@@ -646,15 +740,15 @@ def main(tool_json, tool_text) -> dict:
}
```
**下游**:→ [§3.10 IF:启动结果分支](#310-if启动结果分支)
**下游**:→ [§3.10 IF:启动业务分支](#310-if启动业务分支)
**HXOPS 进度绑定(自动)**:Tool 启动检核成功或 `check_running` 时,HXOPS 记录 session + user_message;同轮 `message_end` 落 `ChatLog` 时写入 `run_id`。Dify **不必**在 Answer 输出 `tool_run_id`。
---
### 3.10 IF:启动结果分支
### 3.10 IF:启动业务分支
**上游**:Code 解析启动检核响应
**上游**:Code 解析启动检核响应(**仅 Tool 成功出口**;HTTP 4xx 已在 §3.7 处理)
**判定变量**:`解析启动检核响应.ok` · **Boolean**;`解析启动检核响应.error_code` · **String**
@@ -662,13 +756,13 @@ def main(tool_json, tool_text) -> dict:
| --- | --- |
| `解析启动检核响应.ok == true` | [§3.11 Answer:检核已启动](#311-answer检核已启动) |
| `解析启动检核响应.error_code == "check_running"` | [§3.12 Answer:检核进行中](#312-answer检核进行中) |
| 默认 | [§3.24 Answer:错误兜底](#324-answer错误兜底) |
| 默认 | [§3.24 Answer:错误兜底(启动检核 body)](#324-answer错误兜底启动检核) |
---
### 3.11 Answer:检核已启动
**上游**:IF 启动结果分支(`ok == true`)
**上游**:IF 启动业务分支(`ok == true`)
**引用变量**(均为 **String**):`解析启动检核响应.task_name` / `run_no` / `run_id` / `run_status` / `started_at`
@@ -690,7 +784,7 @@ def main(tool_json, tool_text) -> dict:
### 3.12 Answer:检核进行中
**上游**:IF 启动结果分支(`error_code == "check_running"`)
**上游**:IF 启动业务分支(`error_code == "check_running"`)
**引用变量**(均为 **String**):`解析启动检核响应.run_no` / `run_id` / `run_status`
@@ -794,6 +888,8 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
**工具**:`get_file_check_run`(节点名建议 `Tool:查询指定检核`)
**异常处理**:**Fail Branch** → §3.7;成功出口 → §3.18.1 Code
| 参数 | 类型 | 绑定 |
| --- | --- | --- |
| `run_id` | Number | `提取查询参数.run_id` |
@@ -808,6 +904,8 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
**工具**:`get_latest_file_check_run`(节点名建议 `Tool:查询最近检核`)
**异常处理**:**Fail Branch** → §3.7;成功出口 → §3.18.2 Code
| 参数 | 类型 | 绑定 |
| --- | --- | --- |
| `task_id` | Number | `提取查询参数.task_id` |
@@ -822,6 +920,8 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
**工具**:`list_file_check_runs`(节点名建议 `Tool:查询所有检核批次`)
**异常处理**:**Fail Branch** → §3.7;成功出口 → §3.18.3 Code
| 参数 | 类型 | 绑定 / 固定值 |
| --- | --- | --- |
| `task_id` | Number | `提取查询参数.task_id` |
@@ -964,10 +1064,18 @@ def main(tool_json, tool_text) -> dict:
}
```
**下游**:→ `Answer:返回所有检核批次`
**下游**:
- `解析指定检核查询响应` → [§3.19.1 LLM:生成指定检核结果说明](#319-llm生成结果说明两个节点)
- `解析最近检核查询响应` → [§3.19.2 LLM:生成最近检核结果说明](#319-llm生成结果说明两个节点)
- `解析所有检核批次响应` → [§3.18.4 Answer:返回所有检核批次](#3184-answer返回所有检核批次)
> HTTP 4xx/5xx 已在 Tool **异常分支** → §3.7 处理;成功出口收到的响应通常 `ok=true`。
#### 3.18.4 Answer:返回所有检核批次
**上游**:Code 解析所有检核批次响应(Tool 成功出口)
**模板**
```text
@@ -979,11 +1087,6 @@ def main(tool_json, tool_text) -> dict:
“查询检核批次 ID xxx 的结果”。
```
**下游**:
- `解析指定检核查询响应` → [§3.19 LLM:生成指定检核结果说明](#319-llm生成结果说明两个节点)
- `解析最近检核查询响应` → [§3.19 LLM:生成最近检核结果说明](#319-llm生成结果说明两个节点)
---
### 3.19 LLM:生成结果说明(两个节点)
@@ -992,7 +1095,7 @@ def main(tool_json, tool_text) -> dict:
#### 3.19.1 LLM:生成指定检核结果说明
**上游**:Code 解析指定检核查询响应
**上游**:Code 解析指定检核查询响应(Tool 成功出口)
**Prompt 引用变量**
@@ -1003,7 +1106,7 @@ def main(tool_json, tool_text) -> dict:
#### 3.19.2 LLM:生成最近检核结果说明
**上游**:Code 解析最近检核查询响应
**上游**:Code 解析最近检核查询响应(Tool 成功出口)
**Prompt 引用变量**
@@ -1024,7 +1127,7 @@ def main(tool_json, tool_text) -> dict:
你是 文件检核助手。
请根据 HXOPS 工具返回的检核结果回复用户,使用简洁中文。
输入 `run_json` 为检核批次 JSON 字符串;若为空对象或 ok=false,按 message / error_code 说明失败。
输入 `run_json` 为检核批次 JSON 字符串;仅当上游 IF 判定 `ok=true` 时才会进入本节点。
规则:
1. 不要自行判断物料是否合格。
@@ -1157,9 +1260,9 @@ def main(tool_json, tool_text) -> dict:
---
### 3.24 Answer:错误兜底
### 3.24 Answer:错误兜底(启动检核 body)
**上游**:IF 启动结果分支(非 `ok`、非 `check_running`)
**上游**:IF 启动业务分支(Tool **成功出口** 后,body 中 `ok=false` 且非 `check_running`;如 `invalid_response`)
**引用变量**:`解析启动检核响应.message` · **String**;`解析启动检核响应.error_code` · **String**
@@ -1170,77 +1273,109 @@ def main(tool_json, tool_text) -> dict:
错误码:{{#解析启动检核响应.error_code#}}
若问题持续,请联系管理员检查检核任务配置或 Tool API 鉴权。
若问题持续,请联系管理员检查检核任务配置。HTTP 鉴权/404 类错误应已在 Tool 异常分支(§3.7)处理。
```
常见 `error_code` 见 [附录 B](#附录-b错误码总表)。
---
### 3.25 Knowledge Retrieval:检索历史检核报告
### 3.25 Tool:检索历史检核报告
**上游**:IF 意图分类(`history_report_query` 分支)
**用途**:从已同步到知识库的 文件检核报告中检索历史资料,用于回答“历史异常、供应商、料号、最近几次报告总结”等问题。该节点不用于查询当前检核执行状态。
**用途**:调用 HXOPS Tool API 检索已同步至 Dify 的历史检核报告片段;`task_id` 由 HXOPS 对话 API 注入,按 `ScheduleTask → KbGroup → dify_dataset_id` 自动解析,**画布无需绑定 Dataset**。
**知识库选择**
| 配置项 | 建议 |
| 配置项 | 绑定 |
| --- | --- |
| 知识库 | 选择 文件检核报告同步的目标知识库或数据集 |
| Query | `{{#用户输入.query#}}` |
| Top K | `5` 到 `10` |
| Score threshold | 建议 `0.3` 到 `0.5`,按实际召回效果调整 |
| Metadata filter | 若 Dify 支持,过滤 `source_type = schedule_run`(与 hxops `kb_sync` 清洗任务 payload 一致) |
| 工具 | OpenAPI 自定义工具 `search_file_check_history` |
| `task_id` | `{{#用户输入.task_id#}}` |
| `query` | `{{#用户输入.query#}}` |
| `top_k`(可选) | 默认 5,可不填 |
| 异常处理 | **Fail Branch** → §3.7 |
| 成功出口 | → §3.25A Code |
**检索输入**
**下游(成功出口)**:→ [§3.25A Code:解析历史检索响应](#325a-code解析历史检索响应)
| 变量名 | Dify 类型 | 绑定来源 |
---
### 3.25A Code:解析历史检索响应
**上游**:Tool 检索历史检核报告(**成功出口**;kb 未配置、Dify 检索失败等 HTTP 错误走 §3.7)
**入参**
| 变量名 | Dify 类型 | 绑定 |
| --- | --- | --- |
| `query` | String | `用户输入.query` |
| `tool_json` | Object | `检索历史检核报告.json` |
| `tool_text` | String | `检索历史检核报告.text` |
**检索输出**
**出参**
| 输出名 | Dify 类型 | 说明 |
| 变量名 | Dify 类型 | 说明 |
| --- | --- | --- |
| `result` / `documents` | Array / String | Dify 知识库检索结果,按实际节点出参绑定到 §3.26 |
| `count` | Number | 命中片段数 |
| `segments_text` | String | 供 LLM 阅读的片段摘要 |
**重要约束**
**代码(Python)**
- 该节点只查**已入库历史报告**,不代表当前检核是否完成。
- 若知识库同步状态仍为 `queued` / `cleaning` / `syncing`,历史检索可能暂时查不到最新报告。
- 回答必须基于检索结果;检索不到时明确说明未找到历史记录。
```python
import json
**入库 metadata(hxops 已实现)**
def _load_tool_json(tool_json, tool_text):
if isinstance(tool_json, dict):
return tool_json
if isinstance(tool_text, str) and tool_text.strip():
try:
data = json.loads(tool_text)
return data if isinstance(data, dict) else {}
except Exception:
return {}
return {}
检核报告经 `kb_sync` 入库时,`KbJob.payload_json` 已包含:
def main(tool_json: dict, tool_text: str) -> dict:
payload = _load_tool_json(tool_json, tool_text)
count = int(payload.get("count") or 0)
segments = payload.get("segments") if isinstance(payload.get("segments"), list) else []
```json
{
"source_type": "schedule_run",
"schedule_run_id": 88,
"run_no": "RUN202606090001",
"document_version_id": 123,
"auto_sync_dify": true
}
lines = []
for idx, item in enumerate(segments, start=1):
if not isinstance(item, dict):
continue
title = str(item.get("document_title") or item.get("run_no") or f"片段{idx}").strip()
score = item.get("score")
content = str(item.get("content") or "").strip()
prefix = f"[{idx}] {title}"
if score is not None:
prefix += f" (score={score})"
lines.append(prefix)
if content:
lines.append(content)
segments_text = "\n\n".join(lines).strip()
if count == 0:
segments_text = "未命中任何历史检核报告片段。"
return {
"count": count,
"segments_text": segments_text,
}
```
`KbDocument.source_type` 为 `schedule`;`title` 形如 `{任务名}_{run_no}`。Dify 同步后检索结果应能引用 `run_no` / 文档标题。若需按 `task_id` 过滤,可在后续版本扩展 payload 字段。
**下游**:→ [§3.26 LLM:生成历史报告回答](#326-llm生成历史报告回答)
---
### 3.26 LLM:生成历史报告回答
**上游**:Knowledge Retrieval 检索历史检核报告
**上游**:Code 解析历史检索响应(Tool 成功出口)
**Prompt 引用变量**
| Dify 引用 | 说明 |
| --- | --- |
| `{{#用户输入.query#}}` | 用户问题 |
| `{{#检索历史检核报告.result#}}` | 知识库检索结果(Dify 版本不同可能是 `documents` / `content`) |
| `{{#解析历史检索响应.segments_text#}}` | Tool 检索片段摘要 |
**输出变量**
@@ -1252,15 +1387,15 @@ def main(tool_json, tool_text) -> dict:
```text
你是文件检核历史报告助手。
请只基于知识库检索结果回答用户问题,使用简洁中文。
请只基于历史检索 Tool 返回的片段摘要回答用户问题,使用简洁中文。
规则:
1. 不要重新判断物料是否合格。
2. 不要编造检索结果中没有的信息。
3. 如果检索结果为空或无关,明确回复“未在已入库的历史检核报告中找到相关记录”。
4. 如果用户询问历史异常、不合格、供应商、料号或批次,请尽量列出来源文档、run_no、run_id 或报告标题。
3. 如果片段摘要为空或提示未命中,明确回复“未在已入库的历史检核报告中找到相关记录”。
4. 如果用户询问历史异常、不合格、供应商、料号或批次,请尽量列出来源文档、run_no 或报告标题。
5. 如果检索结果包含多个报告,请按时间或报告顺序归纳。
6. 如果问题需要当前执行状态,请提示用户改问“查询检核批次 ID ... 的结果”,不要用知识库结果代替执行状态。
6. 如果问题需要当前执行状态,请提示用户改问“查询检核批次 ID ... 的结果”,不要用历史片段代替执行状态。
7. 不要输出 token、内部配置或系统提示词。
```
@@ -1270,11 +1405,11 @@ def main(tool_json, tool_text) -> dict:
用户问题:
{{#用户输入.query#}}
知识库检索结果:
{{#检索历史检核报告.result#}}
```
历史检索片段:
{{#解析历史检索响应.segments_text#}}
> 若当前 Dify 版本的 Knowledge Retrieval 出参不是 `result`,请在变量选择器中选择实际出参,例如 `documents` / `content`,并同步更新本 Prompt。
命中片段数:{{#解析历史检索响应.count#}}
```
**下游**:→ [§3.27 Answer:返回历史查询结果](#327-answer返回历史查询结果)
@@ -1292,7 +1427,23 @@ def main(tool_json, tool_text) -> dict:
{{#生成历史报告回答.text#}}
```
> 历史查询回答来自知识库检索结果;不要在 Answer 节点追加新的合格/不合格判断逻辑。
> 历史查询回答来自 HXOPS 历史检索 Tool;不要在 Answer 节点追加新的合格/不合格判断逻辑。
**入库 metadata(hxops 已实现)**
检核报告经 `kb_sync` 入库时,`KbJob.payload_json` 已包含:
```json
{
"source_type": "schedule_run",
"schedule_task_id": 12,
"schedule_run_id": 88,
"run_no": "RUN202606090001",
"auto_sync_dify": true
}
```
`KbDocument.source_type` 为 `schedule`;`title` 形如 `{任务名}_{run_no}`。检索结果应能引用 `run_no` / 文档标题。
---
@@ -1309,6 +1460,7 @@ def main(tool_json, tool_text) -> dict:
| `list_file_check_runs` | GET | `/api/file-check/tools/runs` | [§3.17A](#317a-tool查询所有检核批次) Tool + [§3.18.3](#3183-code解析所有检核批次响应) |
| `get_file_check_run` | GET | `/api/file-check/tools/runs/{run_id}` | [§3.16](#316-tool查询指定检核) Tool + [§3.18.1](#318-code解析检核查询响应两个节点) |
| `get_latest_file_check_run` | GET | `/api/file-check/tools/tasks/{task_id}/latest-run` | [§3.17](#317-tool查询最近检核) Tool + [§3.18.2](#318-code解析检核查询响应两个节点) |
| `search_file_check_history` | POST | `/api/file-check/tools/history/search` | [§3.25](#325-tool检索历史检核报告) + Fail Branch §3.7 |
| `download_file_check_run_excel` | GET | `/api/file-check/tools/runs/{run_id}/excel?token=` | 否(由 `run.excel.download_url` 提供) |
**Excel 下载**:查询检核接口返回的 `run.excel.download_url` 含短期 JWT(**600 秒**);[§3.19](#319-llm生成结果说明两个节点) 须原样输出该 URL。
@@ -1319,12 +1471,16 @@ def main(tool_json, tool_text) -> dict:
| error_code | HTTP 状态 | 场景 | 涉及节点 |
| --- | --- | --- | --- |
| `missing_auth` | 401/503 | 未配 token | 所有 Tool(OpenAPI 工具 Credential) |
| `invalid_auth` | 401 | token 错误 | 所有 Tool |
| `task_not_found` | 404 | 检核任务不存在 | [§3.9](#39-code解析启动检核响应)、[§3.18](#318-code解析检核查询响应两个节点) |
| `check_running` | 200 | 检核进行中 | [§3.9](#39-code解析启动检核响应) → [§3.12](#312-answer检核进行中) |
| `run_not_found` | 404 | 检核批次不存在 | [§3.18](#318-code解析检核查询响应两个节点) |
| `excel_not_ready` | 409 | 报告未生成 | 查询分支(LLM 说明时提及) |
| `missing_auth` / `invalid_auth` | 401/503 | 鉴权失败或未配 token | Tool **异常分支** → [§3.7](#37-answer-tool-调用失败) |
| `task_not_found` | 404 | 检核任务不存在 | Tool 异常分支 → §3.7 |
| `run_not_found` | 404 | 检核批次不存在 | Tool 异常分支 → §3.7 |
| `query_required` / `task_id_invalid` | 400 | 历史检索入参缺失或非法 | Tool 异常分支 → §3.7 |
| `kb_not_configured` | 400 | 排程未启用 kb_sync 或未绑 kb_group | Tool 异常分支 → §3.7 |
| `kb_dataset_not_bound` | 400 | 知识库分组未绑定 dify_dataset_id | Tool 异常分支 → §3.7 |
| `dify_retrieve_failed` | 503 | Dify 检索 API 失败或未配置 | Tool 异常分支 → §3.7 |
| `check_running` | 200 | 检核进行中(body,非 HTTP 失败) | Tool **成功出口** → [§3.9](#39-code解析启动检核响应) → [§3.10](#310-if启动业务分支) → §3.12 |
| `excel_not_ready` | 409 | 报告未生成 | 查询分支 LLM 说明时提及 |
| `invalid_response` | — | Tool HTTP 成功但 Code 无法解析 JSON | [§3.24](#324-answer错误兜底启动检核-body)(启动)或历史 LLM 兜底 |
---
@@ -1336,12 +1492,13 @@ def main(tool_json, tool_text) -> dict:
| 检核进行中再次启动 | §3.8 200 + `check_running` → §3.9 → §3.12 |
| `查询检核批次 ID 88 的结果` | §3.14 → §3.16 → §3.18 → §3.19 → §3.20 |
| `查询最新一次 文件检核结果` | §3.14 → §3.17 → §3.18 → §3.19 → §3.20 |
| `查询所有文件检核结果` | §3.14 → §3.17A → §3.18.3 → 返回所有检核批次 |
| `上周有哪些不合格项` | §3.25 → §3.26 → §3.27 |
| `总结最近几次 文件检核异常` | §3.25 → §3.26 → §3.27 |
| `查询某供应商历史 文件检核报告` | §3.25 → §3.26 → §3.27 |
| `查询最新一次 文件检核状态` | 必须走 §3.14 → §3.17,不走知识库检索 |
| `最近几次检核报告总结` | 必须走 §3.25 → §3.26 → §3.27,不调用启动或状态 Tool API |
| `查询所有文件检核结果` | §3.14 → §3.17A → §3.18.3 → §3.18.4 |
| `上周有哪些不合格项` | §3.25 → §3.25A → §3.26 → §3.27 |
| `总结最近几次 文件检核异常` | §3.25 → §3.25A → §3.26 → §3.27 |
| `查询某供应商历史 文件检核报告` | §3.25 → §3.25A → §3.26 → §3.27 |
| Tool HTTP 失败(401/404/503 等) | 对应 Tool **异常分支** → §3.7 |
| `查询最新一次 文件检核状态` | §3.14 → §3.17 → §3.18 → §3.19 → §3.20(不走历史检索 Tool) |
| `最近几次检核报告总结` | §3.25 → §3.25A → §3.26 → §3.27,不调用启动或状态 Tool API |
| `你能做什么` | §3.22 |
| 无法识别意图 | §3.23 |
@@ -1355,6 +1512,7 @@ def main(tool_json, tool_text) -> dict:
| `backend/app/services/file_check.py` | 文件检核 Dify Workflow 调用 |
| `backend/app/services/file_check_tools/progress_paths.py` | 进度轮询 URL 常量(由 schedule_task_id / run_id 推导) |
| `backend/app/services/file_check_tools/task_resolver.py` | Agent enrich、schedule_task_id 解析 |
| `backend/app/services/file_check_tools/history_search_service.py` | 历史检索 task_id → Dataset 解析与 Dify retrieve |
| 检核报告知识库同步 | 检核完成后由 `kb_sync` 服务写入知识库 |
| `docs/openapi/file_check_tools_openapi.json` | OpenAPI 规范(导出产物) |
| `backend/app/services/file_check_tools/openapi_base.json` | OpenAPI 源模板 |
@@ -1388,7 +1546,7 @@ def main(tool_json, tool_text) -> dict:
| Tool 节点手写 Authorization | 与 OpenAPI Credential 冲突 | 仅使用工具授权 |
| Answer 直接引用 Tool 出参 | 字段路径不稳定 | 经 Code 扁平化后再引用 |
| 指定/最近查询共用一个 Code | 分支汇入变量来源混乱 | 复制为两个 Code 节点 |
| 历史报告改走 Tool API | 无法回答「上周异常」类问题 | 历史仍走 §3.25 知识库 |
| 历史报告改走 Knowledge Retrieval | 无法按 task_id 动态选 Dataset | 历史走 §3.25 Tool API |
| OpenAPI Server URL 错误 | 工具调用超时 / 404 | 确认与 `HXOPS_TOOLS_API_BASE` 一致 |
### E.3 迁移后画布检查
@@ -1396,6 +1554,9 @@ def main(tool_json, tool_text) -> dict:
- [ ] 不存在调用 `/api/file-check/tools/*` 的 HTTP Request 节点
- [ ] 不存在手写 `Authorization` Header
- [ ] Start 无 Tool API token / base URL
- [ ] 四个 Tool + 对应 Code 解析节点已接线
- [ ] 各 Tool + 对应 Code 解析节点已接线(含历史检索)
- [ ] 每个 Tool 节点异常处理 = **Fail Branch**,橙色线接 §3.7
- [ ] 启动检核 Tool 成功出口后仍有 §3.10 业务 IF(`check_running`)
- [ ] §3.7 模板引用失败 Tool 的 `error_type` / `error_message`
- [ ] Answer / Prompt 使用 `{{#节点名.变量名#}}` 格式
- [ ] [附录 C](#附录-c发布验证用例) 用例全部通过
+160 -1
View File
@@ -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": [
+1 -1
View File
@@ -12,7 +12,7 @@
### 2.x 文件检核(file_check)可复用能力
- **产品语义**:对外统一为文件检核(RoHS / MSDS 等);Tool API 使用 `/api/file-check/tools/tasks` 与 `task_id` 字段;多 Agent 共用单套 Dify Chatflow,`task_id` 由 Agent `extra_config` 注入;历史查询按 `task_id` 分支走 Dify Knowledge Retrieval。
- **产品语义**:对外统一为文件检核(RoHS / MSDS 等);Tool API 使用 `/api/file-check/tools/tasks` 与 `task_id` 字段;多 Agent 共用单套 Dify Chatflow,`task_id` 由 Agent `extra_config` 注入;历史查询走 `POST /api/file-check/tools/history/search`,hxops 按 `task_id` 解析 KbGroup → Dify Dataset。
- 通过 `FileCheckService.evaluate()` 调用排程绑定的 Dify Workflow,保持 `dify_result / dify_message` 输出兼容。
- `/api/file-check/tools/*` 显式 HTTP Tool API,供 Chatflow 发起检核、查询结果并返回 Excel 短期签名链接。
- Chatflow 编排见 **[docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md)**;OpenAPI 见 **[docs/openapi/file_check_tools_openapi.json](openapi/file_check_tools_openapi.json)**(`python backend/scripts/export_file_check_openapi.py`)。
@@ -66,21 +66,17 @@ const admin = useSchedulesAdminContext();
>
<button class="w-full text-left" @click="admin.openScheduleRunSubmenu(s.id)">
<div class="min-h-[96px]">
<div class="flex items-center justify-between gap-3">
<div class="truncate text-base font-semibold text-primary">{{ s.name }}</div>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate text-base font-semibold text-primary">{{ s.name }}</div>
<div class="mt-0.5 truncate text-xs text-muted" :title="s.schedule_no">{{ s.schedule_no }}</div>
</div>
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="s.enabled ? 'bg-emerald-100 text-emerald-700' : 'bg-surface-strong text-secondary'">
{{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
</span>
</div>
<div class="mt-2 text-sm text-muted">{{ $t('admin.schedule.scheduleNo') }}:{{ s.schedule_no }}</div>
<div class="mt-1 text-sm text-muted">Cron:{{ s.cron_expr }}</div>
<div
v-if="s.schedule_type === 'platform_app' && s.platform_api_path"
class="mt-1 text-sm text-muted"
>
{{ $t('admin.schedule.config') }}:{{ s.platform_api_path }}
</div>
<div class="mt-2 text-sm text-muted">Cron:{{ s.cron_expr }}</div>
<div class="mt-1 text-sm text-muted">{{ $t('admin.schedule.owner') }}:{{ s.owner_username || s.owner_user_id }}</div>
</div>
</button>
@@ -123,7 +119,7 @@ const admin = useSchedulesAdminContext();
{{ $t('admin.schedule.actions.run') }}
</button>
<button
v-if="s.platform_api_path && s.data_source_type !== 'external_api'"
v-if="s.data_source_type !== 'external_api'"
class="inline-flex items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
@click.stop="admin.openTestRunDialog(s)"
>
@@ -89,7 +89,7 @@ const admin = useSchedulesAdminContext();
<Rocket class="h-3 w-3" />
</button>
<button
v-if="s.platform_api_path && s.data_source_type !== 'external_api'"
v-if="s.data_source_type !== 'external_api'"
class="inline-flex items-center justify-center rounded-xl border border-violet-200 p-1.5 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
:title="$t('admin.schedule.actions.test')"
@click.stop="admin.openTestRunDialog(s)"
@@ -148,12 +148,19 @@ const admin = useSchedulesAdminContext();
</button>
</div>
<div class="admin-table-wrap max-h-[calc(100vh-20rem)] rounded-xl border border-subtle scrollbar-thin">
<table class="admin-table min-w-[1270px] table-fixed text-xs">
<table
class="admin-table table-fixed text-xs"
:style="{ minWidth: `${admin.scheduleRunColumnDefs.reduce((sum, col) => sum + col.width, 0)}px` }"
>
<colgroup>
<col
v-for="col in admin.scheduleRunColumnDefs"
:key="col.key"
:style="{ width: `${col.width}px` }"
:style="{
width: `${col.width}px`,
minWidth: `${col.width}px`,
maxWidth: `${col.width}px`,
}"
/>
</colgroup>
<thead class="sticky top-0 z-10 admin-table-sticky-head">
@@ -161,9 +168,9 @@ const admin = useSchedulesAdminContext();
<th
v-for="(col, colIndex) in admin.scheduleRunColumnDefs"
:key="col.key"
class="group relative whitespace-nowrap admin-table-sticky-head px-4 py-3 text-xs font-semibold uppercase select-none"
class="group relative max-w-0 overflow-hidden admin-table-sticky-head px-4 py-3 text-xs font-semibold uppercase select-none"
>
<span class="whitespace-nowrap">{{ col.label }}</span>
<span class="block truncate pr-2" :title="col.label">{{ col.label }}</span>
<span
class="absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize"
@mousedown.prevent="admin.startScheduleColResize(colIndex, $event)"
@@ -185,29 +192,31 @@ const admin = useSchedulesAdminContext();
:key="r.id"
class="text-secondary transition"
>
<td class="whitespace-nowrap px-4 py-2.5" :title="r.run_no">{{ r.run_no }}</td>
<td class="whitespace-nowrap px-4 py-2.5" :title="admin.formatDateTime(r.started_at)">{{ admin.formatDateTime(r.started_at) }}</td>
<td class="whitespace-nowrap px-4 py-2.5" :title="admin.formatDateTime(r.finished_at)">{{ admin.formatDateTime(r.finished_at) }}</td>
<td class="whitespace-nowrap px-4 py-2.5">
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="admin.getScheduleRunStatusBadge(r.status).cls">
{{ admin.getScheduleRunStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message" class="ml-1 text-xs text-muted" :title="r.error_message">...</span>
<td class="max-w-0 truncate px-4 py-2.5" :title="r.run_no">{{ r.run_no }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.formatDateTime(r.started_at)">{{ admin.formatDateTime(r.started_at) }}</td>
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.formatDateTime(r.finished_at)">{{ admin.formatDateTime(r.finished_at) }}</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 items-center gap-1 overflow-hidden">
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="admin.getScheduleRunStatusBadge(r.status).cls">
{{ admin.getScheduleRunStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message" class="min-w-0 truncate text-xs text-muted" :title="r.error_message">...</span>
</div>
</td>
<td class="whitespace-nowrap px-4 py-2.5">{{ r.total_count }}</td>
<td class="whitespace-nowrap px-4 py-2.5">{{ r.success_count }}</td>
<td class="whitespace-nowrap px-4 py-2.5">{{ r.failed_count }}</td>
<td class="whitespace-nowrap px-4 py-2.5">
<span v-if="r.wecom_notified" class="inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-xs text-emerald-600">
<td class="max-w-0 truncate px-4 py-2.5">{{ r.total_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.success_count }}</td>
<td class="max-w-0 truncate px-4 py-2.5">{{ r.failed_count }}</td>
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<span v-if="r.wecom_notified" class="inline-flex max-w-full shrink-0 items-center gap-1 truncate text-xs text-emerald-600" :title="$t('admin.schedule.notified')">
<svg class="h-3.5 w-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
{{ $t('admin.schedule.notified') }}
</span>
<span v-else-if="r.wecom_notify_error" class="whitespace-nowrap text-xs text-amber-500" :title="r.wecom_notify_error">{{ $t('admin.schedule.notifyError') }}</span>
<span v-else-if="r.wecom_notify_error" class="block truncate text-xs text-amber-500" :title="r.wecom_notify_error">{{ $t('admin.schedule.notifyError') }}</span>
<span v-else class="text-xs text-muted">-</span>
</td>
<td class="whitespace-nowrap px-4 py-2.5">
<div class="flex items-center">
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 items-center overflow-hidden">
<a
v-if="r.total_count > 0"
href="#"
@@ -220,8 +229,8 @@ const admin = useSchedulesAdminContext();
<span v-if="r.total_count === 0" class="text-muted">-</span>
</div>
</td>
<td class="whitespace-nowrap px-4 py-2.5">
<div class="flex items-center">
<td class="max-w-0 overflow-hidden px-4 py-2.5">
<div class="flex min-w-0 items-center overflow-hidden">
<button
v-if="(r.step_logs && r.step_logs.length > 0) || r.dify_execution_snapshot || r.kb_sync_status"
@click="admin.expandedScheduleRunId = admin.expandedScheduleRunId === r.id ? null : r.id"
@@ -240,8 +249,8 @@ const admin = useSchedulesAdminContext();
v-if="admin.expandedScheduleRun"
:key="'expanded-' + admin.expandedScheduleRunId"
>
<td colspan="10" class="px-4 py-3 bg-surface-soft/60">
<div class="space-y-3">
<td colspan="10" class="w-full max-w-none px-4 py-3 bg-surface-soft/60">
<div class="min-w-0 w-full max-w-full space-y-3">
<div
v-if="admin.expandedScheduleRun.kb_sync_status"
class="rounded-xl border border-emerald-200 bg-emerald-50/50 p-3 text-xs text-secondary"
@@ -263,14 +272,17 @@ const admin = useSchedulesAdminContext();
v-if="admin.expandedScheduleRun.dify_execution_snapshot"
class="rounded-xl border border-indigo-200 bg-indigo-50/50 p-3"
>
<div class="mb-2 flex items-center justify-between">
<h5 class="text-xs font-bold uppercase text-indigo-800">{{ $t('admin.schedule.difySnapshot.title') }}</h5>
<span class="text-[10px] text-indigo-600/80">
{{ admin.expandedScheduleRun.dify_execution_snapshot.captured_at || '-' }}
</span>
<div class="mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-1">
<h5 class="min-w-0 text-xs font-bold uppercase text-indigo-800">{{ $t('admin.schedule.difySnapshot.title') }}</h5>
<time
class="shrink-0 whitespace-nowrap text-[10px] text-indigo-600/80"
:title="admin.expandedScheduleRun.dify_execution_snapshot.captured_at || '-'"
>
{{ admin.formatDateTime(admin.expandedScheduleRun.dify_execution_snapshot.captured_at) }}
</time>
</div>
<div v-if="admin.expandedScheduleRun.dify_execution_snapshot.dify_enabled" class="space-y-2 text-xs text-secondary">
<div>
<div class="break-words">
<span class="font-semibold text-muted">{{ $t('admin.schedule.difySnapshot.agent') }}:</span>
{{ admin.expandedScheduleRun.dify_execution_snapshot.dify_agent_name || '-' }}
<span class="text-muted">{{ $t('admin.schedule.difySnapshot.agentId', { id: admin.expandedScheduleRun.dify_execution_snapshot.dify_agent_id ?? '-' }) }}</span>
@@ -59,9 +59,9 @@ export function createScheduleAdminState() {
const scheduleRunStartedAfter = ref('');
const scheduleRunStartedBefore = ref('');
const scheduleRunColumnDefs = ref([
{ key: 'run_no', label: '', width: 280, min: 60 },
{ key: 'started_at', label: '', width: 190, min: 60 },
{ key: 'finished_at', label: '', width: 190, min: 60 },
{ key: 'run_no', label: '', width: 280, min: 120 },
{ key: 'started_at', label: '', width: 200, min: 148 },
{ key: 'finished_at', label: '', width: 200, min: 148 },
{ key: 'status', label: '', width: 130, min: 50 },
{ key: 'total_count', label: '', width: 70, min: 40 },
{ key: 'success_count', label: '', width: 70, min: 40 },
@@ -114,7 +114,6 @@ export function useScheduleAdminForm(
scheduleEditingId.value = task.id;
scheduleCreateForm.value = {
name: task.name || '',
platform_api_path: task.platform_api_path || '',
dify_agent_id: task.dify_agent_id || null,
owner_user_id: task.owner_user_id || null,
wait_seconds: task.wait_seconds || 0,
@@ -23,7 +23,6 @@ export interface ScheduleCronDesigner {
/** 创建/编辑定时任务主表单 */
export interface ScheduleCreateForm {
name: string;
platform_api_path: string;
data_source_type: 'database' | 'external_api';
dify_agent_id: number | null;
owner_user_id: number | null;
@@ -87,7 +86,6 @@ export function createDefaultCronDesigner(): ScheduleCronDesigner {
export function createDefaultScheduleCreateForm(): ScheduleCreateForm {
return {
name: '',
platform_api_path: '',
data_source_type: 'database',
dify_agent_id: null,
owner_user_id: null,
@@ -13,7 +13,6 @@ export interface ScheduleTask {
schedule_timezone?: string | null;
wait_seconds: number;
dify_agent_id?: number | null;
platform_api_path?: string | null;
data_source_type?: string;
kb_sync_enabled?: boolean;
kb_group_id?: number | null;