feat(faq): 知识库相对应文档更新,标记关联的问题为待复审状态并暂停缓存命中
This commit is contained in:
1 parent
757231e3d5
commit
0d59b23e0c
16 files changed
+809
-185
No files matched your search
@@ -6,7 +6,7 @@ backend/app/api/admin.py
|
||||
逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide, KbDocument
|
||||
from app.services.minio_service import minio_service
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
@@ -840,18 +840,23 @@ def reject_request(id):
|
||||
def list_quick_questions():
|
||||
"""
|
||||
列出全局常用问题(含 FAQ 缓存字段)。
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count 等扩展字段
|
||||
@query stale_only - 可选,true 时仅返回待复审(stale_at 非空)条目
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count/stale_* 等扩展字段
|
||||
"""
|
||||
qqs = (
|
||||
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||
query = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
)
|
||||
if stale_only:
|
||||
query = query.filter(QuickQuestion.stale_at.isnot(None))
|
||||
qqs = query.all()
|
||||
res = []
|
||||
for q in qqs:
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown'))
|
||||
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
|
||||
return jsonify(res)
|
||||
|
||||
|
||||
@@ -895,11 +900,16 @@ def _parse_expires_at(raw_value) -> datetime | None:
|
||||
raise ValidationError('Invalid expires_at format')
|
||||
|
||||
|
||||
def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
def _serialize_admin_quick_question(
|
||||
q: QuickQuestion,
|
||||
agent_name: str,
|
||||
stale_kb_document: KbDocument | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
序列化全局常用问题供管理端展示。
|
||||
@param q - QuickQuestion 实例
|
||||
@param agent_name - 所属应用名称
|
||||
@param stale_kb_document - 触发待复审的 KB 文档(可选)
|
||||
@returns 可 JSON 化的字典
|
||||
"""
|
||||
return {
|
||||
@@ -916,6 +926,11 @@ def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
'sort_order': q.sort_order,
|
||||
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
|
||||
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
|
||||
'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [],
|
||||
'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None,
|
||||
'stale_reason': q.stale_reason,
|
||||
'stale_kb_document_id': q.stale_kb_document_id,
|
||||
'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -944,6 +959,14 @@ def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answ
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = _parse_expires_at(data['expires_at'])
|
||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
if data.get('clear_stale'):
|
||||
from app.services.faq_kb_invalidation import clear_faq_stale
|
||||
|
||||
clear_faq_stale(qq)
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
@@ -961,6 +984,10 @@ def create_quick_question():
|
||||
data = request.get_json() or {}
|
||||
qq = QuickQuestion(user_id=None)
|
||||
_apply_quick_question_payload(qq, data, require_answer=True)
|
||||
if isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
@@ -1063,6 +1090,7 @@ def promote_faq_candidate():
|
||||
|
||||
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
|
||||
|
||||
retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=int(agent_id),
|
||||
@@ -1072,10 +1100,13 @@ def promote_faq_candidate():
|
||||
aliases=aliases or None,
|
||||
cache_enabled=True,
|
||||
is_enabled=True,
|
||||
retriever_resources=candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None,
|
||||
retriever_resources=retriever_resources,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, retriever_resources)
|
||||
db.session.add(qq)
|
||||
db.session.flush()
|
||||
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
|
||||
|
||||
@@ -291,7 +291,11 @@ class QuickQuestion(Base):
|
||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||
hit_count: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
stale_kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@@ -82,6 +82,7 @@ class FaqCacheService:
|
||||
QuickQuestion.is_enabled.is_(True),
|
||||
QuickQuestion.answer.isnot(None),
|
||||
QuickQuestion.answer != "",
|
||||
QuickQuestion.stale_at.is_(None),
|
||||
)
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
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.models import KbDifySyncRecord, QuickQuestion, db
|
||||
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,
|
||||
)
|
||||
@@ -10,6 +10,7 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
@@ -312,6 +313,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
previous_sync_hash = existing_record.sync_hash if existing_record else None
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
@@ -401,6 +403,35 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
content_changed = previous_sync_hash != sync_hash
|
||||
if content_changed:
|
||||
try:
|
||||
from app.services.faq_kb_invalidation import (
|
||||
STALE_REASON_KB_UPDATED,
|
||||
invalidate_faqs_for_kb_document,
|
||||
)
|
||||
|
||||
invalidated = invalidate_faqs_for_kb_document(
|
||||
document.id,
|
||||
reason=STALE_REASON_KB_UPDATED,
|
||||
dataset_id=str(dataset_id),
|
||||
remote_document_id=str(remote_document_id),
|
||||
)
|
||||
if current_app and invalidated:
|
||||
current_app.logger.info(
|
||||
'[faq-kb-invalidation] kb_document_updated id=%s invalidated=%s',
|
||||
document.id,
|
||||
invalidated,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] hook failed document_id=%s: %s',
|
||||
document.id,
|
||||
exc,
|
||||
)
|
||||
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
@@ -445,4 +476,32 @@ def delete_document_from_dify(document_id: int) -> dict:
|
||||
deleted_count += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
from app.services.faq_kb_invalidation import (
|
||||
STALE_REASON_KB_DELETED,
|
||||
invalidate_faqs_for_kb_document,
|
||||
)
|
||||
|
||||
latest = records[0] if records else None
|
||||
invalidated = invalidate_faqs_for_kb_document(
|
||||
int(document_id),
|
||||
reason=STALE_REASON_KB_DELETED,
|
||||
dataset_id=str(latest.dataset_id) if latest and latest.dataset_id else None,
|
||||
remote_document_id=str(latest.remote_document_id) if latest and latest.remote_document_id else None,
|
||||
)
|
||||
if current_app and invalidated:
|
||||
current_app.logger.info(
|
||||
'[faq-kb-invalidation] kb_document_deleted id=%s invalidated=%s',
|
||||
document_id,
|
||||
invalidated,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] delete hook failed document_id=%s: %s',
|
||||
document_id,
|
||||
exc,
|
||||
)
|
||||
|
||||
return {'deleted': True, 'remote_document_count': deleted_count}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/migrations/versions/c6d7e8f9a0b1_add_faq_kb_stale_fields.py
|
||||
|
||||
用途:为 quick_questions 增加 KB 关联与待复审(stale)字段,支持方案 B 失效标记。
|
||||
依赖:alembic.op、sqlalchemy。
|
||||
逻辑:KB sync 成功后按 source_kb_document_ids / retriever_resources 标记 FAQ 待复审。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "c6d7e8f9a0b1"
|
||||
down_revision = "c5d6e7f8a9b0"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("source_kb_document_ids", sa.JSON(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_reason", sa.String(length=64), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_kb_document_id", sa.Integer(), nullable=True),
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_quick_questions_stale_kb_document_id",
|
||||
"quick_questions",
|
||||
"kb_documents",
|
||||
["stale_kb_document_id"],
|
||||
["id"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_quick_questions_stale_at",
|
||||
"quick_questions",
|
||||
["stale_at"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index("ix_quick_questions_stale_at", table_name="quick_questions")
|
||||
op.drop_constraint(
|
||||
"fk_quick_questions_stale_kb_document_id",
|
||||
"quick_questions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_column("quick_questions", "stale_kb_document_id")
|
||||
op.drop_column("quick_questions", "stale_reason")
|
||||
op.drop_column("quick_questions", "stale_at")
|
||||
op.drop_column("quick_questions", "source_kb_document_ids")
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/tests/test_faq_kb_invalidation.py
|
||||
|
||||
用途:FAQ 与 KB 文档关联解析及失效标记单元测试。
|
||||
"""
|
||||
from app.services.faq_kb_invalidation import (
|
||||
_faq_links_kb_document,
|
||||
extract_dify_id_pairs,
|
||||
merge_source_kb_document_ids,
|
||||
)
|
||||
from app.models import QuickQuestion
|
||||
|
||||
|
||||
def test_extract_dify_id_pairs_from_retriever_resources():
|
||||
resources = [
|
||||
{'dataset_id': 'ds-1', 'document_id': 'doc-1'},
|
||||
{'metadata': {'dify_dataset_id': 'ds-2', 'remote_document_id': 'doc-2'}},
|
||||
]
|
||||
pairs = extract_dify_id_pairs(resources)
|
||||
assert ('ds-1', 'doc-1') in pairs
|
||||
assert ('ds-2', 'doc-2') in pairs
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_source_ids():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
source_kb_document_ids=[10, 20],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 10, None, None) is True
|
||||
assert _faq_links_kb_document(qq, 99, None, None) is False
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_retriever_resources():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
retriever_resources=[{'dataset_id': 'ds-a', 'document_id': 'remote-a'}],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-a', 'remote-a') is True
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-b', 'remote-a') is False
|
||||
|
||||
|
||||
def test_merge_source_kb_document_ids():
|
||||
merged = merge_source_kb_document_ids([1], None)
|
||||
assert merged == [1]
|
||||
Reference in new issue
Block a user