diff --git a/AGENTS.md b/AGENTS.md
index f5ad7f2c..e92d7032 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -205,7 +205,7 @@ docker compose logs -f hxops-backend
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
-| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
+| FAQ 缓存 / 热点发现运维 | [docs/features/faq/faq_cache_ops_manual.md](docs/features/faq/faq_cache_ops_manual.md) |
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
diff --git a/backend/app/models/content.py b/backend/app/models/content.py
index c88dbe4c..8f4305b7 100644
--- a/backend/app/models/content.py
+++ b/backend/app/models/content.py
@@ -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)
diff --git a/backend/app/services/admin/faq_service.py b/backend/app/services/admin/faq_service.py
index d6f243de..ca9198f7 100644
--- a/backend/app/services/admin/faq_service.py
+++ b/backend/app/services/admin/faq_service.py
@@ -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')
diff --git a/backend/app/services/chat/router.py b/backend/app/services/chat/router.py
index 51506123..35196b65 100644
--- a/backend/app/services/chat/router.py
+++ b/backend/app/services/chat/router.py
@@ -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',
)
diff --git a/backend/app/services/faq_cache.py b/backend/app/services/faq_cache.py
index 032a6a32..e992b213 100644
--- a/backend/app/services/faq_cache.py
+++ b/backend/app/services/faq_cache.py
@@ -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:
diff --git a/backend/app/services/faq_text_utils.py b/backend/app/services/faq_text_utils.py
index d797fa14..b80079ce 100644
--- a/backend/app/services/faq_text_utils.py
+++ b/backend/app/services/faq_text_utils.py
@@ -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
diff --git a/backend/migrations/versions/b51c9e4a7d30_add_quick_question_fuzzy_match_fields.py b/backend/migrations/versions/b51c9e4a7d30_add_quick_question_fuzzy_match_fields.py
new file mode 100644
index 00000000..1c9654c7
--- /dev/null
+++ b/backend/migrations/versions/b51c9e4a7d30_add_quick_question_fuzzy_match_fields.py
@@ -0,0 +1,36 @@
+"""常用问题增加模糊匹配开关与阈值。
+
+Revision ID: b51c9e4a7d30
+Revises: eah8c9d0e1f2
+Create Date: 2026-10-22 15:00:00.000000
+
+用途:quick_questions 增加 fuzzy_enabled / fuzzy_threshold 两列,支撑 FAQ 缓存精确未命中后的模糊兜底直答。
+依赖:eah8c9d0e1f2、quick_questions 表。
+逻辑:两列均带 server_default,存量行回填为「关闭 + 0.80」,行为与升级前完全一致。
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+revision = "b51c9e4a7d30"
+down_revision = "eah8c9d0e1f2"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ """补上模糊匹配开关(默认关)与阈值列(默认 0.8)。"""
+ op.add_column(
+ "quick_questions",
+ sa.Column("fuzzy_enabled", sa.Boolean(), nullable=False, server_default=sa.false()),
+ )
+ op.add_column(
+ "quick_questions",
+ sa.Column("fuzzy_threshold", sa.Float(), nullable=False, server_default=sa.text("0.8")),
+ )
+
+
+def downgrade():
+ """按相反顺序去掉模糊匹配阈值与开关列。"""
+ op.drop_column("quick_questions", "fuzzy_threshold")
+ op.drop_column("quick_questions", "fuzzy_enabled")
diff --git a/backend/tests/test_chat_router.py b/backend/tests/test_chat_router.py
index 6fad1679..526ebb2a 100644
--- a/backend/tests/test_chat_router.py
+++ b/backend/tests/test_chat_router.py
@@ -14,6 +14,7 @@ import pytest
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
from app.services.chat.router import FastRouteResult, try_fast_route
+from app.services.faq_cache import FaqCacheMatch
@pytest.fixture(autouse=True)
@@ -42,11 +43,11 @@ def _user(**kwargs):
def test_try_fast_route_faq_cache(monkeypatch):
"""FAQ 命中时应返回 faq_cache 路由。"""
- faq_entry = object()
+ faq_match = FaqCacheMatch(entry=object(), match_type='exact', match_score=1.0, matched_text='常见问题')
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
- staticmethod(lambda query, agent_id: faq_entry),
+ staticmethod(lambda query, agent_id: faq_match),
)
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.stream_chat',
diff --git a/backend/tests/test_faq_cache.py b/backend/tests/test_faq_cache.py
index 50e7713d..e05dd1a4 100644
--- a/backend/tests/test_faq_cache.py
+++ b/backend/tests/test_faq_cache.py
@@ -1,8 +1,9 @@
"""
backend/tests/test_faq_cache.py
-用途:FAQ 缓存在线匹配规则。
-逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中。
+用途:FAQ 缓存在线匹配规则(精确 + 模糊兜底两阶段)。
+逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中;
+ 模糊兜底仅在条目开启 fuzzy_enabled 后参与,且得分受逐条目阈值约束。
"""
from app import db
from app.models import Agent, QuickQuestion
@@ -37,18 +38,20 @@ def _create_faq(agent_id: int, **overrides) -> QuickQuestion:
def test_try_match_hits_when_cache_on_even_if_not_shown_on_home(app):
- """关闭前台展示时,启用缓存的问句仍应直答,不走 Dify。"""
+ """关闭前台展示时,启用缓存的问句仍应精确直答,不走 Dify。"""
with app.app_context():
agent = _create_agent()
- _create_faq(agent.id, is_enabled=False)
+ faq = _create_faq(agent.id, is_enabled=False)
hit = FaqCacheService.try_match('公司的企业文化', agent.id)
alias_hit = FaqCacheService.try_match('企业文化', agent.id)
assert hit is not None
- assert hit.answer == '客户满意、员工乐意、经营得意'
+ assert hit.match_type == 'exact'
+ assert hit.entry.id == faq.id
+ assert hit.entry.answer == '客户满意、员工乐意、经营得意'
assert alias_hit is not None
- assert alias_hit.id == hit.id
+ assert alias_hit.entry.id == hit.entry.id
def test_try_match_skips_when_cache_disabled(app):
@@ -58,3 +61,106 @@ def test_try_match_skips_when_cache_disabled(app):
_create_faq(agent.id, cache_enabled=False, is_enabled=True)
assert FaqCacheService.try_match('公司的企业文化', agent.id) is None
+
+
+def test_fuzzy_fallback_hits_affix_variant_when_enabled(app):
+ """精确未命中时,开启模糊的条目应容忍加前缀(我/请问)后兜底直答。"""
+ with app.app_context():
+ agent = _create_agent()
+ faq = _create_faq(
+ agent.id,
+ title='还能问什么',
+ question='还能问什么',
+ aliases=['还能问你什么'],
+ fuzzy_enabled=True,
+ )
+
+ hit = FaqCacheService.try_match('我还能问什么', agent.id)
+
+ assert hit is not None
+ assert hit.match_type == 'fuzzy'
+ assert hit.entry.id == faq.id
+ assert hit.match_score is not None and hit.match_score >= 0.8
+ assert hit.matched_text == '还能问什么'
+
+
+def test_fuzzy_fallback_not_hit_when_toggle_off(app):
+ """未开启模糊匹配的条目,加前缀的近似问法不应命中(维持旧行为)。"""
+ with app.app_context():
+ agent = _create_agent()
+ _create_faq(agent.id, title='还能问什么', question='还能问什么', aliases=None)
+
+ assert FaqCacheService.try_match('我还能问什么', agent.id) is None
+
+
+def test_fuzzy_fallback_respects_per_entry_threshold(app):
+ """得分低于条目阈值不应命中;阈值调低后同问法可命中。"""
+ with app.app_context():
+ agent = _create_agent()
+ faq = _create_faq(
+ agent.id,
+ title='还能问什么',
+ question='还能问什么',
+ aliases=None,
+ fuzzy_enabled=True,
+ fuzzy_threshold=0.9,
+ )
+
+ # 「我可以问什么」对「还能问什么」的实际得分约 0.55(中段换字对编辑距离不友好),低于 0.6
+ assert FaqCacheService.try_match('我可以问什么', agent.id) is None
+
+ faq.fuzzy_threshold = 0.5
+ db.session.commit()
+ hit = FaqCacheService.try_match('我可以问什么', agent.id)
+ assert hit is not None
+ assert hit.match_type == 'fuzzy'
+ assert hit.match_score is not None and hit.match_score >= 0.5
+
+
+def test_fuzzy_guard_blocks_real_question_containing_alias(app):
+ """真问题只包含短候选短语时覆盖率低,不应被误直答(放行走 Dify)。"""
+ with app.app_context():
+ agent = _create_agent()
+ _create_faq(agent.id, title='怎么用你', question='怎么用你', aliases=None, fuzzy_enabled=True)
+
+ assert FaqCacheService.try_match('怎么用你来查mes服务器', agent.id) is None
+
+
+def test_fuzzy_skips_short_queries_and_candidates(app):
+ """归一化后不足 4 字的输入不参与模糊兜底,只能精确命中。"""
+ with app.app_context():
+ agent = _create_agent()
+ _create_faq(
+ agent.id,
+ title='帮助中心',
+ question='帮助中心',
+ aliases=['帮助'],
+ fuzzy_enabled=True,
+ fuzzy_threshold=0.5,
+ )
+
+ # 逐字命中同义问法「帮助」:短问句的精确匹配不受护栏影响
+ exact = FaqCacheService.try_match('帮助', agent.id)
+ assert exact is not None
+ assert exact.match_type == 'exact'
+
+ # 「帮助台」不是逐字命中;若无护栏会以 0.75 覆盖率误命中,应被长度护栏拦截
+ assert FaqCacheService.try_match('帮助台', agent.id) is None
+
+ # 长度足够的输入包含完整候选时覆盖率高,应兜底命中
+ hit = FaqCacheService.try_match('帮助中心怎么打开', agent.id)
+ assert hit is not None
+ assert hit.match_type == 'fuzzy'
+
+
+def test_exact_match_wins_over_fuzzy_phase(app):
+ """逐字一致的问法必须标记 exact 命中,即使条目同时开启了模糊。"""
+ with app.app_context():
+ agent = _create_agent()
+ faq = _create_faq(agent.id, fuzzy_enabled=True)
+
+ hit = FaqCacheService.try_match('企业文化', agent.id)
+
+ assert hit is not None
+ assert hit.match_type == 'exact'
+ assert hit.entry.id == faq.id
diff --git a/docs/features/README.md b/docs/features/README.md
index 085cf394..c2ab5334 100644
--- a/docs/features/README.md
+++ b/docs/features/README.md
@@ -18,6 +18,7 @@
| [equipment-maintenance](equipment-maintenance/README.md) | 设备维保助手 | [聊天原型](equipment-maintenance/equipment-maintenance-agent-chat-lofi.html) |
| [equipment-acceptance-warning](equipment-acceptance-warning/README.md) | 设备验收停留预警 | [需求说明](equipment-acceptance-warning/demand.md) · [数据设计](equipment-acceptance-warning/technical.md) |
| [training](training/) | 教育训练:新人培训与年度计划 | [年度教育训练计划需求](training/annual-training-plan-demand.md) · [设计方案](training/annual-training-plan-design.md) · [可点击原型](training/annual-training-plan-prototype.html) · [精益周任务规则](training/精益管理周任务规则手册.md) |
+| [faq](faq/) | 常用问题 / FAQ 缓存直答 | [运维手册](faq/faq_cache_ops_manual.md) · [模糊查询与 AI 自动维护设计](faq/faq_fuzzy_and_ai_maintenance_design.md) |
**平台级**设计与跨域原型见 [platform/](../platform/README.md)。
diff --git a/docs/features/faq/faq_cache_ops_manual.md b/docs/features/faq/faq_cache_ops_manual.md
index 451b8792..a3c9f708 100644
--- a/docs/features/faq/faq_cache_ops_manual.md
+++ b/docs/features/faq/faq_cache_ops_manual.md
@@ -61,19 +61,30 @@ flowchart TB
```mermaid
flowchart TD
- A[用户发消息 chat.py] --> B{有附件?}
+ A[用户发消息 chat router] --> B{有附件?}
B -->|是| Z[跳过 FAQ,走业务路由]
B -->|否| C[FaqCacheService.try_match]
C --> D{agent 全局 FAQ
cache_enabled=true
stale_at 为空
未过期?}
D -->|否| E[未命中 → Dify 等]
- D -->|是| F{归一化问句匹配
question / title / aliases?}
- F -->|否| E
+ D -->|是| F{阶段一:归一化精确匹配
question / title / aliases?}
F -->|是| G[SSE 直答 stream_chat]
- G --> H[ChatLog: tokens=0
payload.source=faq_cache]
+ F -->|否| F2{阶段二:条目 fuzzy_enabled?
输入 ≥ 4 字?}
+ F2 -->|否| E
+ F2 -->|是| F3{最高相似度得分
≥ 条目 fuzzy_threshold?}
+ F3 -->|否| E
+ F3 -->|是| G
+ G --> H[ChatLog: tokens=0
payload.source=faq_cache
match_type / match_score]
E --> I[ChatLog: tokens>0]
```
-**匹配规则**:`normalize_faq_query` 归一化后精确匹配(见 `faq_text_utils.py`)。
+**匹配规则**(两阶段,见 `faq_text_utils.py` / `faq_cache.py`):
+
+1. **阶段一·精确**:`normalize_faq_query` 归一化后全等比对,所有 `cache_enabled` 条目参与。
+2. **阶段二·模糊兜底**:精确未命中且归一化输入 ≥ 4 字时,仅对 `fuzzy_enabled=true` 的条目计算
+ `fuzzy_match_score = max(编辑距离相似度, 包含覆盖率)`,最高分达到该条目 `fuzzy_threshold`
+ (钳制 0.50–1.00,默认 0.80)才直答;加前缀(我/请问)靠包含覆盖率命中,真问题偶含短语
+ (如「怎么用你查MES服务器」)覆盖率低不会误命中。命中方式写入 `payload.match_type`
+ (`exact` / `fuzzy`)、`match_score`、`matched_text`,供审计排障。
### 离线热点发现流程
@@ -281,8 +292,8 @@ FAQ_HOT_BAD_SCORE=2
| 操作 | 说明 |
| --- | --- |
-| 新建/编辑 | 填写 question、answer、aliases;开启「启用缓存」 |
-| 关闭缓存 | `cache_enabled=false` 后不再在线命中,但不删 ChatLog |
+| 新建/编辑 | 填写 question、answer、aliases;开启「启用缓存」;需要时可开启「模糊匹配」并调阈值(前提:已启用缓存) |
+| 关闭缓存 | `cache_enabled=false` 后不再在线命中(模糊兜底一并失效),但不删 ChatLog |
| 关闭前台展示 | `is_enabled=false` 后工作台首页不显示快捷入口,**不影响** FAQ 缓存命中 |
| 设置过期 | `expires_at` 到期后 `try_match` 自动跳过 |
| 查看命中 | 列表字段 `hit_count` |
@@ -300,6 +311,8 @@ FAQ_HOT_BAD_SCORE=2
| 场景 | ChatLog 特征 |
| --- | --- |
| L1 FAQ 直答 | `tokens_used=0`,`payload.source=faq_cache`,`payload.faq_id=` |
+| ┙ 精确命中 | 追加 `payload.match_type='exact'`、`match_score=1.0` |
+| ┙ 模糊兜底命中 | 追加 `payload.match_type='fuzzy'`、`match_score=<0.5~1.0>`、`matched_text=<命中的候选原文>` |
| Dify 正常对话 | `tokens_used>0`,无 `faq_cache` source |
| 不参与聚合 | `payload.source` 为 `faq_cache` / `hot_faq_cache` |
@@ -442,7 +455,8 @@ WHERE status = 'candidate'
| --- | --- | --- |
| CLI 提示 `FAQ_HOT_ENABLED is false` | 环境变量关闭 | 设 `FAQ_HOT_ENABLED=true` 并重启 |
| 热点列表始终为空 | 未跑聚合 / 阈值过高 / 窗口内无 Dify 对话 | `--dry-run` 看 skipped reason;调低 MIN_COUNT |
-| 晋升后仍走 Dify | 问句与 FAQ 归一化不一致 | 检查 aliases;用户问法是否在 aliases 中 |
+| 晋升后仍走 Dify | 问句与 FAQ 归一化不一致 | 检查 aliases;用户问法是否在 aliases 中;或在 FAQ 上开启「模糊匹配」并按需调低阈值 |
+| 疑似模糊误命中 | `fuzzy_threshold` 设得过低(如 0.5) | 查 ChatLog `payload.match_score`;调高该条目阈值或关闭其「模糊匹配」 |
| 同问题重复出现在热点 | 未晋升也未忽略;或 deny 已过期 | 晋升或 dismiss |
| 聚合很慢 | ChatLog 量大 | 按 `--agent-id` 拆分;错峰 cron |
| `purge_expired` 报错 | DB 连接/迁移未执行 | 查日志;确认 `faq_hot_candidates` 表存在 |
diff --git a/docs/features/faq/faq_fuzzy_and_ai_maintenance_design.md b/docs/features/faq/faq_fuzzy_and_ai_maintenance_design.md
new file mode 100644
index 00000000..e946aebe
--- /dev/null
+++ b/docs/features/faq/faq_fuzzy_and_ai_maintenance_design.md
@@ -0,0 +1,118 @@
+# 常用问题:模糊查询 · 答案素材化 · AI 自动维护 设计文档
+
+> 日期:2026-10-23 · 分支:`common-problems-fuzzy-query` · 状态:一期 A 已实现,一期 B / 二期待实现
+> 关联文档:[faq_cache_ops_manual.md](faq_cache_ops_manual.md)(L1 缓存运维)· [../../funclist.md](../../funclist.md) §7
+
+## 1. 背景与目标
+
+管理控制台「常用问题」(FAQ 缓存) 原先仅支持归一化后精确匹配,用户问法稍有变化(加字、换近义词)即漏检,落到知识库兜底话术;标准答案靠管理员手工粘贴,知识库文档变更后答案无人维护。本设计分三期:
+
+1. **模糊查询**(一期 A,已实现):精确未命中时按相似度兜底直答;
+2. **答案素材化**(一期 B):标准答案从知识库文档导入,接入既有失效联动;
+3. **AI 自动维护**(二期):业务库文档变更 → AI 总结 → 素材文档 → FAQ 答案自动更新,无人工介入。
+
+## 2. 概念模型(术语表)
+
+| 概念 | 定义 |
+| --- | --- |
+| FAQ 直答 | 用户提问命中常用问题条目时跳过 Dify,SSE 直接返回预置答案(`payload.source=faq_cache`) |
+| answer 快照 | `quick_questions.answer` 保存**配置时刻**从素材文档复制的文本;直答只读此字段,不碰 KB/Dify/文件系统 |
+| 精确匹配 | `normalize_faq_query`(trim→小写→去标点空白)归一化后全等比对,候选含 标题/标准问句/同义问法 |
+| 模糊兜底 | 精确未命中后,仅对开启模糊的条目按相似度评分,达阈值才直答 |
+| 答案素材文档 | 独立 KB 组(不绑 `dify_dataset_id`)中的文档,是 FAQ 答案的内容来源;**不进 Dify 检索** |
+| 源范围 | 素材文档声明的"总结哪些业务文档"(指定组 / 标签 / 文档清单) |
+| 源版本指纹 | 素材文档各源文档 sha256 的集合哈希,用于观测"素材落后于业务库" |
+| 待复审 (stale) | 关联文档变更后条目被写 `stale_at`、`cache_enabled=false` 暂停直答,复核后 `clear_stale` 恢复 |
+
+## 3. 已确定的架构决策
+
+### 3.1 匹配:两阶段(一期 A,已实现)
+
+- **阶段一·精确**:归一化全等,所有 `cache_enabled` 条目参与;精确永远优先。
+- **阶段二·模糊兜底**:归一化输入 ≥ 4 字才参与;仅 `fuzzy_enabled=true` 条目;
+ `score = max(编辑距离相似度 difflib.ratio, 包含覆盖率 min/max)`;最高分 ≥ 该条目阈值才命中,同分先出现者胜。
+- **阈值**:0.50–1.00、步进 0.05、默认 0.80,前后端双重钳制;启用模糊以启用缓存为前提。
+- **实测基准**(调阈值的依据):
+
+ | 用户输入 | 对比候选 | 得分 | 默认 0.80 |
+ | --- | --- | --- | --- |
+ | 我还能问什么 | 还能问什么 | ≈0.91 | ✅ 命中 |
+ | 我可以问什么 | 还能问什么 | ≈0.55 | ❌ 需调至 0.50–0.55(中段换字对编辑距离不友好) |
+ | 怎么用你查MES服务器 | 怎么用你 | ≈0.50 | ❌ 不误命中(真问题护栏) |
+
+- **审计**:ChatLog payload 与 SSE metadata 写入 `match_type`(exact/fuzzy) / `match_score` / `matched_text`。
+- **实现落点**:`faq_text_utils.py`(评分与钳制)、`faq_cache.py`(两阶段 `try_match` + `FaqCacheMatch`)、迁移 `b51c9e4a7d30`。
+
+### 3.2 答案来源:快照模式(已定,一期 B 实现)
+
+- **快照**:配置时从素材文档导入文本 → 管理员可裁剪 → 存入 `answer`;直答零外部依赖。
+- **明确否决动态引用**(直答时实时读 KB):延迟、故障面、段落解析成本,且失效机制已兜住新鲜度——"内容一致性不靠读取时保证,靠过时即下线保证"。
+- **素材文档独立成组**「FAQ 答案素材」,不绑 `dify_dataset_id`:回答文件与业务文件同库会双向污染召回(业务问题误召回元话术、素材抢占业务文档位置),这是业务硬约束。备选的"Dify 元数据过滤排除"方案否决——每个检索节点都要记得配置,结构性脆弱。
+- **管理端入口**:编辑弹窗「关联知识库文档」选择器 + 「从文档导入答案」(`GET /api/kb/documents//markdown` 预填,管理员保留最终编辑权);后端 `apply_quick_question_payload` 增加直传 `source_kb_document_ids` 入口(现状只能从 `retriever_resources` 反推,手工条目完全没有绑定)。
+
+### 3.3 失效联动:触发点前移(已定,一期 B 实现)
+
+- **现状缺口**:`invalidate_faqs_for_kb_document` 只挂在 Dify 同步链(`dify_sync_service.py:680/753`);素材组不同步 → 钩子永不触发;本地改内容但 Dify 同步失败的场景同样漏触发。
+- **前移**:本地文档生命周期入口(`PUT /documents//markdown`、`PATCH`、`DELETE`、新版本上传)直接调失效,`sha256` 变更判断避免小改动误触发;Dify 同步钩子保留兜底,`stale_at` 幂等去重。
+- **stale 期间行为**:直答退出 → 走 Dify 通用兜底(fail-closed:宁可 temporarily 通用回答,不给过时答案)。
+
+### 3.4 AI 自动维护:两级派生链(方向已定,二期实现)
+
+```mermaid
+flowchart TD
+ A[业务库 12.资讯 文档 上传/变更/删除] --> B[一期本地生命周期钩子]
+ B --> C{落在哪些素材文档的源范围内?}
+ C --> D[AI 第 1 级: 全量重总结
LLM 读取源文档最新 markdown]
+ D --> E[素材文档新版本
走标准 KB 服务写入 → 版本化/事件自动获得]
+ E --> F[一期素材组失效钩子]
+ F --> G[AI 第 2 级已被优化掉:
answer 直接复制素材文档内容]
+ G --> H[直连该素材文档的所有 FAQ
answer 快照切换 + 留档旧答案]
+ D -->|LLM 失败/校验不过| X[素材/FAQ 保持待复审
fail-closed 不自动恢复直答]
+```
+
+- **两级派生**:业务文档不直接连 FAQ;素材文档是业务库的 AI 总结产物,FAQ 只连素材文档。
+- **蓝绿更新**:旧快照服务到新素材就绪那一刻才切换,无"先下线再等"的空窗。
+- **软失效与观测**:业务变更不再立即下线 FAQ;靠源版本指纹显示"素材落后于源 N 篇",超阈值告警或自动转待复审(可配置)。
+- **按答案口径生成(待确认的建议)**:素材文档生成 prompt 直接携带 FAQ 问题与口吻要求("我可以帮您…"),产物即答案正文,answer 复制即可——省一次 LLM 调用、少一处幻觉入口。
+- **总结策略(待确认的建议)**:源范围 ≤10 篇全量重总结;更大再上增量合并。
+
+### 3.5 护栏与降级(已定)
+
+| 护栏 | 规则 |
+| --- | --- |
+| 逐条目开关 | `auto_maintained` 默认关;只对放心的条目开全自动,其余走"AI 生成建议 + 人工一键采纳" |
+| 生成校验 | 非空、长度区间、不含"超出收录范围"类兜底话术、与问题相关性;失败 → 保持待复审 |
+| fail-closed | LLM 失败/校验不过绝不自动恢复直答;进重试队列(schedule 框架) |
+| 删除源文档 | 触发重总结去除章节;源全删光 → 素材清空 → FAQ 转人工(下架/改写由人决定) |
+| 留档回滚 | `answer_history`(旧答案+文档版本号+生成时间+prompt 标识);管理端 diff + 一键回滚 |
+| 异步 | LLM 不阻塞上传接口,事件入队后台;批量上传去抖合并 |
+
+## 4. 数据模型增量
+
+| 字段/结构 | 期 | 状态 |
+| --- | --- | --- |
+| `quick_questions.fuzzy_enabled` / `fuzzy_threshold` | 一期 A | ✅ 迁移 `b51c9e4a7d30` |
+| `source_kb_document_ids` 直传(字段已存在,补 payload 入口) | 一期 B | 待实现 |
+| 素材源范围配置、源版本指纹、生成状态记录 | 二期 | 待实现 |
+| `quick_questions.auto_maintained` / `answer_history` | 二期 | 待实现(与二期其余字段合并一次迁移) |
+
+## 5. 分期与实施顺序
+
+| 期 | 内容 | 依赖 | 状态 |
+| --- | --- | --- | --- |
+| 一·A 模糊查询 | 两阶段匹配 + 弹窗开关/阈值 + 四语言 + 审计 | 无 | ✅ 已实现(测试 34 通过、build 通过、dev 库已迁移) |
+| 一·B 答案素材化 | 素材组约定 + 弹窗选择器/导入 + `source_kb_document_ids` 直传 + 本地生命周期失效钩子 | 无 | 待实现 |
+| 二 AI 自动维护 | 源范围 + 总结任务 + 快照同步 + 指纹观测 + 护栏/回滚 UI | 一·B | 待实现 |
+
+## 6. 非目标
+
+- **动态引用直答**(实时读 KB 渲染答案)——快照 + 失效机制已覆盖其唯一收益;
+- **无护栏全自动发布**——全自动仅对显式开启的条目,且必有校验与回滚;
+- **段落级绑定锚点**(标题+hash 局部失效)——素材文档小而专,整文档绑定足够,留作后续优化;
+- **素材文档进业务召回库**——即使配合元数据过滤也不采用。
+
+## 7. 待确认项
+
+1. 源范围圈定方式细节:建议一期支持「指定文档清单」+「整组」两档,标签后续按需;
+2. 全自动放开节奏:建议先以"AI 生成 + 待复审一键采纳"运行数周,观察质量后对稳定条目开 `auto_maintained`;
+3. 生成用 LLM 通道:专用 Dify 工作流应用(prompt 可视化调优)vs 后端直连 LLM API。
diff --git a/docs/funclist.md b/docs/funclist.md
index 8d289f8d..412a57cc 100644
--- a/docs/funclist.md
+++ b/docs/funclist.md
@@ -673,6 +673,7 @@
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
+| 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 |
---
diff --git a/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue b/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue
index 6d3daeff..fbb9f54c 100644
--- a/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue
+++ b/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue
@@ -3,10 +3,11 @@
* 用途:常用问题 / FAQ 缓存的创建与编辑对话框。字段多,宽 680px,两列短字段。
* 依赖:element-plus 对话框和表单、QuestionFormState、AdminAgentOption。
* 逻辑:QuestionsPage 打开本组件。提交时 emit save 或 review,由 useQuestionsAdmin 调接口。样式跟页面已引入的 Element 皮肤走。
- * is_enabled 仅控制工作台首页入口;cache_enabled 单独控制聊天是否跳过 Dify。
+ * is_enabled 仅控制工作台首页入口;cache_enabled 单独控制聊天是否跳过 Dify;
+ * fuzzy_enabled 在精确未命中时按阈值兜底直答,以 cache_enabled 为前提(关闭缓存时联动取消勾选)。
*/