feat(faq): 缓存高频问题及答案,命中直接返回预置答案,不走dify
This commit is contained in:
1 parent
3264ed1e07
commit
cf7cc11ffc
32 files changed
+3504
-180
No files matched your search
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
backend/app/services/faq_cache.py
|
||||
|
||||
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
|
||||
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
|
||||
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match;命中则 stream_chat 返回预置答案。
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ChatLog, QuickQuestion, db
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
|
||||
|
||||
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_texts(entry: QuickQuestion) -> list[str]:
|
||||
"""
|
||||
收集条目可用于匹配的标准化文本集合。
|
||||
@param entry - QuickQuestion 实例
|
||||
@returns 归一化后的候选文本列表
|
||||
"""
|
||||
texts: list[str] = []
|
||||
for raw in (entry.question, entry.title):
|
||||
normalized = FaqCacheService._normalize_text(raw)
|
||||
if normalized:
|
||||
texts.append(normalized)
|
||||
aliases = entry.aliases if isinstance(entry.aliases, list) else []
|
||||
for alias in aliases:
|
||||
normalized = FaqCacheService._normalize_text(str(alias))
|
||||
if normalized:
|
||||
texts.append(normalized)
|
||||
return texts
|
||||
|
||||
@staticmethod
|
||||
def try_match(query: str, agent_id: int) -> Optional[QuickQuestion]:
|
||||
"""
|
||||
尝试为指定 Agent 命中全局 FAQ 缓存条目。
|
||||
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
|
||||
@param query - 用户提问
|
||||
@param agent_id - 当前 Agent 主键
|
||||
@returns 命中的 QuickQuestion;未命中返回 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.is_enabled.is_(True),
|
||||
QuickQuestion.answer.isnot(None),
|
||||
QuickQuestion.answer != "",
|
||||
)
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
for entry in entries:
|
||||
if FaqCacheService._is_expired(entry):
|
||||
continue
|
||||
if normalized_query in FaqCacheService._candidate_texts(entry):
|
||||
return entry
|
||||
return None
|
||||
|
||||
@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,
|
||||
):
|
||||
"""
|
||||
以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。
|
||||
核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache。
|
||||
@param entry - 命中的 QuickQuestion
|
||||
@param query - 用户原始提问
|
||||
@param user - 当前用户代理对象(需含 id)
|
||||
@param agent - 当前 Agent 代理对象(需含 id)
|
||||
@param conversation_id - Dify/外部会话 ID
|
||||
@param session_id - 本地会话 ID
|
||||
@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 []
|
||||
|
||||
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:
|
||||
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={
|
||||
"source": "faq_cache",
|
||||
"faq_id": entry.id,
|
||||
"faq_title": entry.title,
|
||||
},
|
||||
)
|
||||
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,
|
||||
},
|
||||
}
|
||||
if retriever_resources:
|
||||
end_data["retriever_resources"] = retriever_resources
|
||||
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
|
||||
Reference in new issue
Block a user