""" backend/app/services/faq_cache.py 用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。 依赖:models.QuickQuestion、ChatLog、SQLAlchemy db、faq_text_utils(归一化与模糊评分)。 逻辑:chat router 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled)。 匹配分两阶段:[STEP 1] 归一化精确命中(所有启用缓存的条目);[STEP 2] 模糊兜底 (仅 fuzzy_enabled 条目,得分达该条目阈值才命中),命中后 stream_chat 返回预置答案。 """ import json import time from dataclasses import dataclass from datetime import datetime from typing import Any, Optional from flask import current_app from app import db from app.models import ChatLog, QuickQuestion from app.services.faq_text_utils import ( FUZZY_MIN_LENGTH, clamp_fuzzy_threshold, fuzzy_match_score, normalize_faq_query, ) # 命中类型(写入 ChatLog payload 与 SSE metadata,供审计与排障) MATCH_TYPE_EXACT = 'exact' MATCH_TYPE_FUZZY = 'fuzzy' @dataclass(frozen=True) class FaqCacheMatch: """FAQ 缓存命中结果:条目本体 + 命中方式审计信息。""" entry: QuickQuestion match_type: str # 'exact' 归一化全等;'fuzzy' 模糊兜底 match_score: Optional[float] = None matched_text: Optional[str] = None class FaqCacheService: """全局常用问题 FAQ 缓存服务。""" @staticmethod def _normalize_text(text: str) -> str: """ 归一化问句文本,便于精确/别名匹配。 核心逻辑:委托 faq_text_utils.normalize_faq_query,与热点聚合共用规则。 @param text - 原始问句 @returns 归一化后的字符串 """ return normalize_faq_query(text) @staticmethod def _is_expired(entry: QuickQuestion) -> bool: """ 判断 FAQ 条目是否已过期。 @param entry - QuickQuestion 实例 @returns 过期返回 True """ expires_at = getattr(entry, "expires_at", None) if not expires_at: return False return expires_at <= datetime.utcnow() @staticmethod def _candidate_pairs(entry: QuickQuestion) -> list[tuple[str, str]]: """ 收集条目可用于匹配的 (原文, 归一化文本) 对。 核心逻辑:候选来源为 question、title 与 aliases;原文用于审计展示,归一化文本用于比对。 @param entry - QuickQuestion 实例 @returns (原文, 归一化文本) 列表 """ pairs: list[tuple[str, str]] = [] for raw in (entry.question, entry.title): normalized = FaqCacheService._normalize_text(raw) if normalized: pairs.append((str(raw), normalized)) aliases = entry.aliases if isinstance(entry.aliases, list) else [] for alias in aliases: normalized = FaqCacheService._normalize_text(str(alias)) if normalized: pairs.append((str(alias), normalized)) return pairs @staticmethod def _candidate_texts(entry: QuickQuestion) -> list[str]: """ 收集条目可用于匹配的标准化文本集合。 核心逻辑:委托 _candidate_pairs 取归一化列;热点聚合(hot_faq_aggregator)依赖本方法做去重比对。 @param entry - QuickQuestion 实例 @returns 归一化后的候选文本列表 """ return [normalized for _, normalized in FaqCacheService._candidate_pairs(entry)] @staticmethod def try_match(query: str, agent_id: int) -> Optional[FaqCacheMatch]: """ 尝试为指定 Agent 命中全局 FAQ 缓存条目(两阶段)。 核心逻辑: [STEP 1] 精确阶段——所有 cache_enabled 条目的 question/title/aliases 归一化后与输入全等比对; [STEP 2] 模糊兜底——精确未命中且输入长度达 FUZZY_MIN_LENGTH 时,仅对 fuzzy_enabled 条目 计算 fuzzy_match_score,最高分达到该条目阈值(钳制在 0.5~1.0)才命中; 同分时先出现的条目(sort_order 靠前)胜出。 is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。 @param query - 用户提问 @param agent_id - 当前 Agent 主键 @returns FaqCacheMatch;未命中返回 None """ normalized_query = FaqCacheService._normalize_text(query) if not normalized_query or not agent_id: return None entries = ( db.session.query(QuickQuestion) .filter( QuickQuestion.user_id.is_(None), QuickQuestion.agent_id == agent_id, QuickQuestion.cache_enabled.is_(True), QuickQuestion.answer.isnot(None), QuickQuestion.answer != "", QuickQuestion.stale_at.is_(None), ) .order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc()) .all() ) # [STEP 1] 精确命中:归一化后全等,任何启用缓存的条目参与 for entry in entries: if FaqCacheService._is_expired(entry): continue for raw, normalized in FaqCacheService._candidate_pairs(entry): if normalized_query == normalized: return FaqCacheMatch( entry=entry, match_type=MATCH_TYPE_EXACT, match_score=1.0, matched_text=raw ) # [STEP 2] 模糊兜底:仅参与模糊开关打开的条目,取最高分;短问句不参与 if len(normalized_query) < FUZZY_MIN_LENGTH: return None best: Optional[FaqCacheMatch] = None for entry in entries: if not entry.fuzzy_enabled: continue if FaqCacheService._is_expired(entry): continue threshold = clamp_fuzzy_threshold(entry.fuzzy_threshold) for raw, normalized in FaqCacheService._candidate_pairs(entry): if len(normalized) < FUZZY_MIN_LENGTH: continue score = fuzzy_match_score(normalized_query, normalized) if score >= threshold and (best is None or score > (best.match_score or 0.0)): best = FaqCacheMatch( entry=entry, match_type=MATCH_TYPE_FUZZY, match_score=score, matched_text=raw ) return best @staticmethod def _match_audit_fields(match: Optional[FaqCacheMatch]) -> dict[str, Any]: """ 构造命中方式的审计字段,写入 ChatLog payload 与 SSE metadata。 @param match - try_match 的命中结果;可为 None(历史调用方未传) @returns 含 match_type / match_score / matched_text 的字典 """ if match is None: return {} return { 'match_type': match.match_type, 'match_score': round(match.match_score, 4) if match.match_score is not None else None, 'matched_text': match.matched_text, } @staticmethod def _increment_hit_count(entry_id: int) -> None: """ 异步安全地增加 FAQ 命中计数。 @param entry_id - QuickQuestion 主键 """ try: db.session.query(QuickQuestion).filter_by(id=entry_id).update( { QuickQuestion.hit_count: QuickQuestion.hit_count + 1, QuickQuestion.updated_at: datetime.utcnow(), }, synchronize_session=False, ) db.session.commit() except Exception as exc: if current_app: current_app.logger.warning("[faq-cache] failed to increment hit_count id=%s: %s", entry_id, exc) db.session.rollback() @staticmethod def stream_chat( entry: QuickQuestion, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None, match: Optional[FaqCacheMatch] = None, ): """ 以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。 核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache; match 非空时附带 match_type / match_score / matched_text 供审计与排障。 @param entry - 命中的 QuickQuestion @param query - 用户原始提问 @param user - 当前用户代理对象(需含 id) @param agent - 当前 Agent 代理对象(需含 id) @param conversation_id - Dify/外部会话 ID @param session_id - 本地会话 ID @param match - try_match 的命中结果;历史调用方可不传 @yields SSE 格式字符串 """ start_time = time.time() final_conversation_id = conversation_id or f"faq_{int(time.time())}" answer = str(entry.answer or "").strip() retriever_resources = entry.retriever_resources if isinstance(entry.retriever_resources, list) else [] audit_fields = FaqCacheService._match_audit_fields(match) yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n" latency = int((time.time() - start_time) * 1000) chat_log_id = None try: payload: dict[str, Any] = { 'source': 'faq_cache', 'faq_id': entry.id, 'faq_title': entry.title, } payload.update(audit_fields) chat_log = ChatLog( user_id=user.id, agent_id=agent.id, conversation_id=final_conversation_id, session_id=session_id, query=query, answer=answer, tokens_used=0, latency=latency, retriever_resources=retriever_resources, payload=payload, ) db.session.add(chat_log) db.session.commit() chat_log_id = chat_log.id except Exception as exc: if current_app: current_app.logger.error("[faq-cache] failed to log chat: %s", exc) db.session.rollback() FaqCacheService._increment_hit_count(entry.id) end_data: dict[str, Any] = { 'event': 'message_end', 'answer': answer, 'replace_answer': True, 'chat_log_id': chat_log_id, 'conversation_id': final_conversation_id, 'metadata': { 'retriever_resources': retriever_resources, 'source': 'faq_cache', 'faq_id': entry.id, **audit_fields, }, } if retriever_resources: end_data["retriever_resources"] = retriever_resources yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"