feat(faq): 缓存高频问题及答案,命中直接返回预置答案,不走dify
This commit is contained in:
1 parent
3264ed1e07
commit
cf7cc11ffc
32 files changed
+3504
-180
No files matched your search
+237
-14
@@ -697,39 +697,148 @@ def reject_request(id):
|
||||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_quick_questions():
|
||||
qqs = db.session.query(QuickQuestion).filter(QuickQuestion.user_id == None).order_by(QuickQuestion.sort_order.asc()).all()
|
||||
"""
|
||||
列出全局常用问题(含 FAQ 缓存字段)。
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count 等扩展字段
|
||||
"""
|
||||
qqs = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
)
|
||||
res = []
|
||||
for q in qqs:
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
res.append({'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id, 'agent_name': agent.name if agent else 'Unknown', 'sort_order': q.sort_order})
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown'))
|
||||
return jsonify(res)
|
||||
|
||||
|
||||
def _parse_aliases(raw_aliases) -> list[str]:
|
||||
"""
|
||||
解析别名列表,支持 JSON 数组或换行分隔字符串。
|
||||
@param raw_aliases - 请求体 aliases 字段
|
||||
@returns 去重后的别名字符串列表
|
||||
"""
|
||||
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 过期时间。
|
||||
@param raw_value - ISO 字符串或 None
|
||||
@returns datetime 或 None
|
||||
"""
|
||||
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:
|
||||
raise ValidationError('Invalid expires_at format')
|
||||
|
||||
|
||||
def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
"""
|
||||
序列化全局常用问题供管理端展示。
|
||||
@param q - QuickQuestion 实例
|
||||
@param agent_name - 所属应用名称
|
||||
@returns 可 JSON 化的字典
|
||||
"""
|
||||
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),
|
||||
'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,
|
||||
}
|
||||
|
||||
|
||||
def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None:
|
||||
"""
|
||||
将请求体字段写入 QuickQuestion 实例。
|
||||
@param qq - 待更新的 QuickQuestion
|
||||
@param data - 请求 JSON
|
||||
@param require_answer - 创建时为 True,cache_enabled 时强制校验 answer
|
||||
"""
|
||||
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 'expires_at' in data:
|
||||
qq.expires_at = _parse_expires_at(data['expires_at'])
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
||||
raise ValidationError('Missing required fields')
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_quick_question():
|
||||
"""
|
||||
创建全局常用问题,可选启用 FAQ 缓存。
|
||||
@returns 201 + {id}
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||||
raise ValidationError('Missing required fields')
|
||||
qq = QuickQuestion(user_id=None, agent_id=data['agent_id'], title=data['title'], question=data['question'], sort_order=data.get('sort_order', 0))
|
||||
qq = QuickQuestion(user_id=None)
|
||||
_apply_quick_question_payload(qq, data, require_answer=True)
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return (jsonify({'id': qq.id}), 201)
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_quick_question(id):
|
||||
"""
|
||||
更新全局常用问题及 FAQ 缓存配置。
|
||||
@returns {status: ok}
|
||||
"""
|
||||
qq = db.session.get(QuickQuestion, id)
|
||||
if not qq:
|
||||
if not qq or qq.user_id is not None:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data:
|
||||
qq.sort_order = data['sort_order']
|
||||
_apply_quick_question_payload(qq, data)
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -742,6 +851,120 @@ def delete_quick_question(id):
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_faq_candidates():
|
||||
"""
|
||||
列出 PostgreSQL 中的热点 FAQ 候选(离线聚合结果)。
|
||||
@query agent_id - 可选,按应用筛选
|
||||
@returns { items, stats, rules }
|
||||
"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
agent_id = request.args.get('agent_id', type=int)
|
||||
items = HotFaqCandidateStore.list_candidates(agent_id)
|
||||
stats = HotFaqCandidateStore.summarize(items)
|
||||
return jsonify({
|
||||
'items': items,
|
||||
'stats': stats,
|
||||
'rules': HotFaqAggregator.get_rules_document(),
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
|
||||
@require_admin
|
||||
def refresh_faq_candidates():
|
||||
"""
|
||||
手动触发离线热点聚合。
|
||||
@body agent_id - 可选;dry_run - 可选,仅预览
|
||||
@returns 聚合结果摘要
|
||||
"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id')
|
||||
dry_run = bool(data.get('dry_run'))
|
||||
if agent_id is not None:
|
||||
agent_id = int(agent_id)
|
||||
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
|
||||
@require_admin
|
||||
def promote_faq_candidate():
|
||||
"""
|
||||
将热点候选晋升为全局 QuickQuestion(启用 FAQ 缓存),同事务更新候选状态。
|
||||
@body agent_id, q_norm - 必填;title - 可选
|
||||
@returns { id } 新建 QuickQuestion 主键
|
||||
"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
data = request.get_json() or {}
|
||||
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]
|
||||
|
||||
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=candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
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 jsonify({'id': qq.id, 'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
|
||||
@require_admin
|
||||
def dismiss_faq_candidate():
|
||||
"""
|
||||
忽略热点候选:标记 dismissed 并设置 deny_until。
|
||||
@body agent_id, q_norm - 必填
|
||||
@returns { status: ok }
|
||||
"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
data = request.get_json() or {}
|
||||
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')
|
||||
|
||||
HotFaqCandidateStore.dismiss(int(agent_id), q_norm)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
|
||||
Reference in new issue
Block a user