248 lines
9.7 KiB
Python
248 lines
9.7 KiB
Python
"""
|
|
backend/app/services/admin/faq_service.py
|
|
|
|
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
|
|
依赖:models、faq_kb_invalidation、hot_faq_* services、faq_text_utils(模糊阈值钳制)。
|
|
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from app import db
|
|
from app.core.errors import NotFoundError, ValidationError
|
|
from app.models import Agent, KbDocument, QuickQuestion
|
|
from app.services.faq_text_utils import clamp_fuzzy_threshold
|
|
|
|
|
|
def parse_aliases(raw_aliases) -> list[str]:
|
|
"""解析别名列表,支持 JSON 数组或换行分隔字符串。"""
|
|
if raw_aliases is None:
|
|
return []
|
|
if isinstance(raw_aliases, list):
|
|
items = [str(item).strip() for item in raw_aliases if str(item).strip()]
|
|
elif isinstance(raw_aliases, str):
|
|
items = [line.strip() for line in raw_aliases.splitlines() if line.strip()]
|
|
else:
|
|
return []
|
|
seen: set[str] = set()
|
|
result: list[str] = []
|
|
for item in items:
|
|
if item not in seen:
|
|
seen.add(item)
|
|
result.append(item)
|
|
return result
|
|
|
|
|
|
def parse_expires_at(raw_value) -> datetime | None:
|
|
"""解析 FAQ 过期时间 ISO 字符串。"""
|
|
if not raw_value:
|
|
return None
|
|
text = str(raw_value).strip()
|
|
if not text:
|
|
return None
|
|
try:
|
|
return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None)
|
|
except ValueError as exc:
|
|
raise ValidationError('Invalid expires_at format') from exc
|
|
|
|
|
|
def serialize_quick_question(
|
|
q: QuickQuestion,
|
|
agent_name: str,
|
|
stale_kb_document: KbDocument | None = None,
|
|
) -> dict:
|
|
"""序列化全局常用问题供管理端展示。"""
|
|
return {
|
|
'id': q.id,
|
|
'title': q.title,
|
|
'question': q.question,
|
|
'answer': q.answer,
|
|
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
|
'cache_enabled': bool(q.cache_enabled),
|
|
'is_enabled': bool(q.is_enabled),
|
|
'fuzzy_enabled': bool(getattr(q, 'fuzzy_enabled', False)),
|
|
'fuzzy_threshold': clamp_fuzzy_threshold(getattr(q, 'fuzzy_threshold', None)),
|
|
'hit_count': q.hit_count or 0,
|
|
'agent_id': q.agent_id,
|
|
'agent_name': agent_name,
|
|
'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,
|
|
}
|
|
|
|
|
|
def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None:
|
|
"""将请求体字段写入 QuickQuestion 实例。"""
|
|
if 'title' in data:
|
|
qq.title = str(data['title']).strip()
|
|
if 'question' in data:
|
|
qq.question = str(data['question']).strip()
|
|
if 'agent_id' in data:
|
|
qq.agent_id = data['agent_id']
|
|
if 'sort_order' in data:
|
|
qq.sort_order = data.get('sort_order', 0)
|
|
if 'answer' in data:
|
|
qq.answer = str(data['answer']).strip() or None
|
|
if 'aliases' in data:
|
|
qq.aliases = parse_aliases(data['aliases'])
|
|
if 'cache_enabled' in data:
|
|
qq.cache_enabled = bool(data['cache_enabled'])
|
|
if 'is_enabled' in data:
|
|
qq.is_enabled = bool(data['is_enabled'])
|
|
if 'fuzzy_enabled' in data:
|
|
qq.fuzzy_enabled = bool(data['fuzzy_enabled'])
|
|
if 'fuzzy_threshold' in data:
|
|
qq.fuzzy_threshold = clamp_fuzzy_threshold(data['fuzzy_threshold'])
|
|
else:
|
|
qq.fuzzy_threshold = clamp_fuzzy_threshold(qq.fuzzy_threshold)
|
|
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 缓存时必须填写标准答案')
|
|
if qq.fuzzy_enabled and not qq.cache_enabled:
|
|
raise ValidationError('启用模糊匹配前需先启用 FAQ 缓存')
|
|
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
|
raise ValidationError('Missing required fields')
|
|
|
|
|
|
def list_quick_questions(*, stale_only: bool = False) -> list[dict]:
|
|
"""列出全局常用问题(user_id IS NULL)。"""
|
|
query = (
|
|
db.session.query(QuickQuestion)
|
|
.filter(QuickQuestion.user_id.is_(None))
|
|
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
|
)
|
|
if stale_only:
|
|
query = query.filter(QuickQuestion.stale_at.isnot(None))
|
|
rows = []
|
|
for q in query.all():
|
|
agent = db.session.get(Agent, q.agent_id)
|
|
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
|
|
rows.append(serialize_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
|
|
return rows
|
|
|
|
|
|
def create_quick_question(data: dict[str, Any]) -> dict:
|
|
"""创建全局 QuickQuestion。"""
|
|
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()
|
|
return {'id': qq.id}
|
|
|
|
|
|
def update_quick_question(question_id: int, data: dict[str, Any]) -> None:
|
|
"""更新全局 QuickQuestion。"""
|
|
qq = db.session.get(QuickQuestion, question_id)
|
|
if not qq or qq.user_id is not None:
|
|
raise NotFoundError('Not found')
|
|
apply_quick_question_payload(qq, data)
|
|
qq.updated_at = datetime.utcnow()
|
|
db.session.commit()
|
|
|
|
|
|
def delete_quick_question(question_id: int) -> None:
|
|
"""删除 QuickQuestion(不存在时静默成功)。"""
|
|
qq = db.session.get(QuickQuestion, question_id)
|
|
if qq:
|
|
db.session.delete(qq)
|
|
db.session.commit()
|
|
|
|
|
|
def list_faq_candidates(*, agent_id: int | None = None) -> dict:
|
|
"""列出热点 FAQ 候选及统计。"""
|
|
from app.services.hot_faq_aggregator import HotFaqAggregator
|
|
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
|
|
|
items = HotFaqCandidateStore.list_candidates(agent_id)
|
|
return {
|
|
'items': items,
|
|
'stats': HotFaqCandidateStore.summarize(items),
|
|
'rules': HotFaqAggregator.get_rules_document(),
|
|
}
|
|
|
|
|
|
def refresh_faq_candidates(*, agent_id: int | None, dry_run: bool) -> dict:
|
|
"""手动触发离线热点聚合。"""
|
|
from app.services.hot_faq_aggregator import HotFaqAggregator
|
|
|
|
return HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
|
|
|
|
|
def promote_faq_candidate(data: dict[str, Any]) -> dict:
|
|
"""将热点候选晋升为全局 QuickQuestion。"""
|
|
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
|
from app.services.faq_text_utils import normalize_faq_query
|
|
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
|
|
|
agent_id = data.get('agent_id')
|
|
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
|
|
if not agent_id or not q_norm:
|
|
raise ValidationError('agent_id and q_norm are required')
|
|
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
|
|
if not candidate:
|
|
raise NotFoundError('FAQ candidate not found')
|
|
|
|
title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100]
|
|
question = str(candidate.get('canonical_query') or q_norm).strip()
|
|
answer = str(candidate.get('answer') or '').strip()
|
|
if not answer:
|
|
raise ValidationError('Candidate has no answer')
|
|
|
|
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),
|
|
title=title,
|
|
question=question,
|
|
answer=answer,
|
|
aliases=aliases or None,
|
|
cache_enabled=True,
|
|
is_enabled=True,
|
|
retriever_resources=retriever_resources,
|
|
sort_order=int(data.get('sort_order') or 0),
|
|
updated_at=datetime.utcnow(),
|
|
)
|
|
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):
|
|
db.session.rollback()
|
|
raise NotFoundError('FAQ candidate not found')
|
|
db.session.commit()
|
|
return {'id': qq.id, 'status': 'ok'}
|
|
|
|
|
|
def dismiss_faq_candidate(*, agent_id: int, q_norm: str) -> dict:
|
|
"""忽略热点 FAQ 候选。"""
|
|
from app.services.faq_text_utils import normalize_faq_query
|
|
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
|
|
|
normalized = normalize_faq_query(q_norm)
|
|
if not agent_id or not normalized:
|
|
raise ValidationError('agent_id and q_norm are required')
|
|
HotFaqCandidateStore.dismiss(int(agent_id), normalized)
|
|
return {'status': 'ok'}
|