226 lines
7.7 KiB
Python
226 lines
7.7 KiB
Python
"""
|
|
backend/app/services/faq_kb_invalidation.py
|
|
|
|
用途:知识库文档更新/删除时,标记关联 FAQ 为待复审并暂停 L1 缓存命中。
|
|
依赖:models.QuickQuestion、KbDifySyncRecord、DifyService._extract_dify_ids、IntegrationApiService。
|
|
逻辑:dify_sync_service 同步成功后调用 invalidate_faqs_for_kb_document;晋升 FAQ 时写入 source_kb_document_ids。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any, Optional
|
|
|
|
from flask import current_app
|
|
|
|
from app import db
|
|
from app.models import KbDifySyncRecord, QuickQuestion
|
|
from app.services.dify import DifyService
|
|
from app.services.integration_api import IntegrationApiService
|
|
|
|
STALE_REASON_KB_UPDATED = 'kb_document_updated'
|
|
STALE_REASON_KB_DELETED = 'kb_document_deleted'
|
|
|
|
|
|
def extract_dify_id_pairs(retriever_resources: list | None) -> list[tuple[str, str]]:
|
|
"""
|
|
从 retriever_resources 提取 (dataset_id, remote_document_id) 对。
|
|
@param retriever_resources - ChatLog / FAQ 上的引用元数据
|
|
@returns 去重后的 Dify ID 对列表
|
|
"""
|
|
if not isinstance(retriever_resources, list):
|
|
return []
|
|
pairs: list[tuple[str, str]] = []
|
|
seen: set[tuple[str, str]] = set()
|
|
for item in retriever_resources:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
dataset_id, remote_document_id = DifyService._extract_dify_ids(item)
|
|
if not dataset_id or not remote_document_id:
|
|
continue
|
|
key = (str(dataset_id), str(remote_document_id))
|
|
if key in seen:
|
|
continue
|
|
seen.add(key)
|
|
pairs.append(key)
|
|
return pairs
|
|
|
|
|
|
def resolve_kb_document_ids_from_resources(retriever_resources: list | None) -> list[int]:
|
|
"""
|
|
将 retriever_resources 解析为本地 kb_documents.id 列表。
|
|
核心逻辑:优先 IntegrationApiService 本地映射,失败则查 KbDifySyncRecord。
|
|
@param retriever_resources - Dify 检索引用列表
|
|
@returns 去重后的文档主键列表
|
|
"""
|
|
doc_ids: list[int] = []
|
|
seen: set[int] = set()
|
|
for dataset_id, remote_document_id in extract_dify_id_pairs(retriever_resources):
|
|
local_doc_id: Optional[int] = None
|
|
try:
|
|
payload = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
|
if payload and payload.get('document_id') is not None:
|
|
local_doc_id = int(payload['document_id'])
|
|
except Exception:
|
|
local_doc_id = None
|
|
if local_doc_id is None:
|
|
record = (
|
|
db.session.query(KbDifySyncRecord.document_id)
|
|
.filter(
|
|
KbDifySyncRecord.dataset_id == str(dataset_id),
|
|
KbDifySyncRecord.remote_document_id == str(remote_document_id),
|
|
)
|
|
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
|
.first()
|
|
)
|
|
if record and record[0] is not None:
|
|
local_doc_id = int(record[0])
|
|
if local_doc_id is not None and local_doc_id not in seen:
|
|
seen.add(local_doc_id)
|
|
doc_ids.append(local_doc_id)
|
|
return doc_ids
|
|
|
|
|
|
def merge_source_kb_document_ids(
|
|
existing: list | None,
|
|
retriever_resources: list | None,
|
|
) -> list[int] | None:
|
|
"""
|
|
合并已有 source_kb_document_ids 与 retriever_resources 解析结果。
|
|
@returns 合并去重后的 ID 列表;无有效 ID 时返回 None
|
|
"""
|
|
merged: list[int] = []
|
|
seen: set[int] = set()
|
|
for raw in (existing if isinstance(existing, list) else []):
|
|
try:
|
|
doc_id = int(raw)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if doc_id not in seen:
|
|
seen.add(doc_id)
|
|
merged.append(doc_id)
|
|
for doc_id in resolve_kb_document_ids_from_resources(retriever_resources):
|
|
if doc_id not in seen:
|
|
seen.add(doc_id)
|
|
merged.append(doc_id)
|
|
return merged or None
|
|
|
|
|
|
def _faq_links_kb_document(
|
|
qq: QuickQuestion,
|
|
document_id: int,
|
|
dataset_id: str | None,
|
|
remote_document_id: str | None,
|
|
) -> bool:
|
|
"""判断 FAQ 是否关联指定 KB 文档(本地 ID 或 Dify ID 对)。"""
|
|
source_ids = qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else []
|
|
for raw in source_ids:
|
|
try:
|
|
if int(raw) == int(document_id):
|
|
return True
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if not dataset_id or not remote_document_id:
|
|
return False
|
|
target = (str(dataset_id), str(remote_document_id))
|
|
return target in extract_dify_id_pairs(
|
|
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None
|
|
)
|
|
|
|
|
|
def find_linked_faqs(
|
|
document_id: int,
|
|
*,
|
|
dataset_id: str | None = None,
|
|
remote_document_id: str | None = None,
|
|
cache_enabled_only: bool = True,
|
|
) -> list[QuickQuestion]:
|
|
"""
|
|
查找与 KB 文档关联的全局 FAQ。
|
|
@param cache_enabled_only - True 时仅扫描 cache_enabled 条目
|
|
@returns 匹配的 QuickQuestion 列表
|
|
"""
|
|
query = db.session.query(QuickQuestion).filter(QuickQuestion.user_id.is_(None))
|
|
if cache_enabled_only:
|
|
query = query.filter(QuickQuestion.cache_enabled.is_(True))
|
|
rows = query.all()
|
|
return [
|
|
row
|
|
for row in rows
|
|
if _faq_links_kb_document(row, document_id, dataset_id, remote_document_id)
|
|
]
|
|
|
|
|
|
def mark_faq_stale(qq: QuickQuestion, *, document_id: int, reason: str) -> None:
|
|
"""
|
|
将 FAQ 标记为待复审并暂停缓存。
|
|
核心逻辑:写 stale_* 字段,cache_enabled=false,用户提问将回退 Dify。
|
|
"""
|
|
now = datetime.utcnow()
|
|
qq.stale_at = now
|
|
qq.stale_reason = reason
|
|
qq.stale_kb_document_id = document_id
|
|
qq.cache_enabled = False
|
|
qq.updated_at = now
|
|
|
|
|
|
def clear_faq_stale(qq: QuickQuestion) -> None:
|
|
"""清除 FAQ 待复审标记。"""
|
|
qq.stale_at = None
|
|
qq.stale_reason = None
|
|
qq.stale_kb_document_id = None
|
|
|
|
|
|
def invalidate_faqs_for_kb_document(
|
|
document_id: int,
|
|
*,
|
|
reason: str,
|
|
dataset_id: str | None = None,
|
|
remote_document_id: str | None = None,
|
|
) -> int:
|
|
"""
|
|
KB 文档变更后,标记所有关联 FAQ 为待复审。
|
|
@param document_id - kb_documents.id
|
|
@param reason - stale_reason 枚举值
|
|
@param dataset_id - 可选,Dify dataset_id
|
|
@param remote_document_id - 可选,Dify remote document id
|
|
@returns 标记条数
|
|
"""
|
|
if not document_id:
|
|
return 0
|
|
try:
|
|
linked = find_linked_faqs(
|
|
int(document_id),
|
|
dataset_id=dataset_id,
|
|
remote_document_id=remote_document_id,
|
|
cache_enabled_only=True,
|
|
)
|
|
if not linked:
|
|
return 0
|
|
for qq in linked:
|
|
mark_faq_stale(qq, document_id=int(document_id), reason=reason)
|
|
db.session.commit()
|
|
return len(linked)
|
|
except Exception as exc:
|
|
db.session.rollback()
|
|
if current_app:
|
|
current_app.logger.warning(
|
|
'[faq-kb-invalidation] invalidate failed document_id=%s: %s',
|
|
document_id,
|
|
exc,
|
|
)
|
|
return 0
|
|
|
|
|
|
def apply_retriever_resources_to_faq(qq: QuickQuestion, retriever_resources: Any) -> None:
|
|
"""
|
|
将 retriever_resources 写入 FAQ,并解析 source_kb_document_ids。
|
|
@param qq - QuickQuestion 实例
|
|
@param retriever_resources - 引用列表或 None
|
|
"""
|
|
if isinstance(retriever_resources, list) and retriever_resources:
|
|
qq.retriever_resources = retriever_resources
|
|
qq.source_kb_document_ids = merge_source_kb_document_ids(
|
|
qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else None,
|
|
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None,
|
|
)
|