feat(file-check): 增加文件检核 Excel 下载链接解析与展示功能
This commit is contained in:
1 parent
5e7e5a8717
commit
f21216f81e
21 files changed
+885
-125
No files matched your search
@@ -1002,7 +1002,7 @@ def get_chat_messages():
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or [],
|
||||
|
||||
@@ -27,13 +27,19 @@ from app.core.errors import (
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
@@ -41,13 +47,13 @@ _RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or current_app.config.get("SECRET_KEY")
|
||||
or "default-secret"
|
||||
).strip()
|
||||
def _download_token_secret() -> str:
|
||||
"""
|
||||
Excel 下载 JWT 签名密钥。
|
||||
|
||||
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||
"""
|
||||
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
@@ -57,7 +63,7 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
|
||||
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
@@ -65,6 +71,20 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
query_token = str(request.args.get("token") or "").strip()
|
||||
if query_token:
|
||||
if _decode_download_token(query_token):
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用
|
||||
configured = str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
@@ -77,13 +97,11 @@ def _require_tool_auth() -> None:
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
if configured in {api_token, integration_key}:
|
||||
return
|
||||
if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
|
||||
return
|
||||
if not token and not integration_key:
|
||||
if not api_token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
@@ -104,6 +122,8 @@ def _tool_error_code(exc: AppError) -> str:
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "data_source_unavailable":
|
||||
return "data_source_unavailable"
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
@@ -128,7 +148,8 @@ def _handle_tool_app_error(exc: AppError):
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
return resolve_HXOPS_TOOLS_API_BASE()
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
@@ -148,7 +169,7 @@ def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@@ -309,12 +330,30 @@ def _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||
"""
|
||||
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||
|
||||
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||
"""
|
||||
current_app.logger.warning(
|
||||
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||
task.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||
code="data_source_unavailable",
|
||||
) from exc
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。
|
||||
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
@@ -323,12 +362,19 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
try:
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
except RuntimeError as exc:
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
except Exception as exc:
|
||||
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
raise
|
||||
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
if rows:
|
||||
return None
|
||||
return _build_no_data_response(task)
|
||||
|
||||
@@ -119,9 +119,12 @@ class Config:
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
|
||||
HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
|
||||
@@ -134,6 +134,98 @@ class DifyService:
|
||||
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
||||
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
||||
|
||||
@staticmethod
|
||||
def _merge_stream_answer_text(
|
||||
streamed_text: str,
|
||||
terminal_answer: str | None,
|
||||
*,
|
||||
replace_answer: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
合并流式增量文本与终态 answer,避免 Dify 结束事件重复携带整段正文导致落库翻倍。
|
||||
核心逻辑:与前端 useChat.ts 终态事件去重策略保持一致。
|
||||
|
||||
Args:
|
||||
streamed_text: message 事件累积的增量文本。
|
||||
terminal_answer: message_end / workflow_finished 携带的 answer。
|
||||
replace_answer: 为 True 时仅使用终态 answer。
|
||||
|
||||
Returns:
|
||||
去重后的最终正文。
|
||||
"""
|
||||
current_content = str(streamed_text or '')
|
||||
terminal = str(terminal_answer or '')
|
||||
|
||||
if replace_answer and terminal.strip():
|
||||
return terminal.strip()
|
||||
if not terminal:
|
||||
return current_content.strip()
|
||||
if not current_content.strip():
|
||||
return terminal.strip()
|
||||
|
||||
current_stripped = current_content.strip()
|
||||
terminal_stripped = terminal.strip()
|
||||
if (
|
||||
terminal_stripped
|
||||
and current_stripped
|
||||
and len(terminal_stripped) >= len(current_stripped)
|
||||
and current_stripped in terminal_stripped
|
||||
):
|
||||
return terminal_stripped
|
||||
if terminal_stripped and current_stripped and terminal_stripped in current_stripped:
|
||||
return current_stripped
|
||||
return (current_content + terminal).strip()
|
||||
|
||||
@staticmethod
|
||||
def _build_final_answer_text(
|
||||
*,
|
||||
streamed_parts: list[str],
|
||||
data: dict,
|
||||
event_name: str,
|
||||
) -> str:
|
||||
"""
|
||||
根据流式片段与终态事件组装最终落库 answer。
|
||||
核心逻辑:先走 _merge_stream_answer_text 去重;workflow_finished 无 answer 时回退 outputs。
|
||||
"""
|
||||
streamed_text = ''.join(streamed_parts)
|
||||
terminal = str(data.get('answer') or '') if data.get('answer') else ''
|
||||
answer_text = DifyService._merge_stream_answer_text(
|
||||
streamed_text,
|
||||
terminal or None,
|
||||
replace_answer=bool(data.get('replace_answer')),
|
||||
)
|
||||
|
||||
if not answer_text and event_name == 'workflow_finished':
|
||||
wf_data = data.get('data') or {}
|
||||
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
|
||||
if isinstance(outputs, dict):
|
||||
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
|
||||
value = outputs.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
if not answer_text:
|
||||
for value in outputs.values():
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
return answer_text
|
||||
|
||||
@staticmethod
|
||||
def _dedupe_exact_doubled_text(text: str) -> str:
|
||||
"""
|
||||
修复历史落库时将同一段正文原样拼接两次的记录。
|
||||
核心逻辑:仅当整段文本可被均分为两段完全相同子串时才裁剪。
|
||||
"""
|
||||
normalized = str(text or '')
|
||||
stripped = normalized.strip()
|
||||
if len(stripped) < 2:
|
||||
return normalized
|
||||
half = len(stripped) // 2
|
||||
if len(stripped) % 2 == 0 and stripped[:half] == stripped[half:]:
|
||||
return stripped[:half]
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not isinstance(data, dict):
|
||||
@@ -896,25 +988,11 @@ class DifyService:
|
||||
return result
|
||||
|
||||
def build_final_answer_text(data: dict, event_name: str) -> str:
|
||||
answer_text = ''.join(full_answer).strip()
|
||||
if data.get('answer'):
|
||||
answer_text = (answer_text + str(data.get('answer') or '')).strip()
|
||||
|
||||
if not answer_text and event_name == 'workflow_finished':
|
||||
wf_data = data.get('data') or {}
|
||||
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
|
||||
if isinstance(outputs, dict):
|
||||
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
|
||||
value = outputs.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
if not answer_text:
|
||||
for value in outputs.values():
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
return answer_text
|
||||
return DifyService._build_final_answer_text(
|
||||
streamed_parts=full_answer,
|
||||
data=data,
|
||||
event_name=event_name,
|
||||
)
|
||||
|
||||
|
||||
max_retries = 3
|
||||
|
||||
@@ -108,6 +108,9 @@
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/TaskNotFound"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/DataSourceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -533,7 +536,8 @@
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
"example": 12,
|
||||
"description": "检核任务 ID(ScheduleTask.id);绑定 解析运行态上下文.task_id_int(Number),勿绑意图识别.task_id"
|
||||
},
|
||||
"trigger_source": {
|
||||
"type": "string",
|
||||
@@ -561,7 +565,7 @@
|
||||
"required": [
|
||||
"task_id"
|
||||
],
|
||||
"description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
|
||||
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
|
||||
},
|
||||
"RunCheckSuccessResponse": {
|
||||
"type": "object",
|
||||
@@ -887,6 +891,21 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"DataSourceUnavailable": {
|
||||
"description": "检核数据源不可用(ODBC/SQL Server 连接失败或 SRM 环境变量未配置)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "data_source_unavailable",
|
||||
"message": "检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,42 @@
|
||||
"""
|
||||
backend/app/services/hxops_tool_api.py
|
||||
文件用途:解析 HXOPS 对外 Tool API 基地址(Dify Chatflow / OpenAPI / 签名下载链接)。
|
||||
|
||||
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
|
||||
依赖:Flask current_app / request。
|
||||
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, has_request_context, request
|
||||
|
||||
|
||||
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
|
||||
"""返回无尾斜杠的 hxops 对外根地址,如 http://192.168.100.192:8891。"""
|
||||
cfg = config
|
||||
if cfg is None and current_app:
|
||||
cfg = current_app.config
|
||||
cfg = cfg or {}
|
||||
def _resolve_config(config: dict | None = None) -> dict:
|
||||
"""读取 Flask config 或空 dict。"""
|
||||
if config is not None:
|
||||
return config
|
||||
if current_app:
|
||||
return current_app.config
|
||||
return {}
|
||||
|
||||
for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOLS_API_BASE", "PUBLIC_BASE_URL"):
|
||||
configured = str(cfg.get(key) or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
|
||||
"""
|
||||
返回 Dify / RPA 等服务端调用 Tool API 时使用的根地址(无尾斜杠)。
|
||||
|
||||
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
|
||||
|
||||
Args:
|
||||
config: 可选配置字典;缺省时读 current_app.config。
|
||||
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
|
||||
|
||||
Returns:
|
||||
无尾斜杠的根地址,如 http://192.168.100.192:8890。
|
||||
"""
|
||||
cfg = _resolve_config(config)
|
||||
|
||||
configured = str(cfg.get("HXOPS_TOOLS_API_BASE") or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
host = request_host
|
||||
if host is None and has_request_context():
|
||||
@@ -25,3 +44,26 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
|
||||
return host or ""
|
||||
|
||||
|
||||
def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
|
||||
"""
|
||||
返回浏览器侧可访问的根地址,用于 Excel 签名下载等用户可见链接。
|
||||
|
||||
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
|
||||
|
||||
Args:
|
||||
config: 可选配置字典;缺省时读 current_app.config。
|
||||
|
||||
Returns:
|
||||
无尾斜杠的根地址,如 https://ai.example.com。
|
||||
"""
|
||||
cfg = _resolve_config(config)
|
||||
|
||||
for key in ("HXOPS_PUBLIC_BASE_URL", "WECOM_PUBLIC_BASE_URL"):
|
||||
configured = str(cfg.get(key) or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if has_request_context():
|
||||
return request.host_url.rstrip("/")
|
||||
|
||||
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
|
||||
Reference in new issue
Block a user