feat(common problems fuzzy query): 增加常用问题模糊查询兜底
This commit is contained in:
1 parent
b69c725992
commit
5a269f940d
18 files changed
+411
-58
No files matched your search
@@ -35,6 +35,7 @@ class QuickQuestion(Base):
|
||||
常用问题表
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
|
||||
fuzzy_enabled / fuzzy_threshold 控制精确未命中后的模糊兜底直答(逐条目独立,阈值钳制在 0.5~1.0)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'quick_questions'
|
||||
@@ -48,6 +49,8 @@ class QuickQuestion(Base):
|
||||
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||
fuzzy_enabled: Mapped[bool] = mapped_column(default=False)
|
||||
fuzzy_threshold: Mapped[float] = mapped_column(default=0.80)
|
||||
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)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/admin/faq_service.py
|
||||
|
||||
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
|
||||
依赖:models、faq_kb_invalidation、hot_faq_* services。
|
||||
依赖:models、faq_kb_invalidation、hot_faq_* services、faq_text_utils(模糊阈值钳制)。
|
||||
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +13,7 @@ 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]:
|
||||
@@ -61,6 +62,8 @@ def serialize_quick_question(
|
||||
'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,
|
||||
@@ -93,6 +96,12 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
|
||||
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):
|
||||
@@ -106,6 +115,8 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
|
||||
|
||||
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')
|
||||
|
||||
|
||||
@@ -77,12 +77,13 @@ def try_fast_route(
|
||||
_log_fast_route('faq_cache', agent_code=agent_code, agent_id=agent_id, session_id=session_id)
|
||||
return FastRouteResult(
|
||||
generator=FaqCacheService.stream_chat(
|
||||
faq_hit,
|
||||
faq_hit.entry,
|
||||
query,
|
||||
user,
|
||||
agent,
|
||||
external_conversation_id,
|
||||
session_id=session_id,
|
||||
match=faq_hit,
|
||||
),
|
||||
route_name='faq_cache',
|
||||
)
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
backend/app/services/faq_cache.py
|
||||
|
||||
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
|
||||
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
|
||||
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。
|
||||
依赖: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
|
||||
|
||||
@@ -14,7 +17,26 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ChatLog, QuickQuestion
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
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:
|
||||
@@ -43,33 +65,48 @@ class FaqCacheService:
|
||||
return expires_at <= datetime.utcnow()
|
||||
|
||||
@staticmethod
|
||||
def _candidate_texts(entry: QuickQuestion) -> list[str]:
|
||||
def _candidate_pairs(entry: QuickQuestion) -> list[tuple[str, str]]:
|
||||
"""
|
||||
收集条目可用于匹配的标准化文本集合。
|
||||
收集条目可用于匹配的 (原文, 归一化文本) 对。
|
||||
核心逻辑:候选来源为 question、title 与 aliases;原文用于审计展示,归一化文本用于比对。
|
||||
@param entry - QuickQuestion 实例
|
||||
@returns 归一化后的候选文本列表
|
||||
@returns (原文, 归一化文本) 列表
|
||||
"""
|
||||
texts: list[str] = []
|
||||
pairs: list[tuple[str, str]] = []
|
||||
for raw in (entry.question, entry.title):
|
||||
normalized = FaqCacheService._normalize_text(raw)
|
||||
if normalized:
|
||||
texts.append(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:
|
||||
texts.append(normalized)
|
||||
return texts
|
||||
pairs.append((str(alias), normalized))
|
||||
return pairs
|
||||
|
||||
@staticmethod
|
||||
def try_match(query: str, agent_id: int) -> Optional[QuickQuestion]:
|
||||
def _candidate_texts(entry: QuickQuestion) -> list[str]:
|
||||
"""
|
||||
尝试为指定 Agent 命中全局 FAQ 缓存条目。
|
||||
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
|
||||
收集条目可用于匹配的标准化文本集合。
|
||||
核心逻辑:委托 _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 命中的 QuickQuestion;未命中返回 None
|
||||
@returns FaqCacheMatch;未命中返回 None
|
||||
"""
|
||||
normalized_query = FaqCacheService._normalize_text(query)
|
||||
if not normalized_query or not agent_id:
|
||||
@@ -89,12 +126,50 @@ class FaqCacheService:
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 1] 精确命中:归一化后全等,任何启用缓存的条目参与
|
||||
for entry in entries:
|
||||
if FaqCacheService._is_expired(entry):
|
||||
continue
|
||||
if normalized_query in FaqCacheService._candidate_texts(entry):
|
||||
return entry
|
||||
return None
|
||||
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:
|
||||
@@ -124,28 +199,38 @@ class FaqCacheService:
|
||||
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。
|
||||
核心逻辑:产出 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,
|
||||
@@ -156,11 +241,7 @@ class FaqCacheService:
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
payload={
|
||||
"source": "faq_cache",
|
||||
"faq_id": entry.id,
|
||||
"faq_title": entry.title,
|
||||
},
|
||||
payload=payload,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
@@ -173,15 +254,16 @@ class FaqCacheService:
|
||||
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,
|
||||
'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:
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
"""
|
||||
backend/app/services/faq_text_utils.py
|
||||
|
||||
用途:FAQ / 热点问句归一化等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||
依赖:无外部业务模块。
|
||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则。
|
||||
用途:FAQ / 热点问句归一化、模糊相似度评分等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||
依赖:difflib(Python 标准库,无第三方依赖)。
|
||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则;模糊评分供 FAQ 兜底直答使用。
|
||||
"""
|
||||
import re
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
# 模糊兜底参与的最低归一化长度:过短问句(如「帮助」)误命中代价高,只走精确匹配。
|
||||
FUZZY_MIN_LENGTH = 4
|
||||
# 模糊阈值的安全钳制区间与默认值:下限防止管理员设得过低导致大面积误直答。
|
||||
FUZZY_THRESHOLD_MIN = 0.5
|
||||
FUZZY_THRESHOLD_MAX = 1.0
|
||||
FUZZY_THRESHOLD_DEFAULT = 0.8
|
||||
|
||||
|
||||
def normalize_faq_query(text: str) -> str:
|
||||
@@ -16,5 +24,38 @@ def normalize_faq_query(text: str) -> str:
|
||||
@returns 归一化后的字符串;空输入返回空串
|
||||
"""
|
||||
value = str(text or "").strip().lower()
|
||||
value = re.sub(r"[\s\u3000,。!?、;:""''()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||
value = re.sub(r"[\s\u3000,。!?、;:“”‘’()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||
return value
|
||||
|
||||
|
||||
def clamp_fuzzy_threshold(value) -> float:
|
||||
"""
|
||||
将模糊匹配阈值钳制到安全区间 [0.5, 1.0]。
|
||||
核心逻辑:空值/非法值回退默认 0.8,越界值收敛到边界,保证在线匹配不会因配置异常失真。
|
||||
@param value - 数据库或请求体中的阈值原始值
|
||||
@returns 钳制后的浮点阈值
|
||||
"""
|
||||
try:
|
||||
threshold = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return FUZZY_THRESHOLD_DEFAULT
|
||||
return min(FUZZY_THRESHOLD_MAX, max(FUZZY_THRESHOLD_MIN, threshold))
|
||||
|
||||
|
||||
def fuzzy_match_score(query: str, candidate: str) -> float:
|
||||
"""
|
||||
计算两段归一化问句的模糊相似度得分(0~1),供 FAQ 模糊兜底匹配使用。
|
||||
核心逻辑:取编辑距离类相似度(SequenceMatcher.ratio)与包含覆盖率的最大值——
|
||||
前者容忍换字/错字(能→可以),后者容忍加前后缀(我还能问什么 vs 还能问什么);
|
||||
真问题偶含候选短语时(如「怎么用你查MES服务器」vs「怎么用你」)覆盖率很低,不会误命中。
|
||||
@param query - 归一化后的用户问句
|
||||
@param candidate - 归一化后的候选问句(标题/标准问句/同义问法)
|
||||
@returns 0~1 之间的相似度得分
|
||||
"""
|
||||
if not query or not candidate:
|
||||
return 0.0
|
||||
score = SequenceMatcher(None, query, candidate).ratio()
|
||||
if query in candidate or candidate in query:
|
||||
coverage = min(len(query), len(candidate)) / max(len(query), len(candidate))
|
||||
score = max(score, coverage)
|
||||
return score
|
||||
Reference in new issue
Block a user