feat(faq): 缓存高频问题及答案,命中直接返回预置答案,不走dify
This commit is contained in:
1 parent
3264ed1e07
commit
cf7cc11ffc
32 files changed
+3504
-180
No files matched your search
+15
@@ -122,3 +122,18 @@ SRM_SQLSERVER_TIMEOUT=10
|
||||
# ERP
|
||||
ERP_DB_DSN=192.168.8.24:1521/topprod
|
||||
TEXT2SQL_SCHEMA_PATH=
|
||||
|
||||
# Hot FAQ offline aggregation (ChatLog -> PostgreSQL faq_hot_candidates table)
|
||||
FAQ_HOT_ENABLED=true
|
||||
FAQ_HOT_WINDOW_DAYS=7
|
||||
FAQ_HOT_MIN_COUNT=5
|
||||
FAQ_HOT_MIN_USERS=3
|
||||
FAQ_HOT_MIN_AVG_TOKENS=0
|
||||
FAQ_HOT_MAX_QUERY_LEN=200
|
||||
FAQ_HOT_MIN_QUERY_LEN=4
|
||||
FAQ_HOT_MIN_ANSWER_LEN=8
|
||||
FAQ_HOT_TTL_SECONDS=604800
|
||||
FAQ_HOT_ANSWER_SIMILARITY=0.95
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6
|
||||
FAQ_HOT_GOOD_SCORE=4
|
||||
FAQ_HOT_BAD_SCORE=2
|
||||
@@ -181,4 +181,5 @@ 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) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
Vendored
+2
-1
@@ -147,7 +147,8 @@ def notifyPushPlusDeploy(Map opts) {
|
||||
// 企业微信 + PushPlus 微信双通道
|
||||
def notifyDeployAll(Map opts) {
|
||||
notifyWecomDeploy(opts)
|
||||
notifyPushPlusDeploy(opts)
|
||||
// 暂时只发企业微信通知
|
||||
// notifyPushPlusDeploy(opts)
|
||||
}
|
||||
|
||||
pipeline {
|
||||
|
||||
@@ -91,6 +91,8 @@ def create_app(config_name='default'):
|
||||
_apply_persisted_settings(app)
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
from app.cli.faq_commands import init_app as init_faq_cli
|
||||
init_faq_cli(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
|
||||
+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():
|
||||
|
||||
+14
-1
@@ -1153,7 +1153,20 @@ def chat_completions():
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
if PLMOracleService.supports(query, agent_proxy):
|
||||
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None
|
||||
|
||||
if faq_hit:
|
||||
generator = FaqCacheService.stream_chat(
|
||||
faq_hit,
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported and leave_feature_enabled:
|
||||
if normalized_files:
|
||||
|
||||
@@ -1652,7 +1652,12 @@ def home():
|
||||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents]
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter((QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)).all()
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).all()
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""FAQ CLI 包。"""
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
backend/app/cli/faq_commands.py
|
||||
|
||||
用途:FAQ 相关 Flask CLI 命令注册。
|
||||
依赖:HotFaqAggregator、Flask click。
|
||||
逻辑:create_app 时 init_app 注册 faq-aggregate-hot 命令。
|
||||
"""
|
||||
import click
|
||||
from flask.cli import with_appcontext
|
||||
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
|
||||
@click.command('faq-aggregate-hot')
|
||||
@click.option('--agent-id', type=int, default=None, help='仅聚合指定 Agent')
|
||||
@click.option('--dry-run', is_flag=True, help='只统计不写 PostgreSQL')
|
||||
@with_appcontext
|
||||
def faq_aggregate_hot(agent_id: int | None, dry_run: bool):
|
||||
"""
|
||||
离线聚合 ChatLog 热点 FAQ 候选并写入 faq_hot_candidates 表。
|
||||
核心逻辑:委托 HotFaqAggregator.aggregate_hot_faq_candidates。
|
||||
"""
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
if not result.get('enabled'):
|
||||
click.echo(result.get('message', 'FAQ hot aggregation disabled'))
|
||||
return
|
||||
|
||||
click.echo(
|
||||
f"scanned={result['scanned_logs']} groups={result['group_count']} "
|
||||
f"promoted={result['promoted_count']} skipped={result['skipped_count']} dry_run={dry_run}"
|
||||
)
|
||||
for item in result.get('candidates', [])[:20]:
|
||||
click.echo(
|
||||
f" [{item.get('agent_name')}] {item.get('canonical_query')} "
|
||||
f"asks={item.get('ask_count_7d')} users={item.get('user_count_7d')} "
|
||||
f"dominance={item.get('answer_dominance')}"
|
||||
)
|
||||
if len(result.get('candidates', [])) > 20:
|
||||
click.echo(f" ... and {len(result['candidates']) - 20} more")
|
||||
|
||||
|
||||
def init_app(app):
|
||||
"""向 Flask app 注册 FAQ CLI 命令。"""
|
||||
app.cli.add_command(faq_aggregate_hot)
|
||||
+43
-1
@@ -276,7 +276,7 @@ class PermissionRequest(Base):
|
||||
class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储用户自定义的常用问题
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
"""
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
@@ -285,8 +285,50 @@ class QuickQuestion(Base):
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
title: Mapped[str] = mapped_column(String(100))
|
||||
question: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
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)
|
||||
hit_count: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class FaqHotCandidate(Base):
|
||||
"""
|
||||
热点 FAQ 候选表
|
||||
用途:离线聚合 ChatLog 后的待审核热点问句与推荐答案(PostgreSQL 存储,不含在线命中)。
|
||||
"""
|
||||
__tablename__ = 'faq_hot_candidates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('agent_id', 'q_norm', name='uq_faq_hot_candidates_agent_qnorm'),
|
||||
Index('ix_faq_hot_candidates_status_expires', 'status', 'expires_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
q_norm: Mapped[str] = mapped_column(String(255))
|
||||
canonical_query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
source_chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True)
|
||||
ask_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
user_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
avg_tokens: Mapped[int] = mapped_column(default=0)
|
||||
avg_latency_ms: Mapped[int] = mapped_column(default=0)
|
||||
answer_dominance: Mapped[float] = mapped_column(default=0.0)
|
||||
sample_queries: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
last_asked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='candidate') # candidate | promoted | dismissed
|
||||
promoted_quick_question_id: Mapped[Optional[int]] = mapped_column(ForeignKey('quick_questions.id'), nullable=True)
|
||||
deny_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class Announcement(Base):
|
||||
"""
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
backend/app/services/faq_hot_settings.py
|
||||
|
||||
用途:读取热点 FAQ 离线聚合环境变量(权威默认值在仓库根 `.env.shared`)。
|
||||
依赖:os.environ(由 config._load_environment_files 在启动时加载)。
|
||||
逻辑:hot_faq_aggregator、hot_faq_candidate_store 通过本模块读配置,不经过 config.py。
|
||||
"""
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
|
||||
def read_faq_hot_env(key: str, default: Any) -> Any:
|
||||
"""
|
||||
读取单个 FAQ_HOT_* 环境变量并按 default 类型转换。
|
||||
@param key - 环境变量名,如 FAQ_HOT_WINDOW_DAYS
|
||||
@param default - 未配置时的兜底值,同时决定返回类型
|
||||
@returns 转换后的配置值
|
||||
"""
|
||||
raw = os.getenv(key)
|
||||
if raw is None or str(raw).strip() == '':
|
||||
return default
|
||||
text = str(raw).strip()
|
||||
if isinstance(default, bool):
|
||||
return text.lower() == 'true'
|
||||
if isinstance(default, float):
|
||||
return float(text)
|
||||
if isinstance(default, int):
|
||||
return int(text)
|
||||
return text
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
backend/app/services/faq_text_utils.py
|
||||
|
||||
用途:FAQ / 热点问句归一化等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||
依赖:无外部业务模块。
|
||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则。
|
||||
"""
|
||||
import re
|
||||
|
||||
|
||||
def normalize_faq_query(text: str) -> str:
|
||||
"""
|
||||
归一化问句文本,便于精确匹配与 ChatLog 分组。
|
||||
核心逻辑:trim → 小写 → 去除空白与常见中英文标点。
|
||||
@param text - 原始问句
|
||||
@returns 归一化后的字符串;空输入返回空串
|
||||
"""
|
||||
value = str(text or "").strip().lower()
|
||||
value = re.sub(r"[\s\u3000,。!?、;:""''()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||
return value
|
||||
@@ -0,0 +1,449 @@
|
||||
"""
|
||||
backend/app/services/hot_faq_aggregator.py
|
||||
|
||||
用途:从 ChatLog 离线聚合热点 FAQ 候选,写入 PostgreSQL 候选表(不含在线命中)。
|
||||
依赖:ChatLog、Feedback、QuickQuestion、faq_text_utils、hot_faq_candidate_store。
|
||||
逻辑:CLI `flask faq-aggregate-hot` 与管理端「刷新」调用 aggregate_hot_faq_candidates。
|
||||
|
||||
## 热点选取规则(HOT_FAQ_SELECTION_RULES)
|
||||
|
||||
1. **时间窗口**:仅统计近 FAQ_HOT_WINDOW_DAYS 天(默认 7 天)的 ChatLog。
|
||||
2. **必须走过 Dify**:tokens_used > 0(排除 HR/PLM 等本地直答、已有 FAQ 缓存)。
|
||||
3. **排除已有缓存来源**:payload.source 为 faq_cache / hot_faq_cache 的记录不参与。
|
||||
4. **排除特殊业务 payload**:含 material_no(PLM)、query_mode(PLM)等标记。
|
||||
5. **问句长度**:归一化前 query 长度 ≤ FAQ_HOT_MAX_QUERY_LEN(默认 200)。
|
||||
6. **问句非空**:query、answer 均需有实质内容(≥ FAQ_HOT_MIN_QUERY_LEN / MIN_ANSWER_LEN)。
|
||||
7. **分组键**:(agent_id, normalize_faq_query(query))。
|
||||
8. **频次门槛**:组内 ask_count ≥ FAQ_HOT_MIN_COUNT(默认 5)。
|
||||
9. **用户门槛**:组内 distinct user_id ≥ FAQ_HOT_MIN_USERS(默认 3),防止单人刷榜。
|
||||
10. **Token 门槛(可选)**:组内 avg(tokens_used) ≥ FAQ_HOT_MIN_AVG_TOKENS(默认 0 表示不限制)。
|
||||
11. **deny 黑名单**:管理员已忽略的 q_norm 不再晋升。
|
||||
12. **人工 FAQ 已覆盖**:同 agent 下已有 cache_enabled 的全局 QuickQuestion 匹配同 q_norm 则跳过。
|
||||
|
||||
## 最佳答案选取规则(HOT_FAQ_ANSWER_RULES)
|
||||
|
||||
1. **答案聚类**:对组内每条 ChatLog 的 answer 做相似度聚类(SequenceMatcher ≥ FAQ_HOT_ANSWER_SIMILARITY,默认 0.95)。
|
||||
2. **一致性门槛**:最大簇占比 ≥ FAQ_HOT_ANSWER_DOMINANCE(默认 0.6);否则视为答案分歧过大,整组跳过。
|
||||
3. **在最大簇内选代表答案**,优先级:
|
||||
a. Feedback.score ≥ FAQ_HOT_GOOD_SCORE(默认 4)的记录中,取 created_at 最新;
|
||||
b. 否则排除 Feedback.score ≤ FAQ_HOT_BAD_SCORE(默认 2)的记录,取 created_at 最新;
|
||||
c. 否则取簇内 created_at 最新的 answer。
|
||||
4. **canonical_query**:取该组内出现次数最多的原始 query 文本(非归一化,便于人工阅读)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app.models import Agent, ChatLog, QuickQuestion, db
|
||||
from app.services.faq_hot_settings import read_faq_hot_env
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
|
||||
HOT_FAQ_SELECTION_RULES: dict[str, Any] = {
|
||||
'window_days': 'FAQ_HOT_WINDOW_DAYS',
|
||||
'min_count': 'FAQ_HOT_MIN_COUNT',
|
||||
'min_users': 'FAQ_HOT_MIN_USERS',
|
||||
'min_avg_tokens': 'FAQ_HOT_MIN_AVG_TOKENS',
|
||||
'max_query_len': 'FAQ_HOT_MAX_QUERY_LEN',
|
||||
'min_query_len': 'FAQ_HOT_MIN_QUERY_LEN',
|
||||
'min_answer_len': 'FAQ_HOT_MIN_ANSWER_LEN',
|
||||
'excluded_payload_sources': ('faq_cache', 'hot_faq_cache'),
|
||||
'excluded_payload_keys': ('material_no', 'query_mode'),
|
||||
}
|
||||
|
||||
HOT_FAQ_ANSWER_RULES: dict[str, Any] = {
|
||||
'answer_similarity': 'FAQ_HOT_ANSWER_SIMILARITY',
|
||||
'answer_dominance': 'FAQ_HOT_ANSWER_DOMINANCE',
|
||||
'good_feedback_score': 'FAQ_HOT_GOOD_SCORE',
|
||||
'bad_feedback_score': 'FAQ_HOT_BAD_SCORE',
|
||||
}
|
||||
|
||||
HOT_FAQ_AGGREGATOR_DOC_SELECTION = (
|
||||
'近 N 天内 tokens_used>0 的 Dify 对话,按 agent+归一化问句分组;'
|
||||
'需满足最少提问次数、独立用户数;排除 FAQ 缓存来源与 PLM 等特殊 payload。'
|
||||
)
|
||||
|
||||
HOT_FAQ_AGGREGATOR_DOC_ANSWER = (
|
||||
'答案按相似度聚类,最大簇占比需≥dominance 阈值;'
|
||||
'在最大簇内优先选好评最新,其次无差评最新,最后取最新记录。'
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _LogRow:
|
||||
"""聚合过程中的单条 ChatLog 快照。"""
|
||||
|
||||
chat_log_id: int
|
||||
user_id: int
|
||||
agent_id: int
|
||||
query: str
|
||||
answer: str
|
||||
tokens_used: int
|
||||
latency: int
|
||||
created_at: datetime
|
||||
feedback_score: Optional[int] = None
|
||||
retriever_resources: list = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class HotFaqCandidate:
|
||||
"""聚合产出的热点候选。"""
|
||||
|
||||
agent_id: int
|
||||
agent_name: str
|
||||
q_norm: str
|
||||
canonical_query: str
|
||||
answer: str
|
||||
source_chat_log_id: int
|
||||
ask_count_7d: int
|
||||
user_count_7d: int
|
||||
avg_tokens: int
|
||||
avg_latency_ms: int
|
||||
last_asked_at: str
|
||||
answer_dominance: float
|
||||
sample_queries: list[str] = field(default_factory=list)
|
||||
retriever_resources: list = field(default_factory=list)
|
||||
|
||||
def to_store_payload(self) -> dict[str, Any]:
|
||||
return {
|
||||
'agent_id': self.agent_id,
|
||||
'agent_name': self.agent_name,
|
||||
'q_norm': self.q_norm,
|
||||
'canonical_query': self.canonical_query,
|
||||
'answer': self.answer,
|
||||
'source_chat_log_id': self.source_chat_log_id,
|
||||
'ask_count_7d': self.ask_count_7d,
|
||||
'user_count_7d': self.user_count_7d,
|
||||
'avg_tokens': self.avg_tokens,
|
||||
'avg_latency_ms': self.avg_latency_ms,
|
||||
'last_asked_at': self.last_asked_at,
|
||||
'answer_dominance': round(self.answer_dominance, 4),
|
||||
'sample_queries': self.sample_queries[:5],
|
||||
'retriever_resources': self.retriever_resources,
|
||||
'status': 'candidate',
|
||||
'auto': True,
|
||||
}
|
||||
|
||||
|
||||
class HotFaqAggregator:
|
||||
"""ChatLog 离线热点聚合器。"""
|
||||
|
||||
@staticmethod
|
||||
def _cfg(key: str, default: Any) -> Any:
|
||||
"""从环境变量读取 FAQ_HOT 配置(见 `.env.shared`)。"""
|
||||
return read_faq_hot_env(key, default)
|
||||
|
||||
@classmethod
|
||||
def get_rules_document(cls) -> dict[str, Any]:
|
||||
"""
|
||||
返回当前生效的规则说明与配置值,供管理端展示。
|
||||
@returns selection + answer 规则字典
|
||||
"""
|
||||
return {
|
||||
'selection': {
|
||||
'window_days': int(cls._cfg('FAQ_HOT_WINDOW_DAYS', 7)),
|
||||
'min_count': int(cls._cfg('FAQ_HOT_MIN_COUNT', 5)),
|
||||
'min_users': int(cls._cfg('FAQ_HOT_MIN_USERS', 3)),
|
||||
'min_avg_tokens': int(cls._cfg('FAQ_HOT_MIN_AVG_TOKENS', 0)),
|
||||
'max_query_len': int(cls._cfg('FAQ_HOT_MAX_QUERY_LEN', 200)),
|
||||
'min_query_len': int(cls._cfg('FAQ_HOT_MIN_QUERY_LEN', 4)),
|
||||
'min_answer_len': int(cls._cfg('FAQ_HOT_MIN_ANSWER_LEN', 8)),
|
||||
'excluded_payload_sources': list(HOT_FAQ_SELECTION_RULES['excluded_payload_sources']),
|
||||
'description': HOT_FAQ_AGGREGATOR_DOC_SELECTION,
|
||||
},
|
||||
'answer': {
|
||||
'answer_similarity': float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95)),
|
||||
'answer_dominance': float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6)),
|
||||
'good_feedback_score': int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4)),
|
||||
'bad_feedback_score': int(cls._cfg('FAQ_HOT_BAD_SCORE', 2)),
|
||||
'description': HOT_FAQ_AGGREGATOR_DOC_ANSWER,
|
||||
},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def aggregate_hot_faq_candidates(
|
||||
cls,
|
||||
*,
|
||||
agent_id: int | None = None,
|
||||
dry_run: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
执行离线热点聚合:扫描 ChatLog → 筛选 → 选最佳答案 → 写入 Redis。
|
||||
@param agent_id - 可选,仅聚合指定 Agent
|
||||
@param dry_run - True 时不写 Redis
|
||||
@returns 汇总结果:candidates / skipped / stats / rules
|
||||
"""
|
||||
if not cls._cfg('FAQ_HOT_ENABLED', True):
|
||||
return {'enabled': False, 'message': 'FAQ_HOT_ENABLED is false', 'candidates': []}
|
||||
|
||||
if not dry_run:
|
||||
HotFaqCandidateStore.purge_expired()
|
||||
|
||||
since = datetime.utcnow() - timedelta(days=int(cls._cfg('FAQ_HOT_WINDOW_DAYS', 7)))
|
||||
logs = cls._load_chat_logs(since, agent_id)
|
||||
groups = cls._group_logs(logs)
|
||||
|
||||
agent_names = cls._load_agent_names({aid for aid, _ in groups.keys()})
|
||||
manual_norms = cls._load_manual_faq_norms(agent_id)
|
||||
|
||||
promoted: list[HotFaqCandidate] = []
|
||||
skipped: list[dict[str, Any]] = []
|
||||
|
||||
for (aid, q_norm), rows in groups.items():
|
||||
if HotFaqCandidateStore.is_denied(aid, q_norm):
|
||||
skipped.append({'agent_id': aid, 'q_norm': q_norm, 'reason': 'deny_list'})
|
||||
continue
|
||||
if q_norm in manual_norms.get(aid, set()):
|
||||
skipped.append({'agent_id': aid, 'q_norm': q_norm, 'reason': 'manual_faq_exists'})
|
||||
continue
|
||||
|
||||
candidate, reason = cls._build_candidate(aid, agent_names.get(aid, 'Unknown'), q_norm, rows)
|
||||
if candidate is None:
|
||||
skipped.append({'agent_id': aid, 'q_norm': q_norm, 'reason': reason or 'unknown'})
|
||||
continue
|
||||
|
||||
promoted.append(candidate)
|
||||
if not dry_run:
|
||||
HotFaqCandidateStore.save_candidate(aid, q_norm, candidate.to_store_payload())
|
||||
|
||||
promoted.sort(key=lambda c: c.ask_count_7d, reverse=True)
|
||||
return {
|
||||
'enabled': True,
|
||||
'dry_run': dry_run,
|
||||
'window_since': since.isoformat(),
|
||||
'scanned_logs': len(logs),
|
||||
'group_count': len(groups),
|
||||
'promoted_count': len(promoted),
|
||||
'skipped_count': len(skipped),
|
||||
'candidates': [c.to_store_payload() for c in promoted],
|
||||
'skipped': skipped[:100],
|
||||
'rules': cls.get_rules_document(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _load_chat_logs(cls, since: datetime, agent_id: int | None) -> list[_LogRow]:
|
||||
"""加载时间窗口内、通过基础过滤的 ChatLog。"""
|
||||
query = (
|
||||
db.session.query(ChatLog)
|
||||
.options(joinedload(ChatLog.feedback))
|
||||
.filter(ChatLog.created_at >= since, ChatLog.tokens_used > 0)
|
||||
)
|
||||
if agent_id is not None:
|
||||
query = query.filter(ChatLog.agent_id == agent_id)
|
||||
|
||||
max_query_len = int(cls._cfg('FAQ_HOT_MAX_QUERY_LEN', 200))
|
||||
min_query_len = int(cls._cfg('FAQ_HOT_MIN_QUERY_LEN', 4))
|
||||
min_answer_len = int(cls._cfg('FAQ_HOT_MIN_ANSWER_LEN', 8))
|
||||
excluded_sources = set(HOT_FAQ_SELECTION_RULES['excluded_payload_sources'])
|
||||
|
||||
rows: list[_LogRow] = []
|
||||
for log in query.all():
|
||||
if not cls._passes_log_filters(log, excluded_sources, max_query_len, min_query_len, min_answer_len):
|
||||
continue
|
||||
score = log.feedback.score if log.feedback else None
|
||||
rows.append(
|
||||
_LogRow(
|
||||
chat_log_id=log.id,
|
||||
user_id=log.user_id,
|
||||
agent_id=log.agent_id,
|
||||
query=str(log.query or '').strip(),
|
||||
answer=str(log.answer or '').strip(),
|
||||
tokens_used=int(log.tokens_used or 0),
|
||||
latency=int(log.latency or 0),
|
||||
created_at=log.created_at,
|
||||
feedback_score=score,
|
||||
retriever_resources=log.retriever_resources if isinstance(log.retriever_resources, list) else [],
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
@staticmethod
|
||||
def _passes_log_filters(
|
||||
log: ChatLog,
|
||||
excluded_sources: set[str],
|
||||
max_query_len: int,
|
||||
min_query_len: int,
|
||||
min_answer_len: int,
|
||||
) -> bool:
|
||||
"""
|
||||
单条 ChatLog 是否纳入统计。
|
||||
核心逻辑:长度、payload 来源、特殊业务字段检查。
|
||||
"""
|
||||
query = str(log.query or '').strip()
|
||||
answer = str(log.answer or '').strip()
|
||||
if len(query) < min_query_len or len(answer) < min_answer_len:
|
||||
return False
|
||||
if len(query) > max_query_len:
|
||||
return False
|
||||
|
||||
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
source = str(payload.get('source') or '').strip()
|
||||
if source in excluded_sources:
|
||||
return False
|
||||
for key in HOT_FAQ_SELECTION_RULES['excluded_payload_keys']:
|
||||
if payload.get(key):
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def _group_logs(cls, logs: list[_LogRow]) -> dict[tuple[int, str], list[_LogRow]]:
|
||||
"""
|
||||
按 (agent_id, q_norm) 分组,并应用频次 / 用户 / Token 门槛。
|
||||
@returns 通过门槛的分组
|
||||
"""
|
||||
buckets: dict[tuple[int, str], list[_LogRow]] = defaultdict(list)
|
||||
for row in logs:
|
||||
q_norm = normalize_faq_query(row.query)
|
||||
if not q_norm:
|
||||
continue
|
||||
buckets[(row.agent_id, q_norm)].append(row)
|
||||
|
||||
min_count = int(cls._cfg('FAQ_HOT_MIN_COUNT', 5))
|
||||
min_users = int(cls._cfg('FAQ_HOT_MIN_USERS', 3))
|
||||
min_avg_tokens = int(cls._cfg('FAQ_HOT_MIN_AVG_TOKENS', 0))
|
||||
|
||||
qualified: dict[tuple[int, str], list[_LogRow]] = {}
|
||||
for key, rows in buckets.items():
|
||||
if len(rows) < min_count:
|
||||
continue
|
||||
if len({r.user_id for r in rows}) < min_users:
|
||||
continue
|
||||
avg_tokens = sum(r.tokens_used for r in rows) / len(rows)
|
||||
if min_avg_tokens > 0 and avg_tokens < min_avg_tokens:
|
||||
continue
|
||||
qualified[key] = rows
|
||||
return qualified
|
||||
|
||||
@classmethod
|
||||
def _build_candidate(
|
||||
cls,
|
||||
agent_id: int,
|
||||
agent_name: str,
|
||||
q_norm: str,
|
||||
rows: list[_LogRow],
|
||||
) -> tuple[Optional[HotFaqCandidate], Optional[str]]:
|
||||
"""从一组 ChatLog 构建热点候选;失败时返回 skip reason。"""
|
||||
dominance_threshold = float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6))
|
||||
clusters = cls._cluster_answers(rows)
|
||||
if not clusters:
|
||||
return None, 'empty_answer_clusters'
|
||||
|
||||
largest = max(clusters, key=lambda c: len(c['rows']))
|
||||
dominance = len(largest['rows']) / len(rows)
|
||||
if dominance < dominance_threshold:
|
||||
return None, f'answer_divergence:{dominance:.2f}'
|
||||
|
||||
rep = cls._pick_representative_answer(largest['rows'])
|
||||
if not rep:
|
||||
return None, 'no_representative_answer'
|
||||
|
||||
query_counter = Counter(r.query for r in rows)
|
||||
canonical_query = query_counter.most_common(1)[0][0]
|
||||
sample_queries = [q for q, _ in query_counter.most_common(5)]
|
||||
|
||||
last_asked = max(r.created_at for r in rows)
|
||||
avg_tokens = int(sum(r.tokens_used for r in rows) / len(rows))
|
||||
avg_latency = int(sum(r.latency for r in rows) / len(rows))
|
||||
|
||||
return HotFaqCandidate(
|
||||
agent_id=agent_id,
|
||||
agent_name=agent_name,
|
||||
q_norm=q_norm,
|
||||
canonical_query=canonical_query,
|
||||
answer=rep.answer,
|
||||
source_chat_log_id=rep.chat_log_id,
|
||||
ask_count_7d=len(rows),
|
||||
user_count_7d=len({r.user_id for r in rows}),
|
||||
avg_tokens=avg_tokens,
|
||||
avg_latency_ms=avg_latency,
|
||||
last_asked_at=last_asked.isoformat(),
|
||||
answer_dominance=dominance,
|
||||
sample_queries=sample_queries,
|
||||
retriever_resources=rep.retriever_resources,
|
||||
), None
|
||||
|
||||
@classmethod
|
||||
def _cluster_answers(cls, rows: list[_LogRow]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 answer 按相似度聚类(贪心:与簇代表相似度 ≥ 阈值则归入)。
|
||||
@returns [{'representative': str, 'rows': [_LogRow, ...]}, ...]
|
||||
"""
|
||||
threshold = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95))
|
||||
clusters: list[dict[str, Any]] = []
|
||||
|
||||
for row in rows:
|
||||
answer = row.answer.strip()
|
||||
if not answer:
|
||||
continue
|
||||
placed = False
|
||||
for cluster in clusters:
|
||||
rep = cluster['representative']
|
||||
if cls._answer_similarity(rep, answer) >= threshold:
|
||||
cluster['rows'].append(row)
|
||||
placed = True
|
||||
break
|
||||
if not placed:
|
||||
clusters.append({'representative': answer, 'rows': [row]})
|
||||
return clusters
|
||||
|
||||
@staticmethod
|
||||
def _answer_similarity(a: str, b: str) -> float:
|
||||
"""计算两段答案文本相似度(0~1)。"""
|
||||
left = re.sub(r'\s+', ' ', a.strip())
|
||||
right = re.sub(r'\s+', ' ', b.strip())
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
return SequenceMatcher(None, left, right).ratio()
|
||||
|
||||
@classmethod
|
||||
def _pick_representative_answer(cls, rows: list[_LogRow]) -> Optional[_LogRow]:
|
||||
"""
|
||||
在 dominant 簇内按反馈优先级选取最佳 ChatLog 行。
|
||||
优先级:好评最新 > 无差评最新 > 簇内最新。
|
||||
"""
|
||||
good_score = int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4))
|
||||
bad_score = int(cls._cfg('FAQ_HOT_BAD_SCORE', 2))
|
||||
|
||||
good_rows = [r for r in rows if r.feedback_score is not None and r.feedback_score >= good_score]
|
||||
if good_rows:
|
||||
return max(good_rows, key=lambda r: r.created_at)
|
||||
|
||||
neutral_rows = [r for r in rows if r.feedback_score is None or r.feedback_score > bad_score]
|
||||
if neutral_rows:
|
||||
return max(neutral_rows, key=lambda r: r.created_at)
|
||||
|
||||
return max(rows, key=lambda r: r.created_at) if rows else None
|
||||
|
||||
@staticmethod
|
||||
def _load_agent_names(agent_ids: set[int]) -> dict[int, str]:
|
||||
if not agent_ids:
|
||||
return {}
|
||||
agents = db.session.query(Agent.id, Agent.name).filter(Agent.id.in_(agent_ids)).all()
|
||||
return {a.id: a.name for a in agents}
|
||||
|
||||
@staticmethod
|
||||
def _load_manual_faq_norms(agent_id: int | None) -> dict[int, set[str]]:
|
||||
"""加载已启用 cache 的全局 QuickQuestion 归一化问句,避免重复。"""
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
|
||||
query = db.session.query(QuickQuestion).filter(
|
||||
QuickQuestion.user_id.is_(None),
|
||||
QuickQuestion.cache_enabled.is_(True),
|
||||
)
|
||||
if agent_id is not None:
|
||||
query = query.filter(QuickQuestion.agent_id == agent_id)
|
||||
|
||||
result: dict[int, set[str]] = defaultdict(set)
|
||||
for entry in query.all():
|
||||
for text in FaqCacheService._candidate_texts(entry):
|
||||
result[entry.agent_id].add(text)
|
||||
return result
|
||||
@@ -0,0 +1,308 @@
|
||||
"""
|
||||
backend/app/services/hot_faq_candidate_store.py
|
||||
|
||||
用途:热点 FAQ 候选池 PostgreSQL 读写(离线聚合结果,不含在线命中)。
|
||||
依赖:models.FaqHotCandidate、Agent、faq_hot_settings、SQLAlchemy db。
|
||||
逻辑:HotFaqAggregator 写入;管理端 API 读取 / 晋升 / 忽略。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import desc, or_
|
||||
|
||||
from app.models import Agent, FaqHotCandidate, db
|
||||
from app.services.faq_hot_settings import read_faq_hot_env
|
||||
|
||||
|
||||
class HotFaqCandidateStore:
|
||||
"""热点 FAQ 候选 PostgreSQL 存储。"""
|
||||
|
||||
@classmethod
|
||||
def _now(cls) -> datetime:
|
||||
return datetime.utcnow()
|
||||
|
||||
@classmethod
|
||||
def _expires_at(cls) -> datetime:
|
||||
ttl = int(read_faq_hot_env('FAQ_HOT_TTL_SECONDS', 604800))
|
||||
return cls._now() + timedelta(seconds=ttl)
|
||||
|
||||
@classmethod
|
||||
def _deny_until(cls) -> datetime:
|
||||
return cls._expires_at()
|
||||
|
||||
@classmethod
|
||||
def purge_expired(cls) -> int:
|
||||
"""
|
||||
清理已过期的 candidate 记录。
|
||||
@returns 删除条数
|
||||
"""
|
||||
now = cls._now()
|
||||
try:
|
||||
count = (
|
||||
db.session.query(FaqHotCandidate)
|
||||
.filter(
|
||||
FaqHotCandidate.status == 'candidate',
|
||||
FaqHotCandidate.expires_at.isnot(None),
|
||||
FaqHotCandidate.expires_at < now,
|
||||
)
|
||||
.delete(synchronize_session=False)
|
||||
)
|
||||
db.session.commit()
|
||||
return int(count or 0)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.warning('[hot-faq-store] purge_expired failed: %s', exc)
|
||||
return 0
|
||||
|
||||
@classmethod
|
||||
def is_denied(cls, agent_id: int, q_norm: str) -> bool:
|
||||
"""
|
||||
判断问句是否在忽略黑名单有效期内。
|
||||
@param agent_id - Agent 主键
|
||||
@param q_norm - 归一化问句
|
||||
@returns True 表示仍在 deny 期
|
||||
"""
|
||||
now = cls._now()
|
||||
row = (
|
||||
db.session.query(FaqHotCandidate)
|
||||
.filter(
|
||||
FaqHotCandidate.agent_id == agent_id,
|
||||
FaqHotCandidate.q_norm == q_norm,
|
||||
FaqHotCandidate.status == 'dismissed',
|
||||
FaqHotCandidate.deny_until.isnot(None),
|
||||
FaqHotCandidate.deny_until > now,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return row is not None
|
||||
|
||||
@classmethod
|
||||
def add_deny(cls, agent_id: int, q_norm: str) -> bool:
|
||||
"""
|
||||
将问句标记为 dismissed 并设置 deny_until。
|
||||
@returns 是否成功
|
||||
"""
|
||||
return cls.dismiss(agent_id, q_norm)
|
||||
|
||||
@classmethod
|
||||
def dismiss(cls, agent_id: int, q_norm: str) -> bool:
|
||||
"""
|
||||
忽略热点候选:status=dismissed,并设置 deny_until。
|
||||
@returns 是否成功
|
||||
"""
|
||||
now = cls._now()
|
||||
try:
|
||||
row = (
|
||||
db.session.query(FaqHotCandidate)
|
||||
.filter(FaqHotCandidate.agent_id == agent_id, FaqHotCandidate.q_norm == q_norm)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = FaqHotCandidate(
|
||||
agent_id=agent_id,
|
||||
q_norm=q_norm,
|
||||
canonical_query=q_norm,
|
||||
answer='',
|
||||
status='dismissed',
|
||||
)
|
||||
db.session.add(row)
|
||||
row.status = 'dismissed'
|
||||
row.deny_until = cls._deny_until()
|
||||
row.updated_at = now
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.warning('[hot-faq-store] dismiss failed: %s', exc)
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def save_candidate(cls, agent_id: int, q_norm: str, payload: dict[str, Any]) -> bool:
|
||||
"""
|
||||
UPSERT 一条热点候选(status=candidate)。
|
||||
@param payload - 候选字段字典
|
||||
@returns 是否写入成功
|
||||
"""
|
||||
now = cls._now()
|
||||
try:
|
||||
row = (
|
||||
db.session.query(FaqHotCandidate)
|
||||
.filter(FaqHotCandidate.agent_id == agent_id, FaqHotCandidate.q_norm == q_norm)
|
||||
.first()
|
||||
)
|
||||
last_asked_raw = payload.get('last_asked_at')
|
||||
last_asked_at = None
|
||||
if last_asked_raw:
|
||||
try:
|
||||
last_asked_at = datetime.fromisoformat(str(last_asked_raw).replace('Z', '+00:00')).replace(tzinfo=None)
|
||||
except ValueError:
|
||||
last_asked_at = None
|
||||
|
||||
fields = {
|
||||
'canonical_query': str(payload.get('canonical_query') or q_norm),
|
||||
'answer': str(payload.get('answer') or ''),
|
||||
'source_chat_log_id': payload.get('source_chat_log_id'),
|
||||
'ask_count_7d': int(payload.get('ask_count_7d') or 0),
|
||||
'user_count_7d': int(payload.get('user_count_7d') or 0),
|
||||
'avg_tokens': int(payload.get('avg_tokens') or 0),
|
||||
'avg_latency_ms': int(payload.get('avg_latency_ms') or 0),
|
||||
'answer_dominance': float(payload.get('answer_dominance') or 0),
|
||||
'sample_queries': payload.get('sample_queries') if isinstance(payload.get('sample_queries'), list) else None,
|
||||
'retriever_resources': payload.get('retriever_resources') if isinstance(payload.get('retriever_resources'), list) else None,
|
||||
'last_asked_at': last_asked_at,
|
||||
'status': 'candidate',
|
||||
'deny_until': None,
|
||||
'promoted_quick_question_id': None,
|
||||
'expires_at': cls._expires_at(),
|
||||
'updated_at': now,
|
||||
}
|
||||
|
||||
if row is None:
|
||||
row = FaqHotCandidate(agent_id=agent_id, q_norm=q_norm, **fields)
|
||||
db.session.add(row)
|
||||
elif row.status == 'promoted':
|
||||
return True
|
||||
else:
|
||||
for key, value in fields.items():
|
||||
setattr(row, key, value)
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.warning('[hot-faq-store] save failed agent=%s q_norm=%s: %s', agent_id, q_norm, exc)
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def mark_promoted(cls, agent_id: int, q_norm: str, quick_question_id: int) -> bool:
|
||||
"""
|
||||
将候选标记为已晋升为 QuickQuestion。
|
||||
@returns 是否更新成功
|
||||
"""
|
||||
try:
|
||||
row = (
|
||||
db.session.query(FaqHotCandidate)
|
||||
.filter(
|
||||
FaqHotCandidate.agent_id == agent_id,
|
||||
FaqHotCandidate.q_norm == q_norm,
|
||||
FaqHotCandidate.status == 'candidate',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not row:
|
||||
return False
|
||||
row.status = 'promoted'
|
||||
row.promoted_quick_question_id = quick_question_id
|
||||
row.updated_at = cls._now()
|
||||
return True
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning('[hot-faq-store] mark_promoted failed: %s', exc)
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def delete_candidate(cls, agent_id: int, q_norm: str) -> bool:
|
||||
"""删除 candidate 状态记录(兼容旧接口;dismiss/promote 优先用状态标记)。"""
|
||||
try:
|
||||
count = (
|
||||
db.session.query(FaqHotCandidate)
|
||||
.filter(
|
||||
FaqHotCandidate.agent_id == agent_id,
|
||||
FaqHotCandidate.q_norm == q_norm,
|
||||
FaqHotCandidate.status == 'candidate',
|
||||
)
|
||||
.delete(synchronize_session=False)
|
||||
)
|
||||
db.session.commit()
|
||||
return bool(count)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.warning('[hot-faq-store] delete failed: %s', exc)
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _serialize(cls, row: FaqHotCandidate, agent_name: str | None = None) -> dict[str, Any]:
|
||||
"""将 ORM 行序列化为 API 字典。"""
|
||||
return {
|
||||
'id': row.id,
|
||||
'agent_id': row.agent_id,
|
||||
'agent_name': agent_name,
|
||||
'q_norm': row.q_norm,
|
||||
'canonical_query': row.canonical_query,
|
||||
'answer': row.answer,
|
||||
'source_chat_log_id': row.source_chat_log_id,
|
||||
'ask_count_7d': row.ask_count_7d,
|
||||
'user_count_7d': row.user_count_7d,
|
||||
'avg_tokens': row.avg_tokens,
|
||||
'avg_latency_ms': row.avg_latency_ms,
|
||||
'answer_dominance': row.answer_dominance,
|
||||
'sample_queries': row.sample_queries or [],
|
||||
'retriever_resources': row.retriever_resources or [],
|
||||
'last_asked_at': row.last_asked_at.isoformat() if row.last_asked_at else None,
|
||||
'status': row.status,
|
||||
'expires_at': row.expires_at.isoformat() if row.expires_at else None,
|
||||
'updated_at': row.updated_at.isoformat() if row.updated_at else None,
|
||||
'auto': True,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def get_candidate(cls, agent_id: int, q_norm: str) -> Optional[dict[str, Any]]:
|
||||
"""读取单条有效 candidate。"""
|
||||
now = cls._now()
|
||||
row = (
|
||||
db.session.query(FaqHotCandidate, Agent.name)
|
||||
.join(Agent, Agent.id == FaqHotCandidate.agent_id)
|
||||
.filter(
|
||||
FaqHotCandidate.agent_id == agent_id,
|
||||
FaqHotCandidate.q_norm == q_norm,
|
||||
FaqHotCandidate.status == 'candidate',
|
||||
or_(FaqHotCandidate.expires_at.is_(None), FaqHotCandidate.expires_at >= now),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
candidate, agent_name = row
|
||||
return cls._serialize(candidate, agent_name)
|
||||
|
||||
@classmethod
|
||||
def list_candidates(cls, agent_id: int | None = None) -> list[dict[str, Any]]:
|
||||
"""
|
||||
列出有效 candidate 条目。
|
||||
@returns 按 ask_count_7d 降序
|
||||
"""
|
||||
now = cls._now()
|
||||
query = (
|
||||
db.session.query(FaqHotCandidate, Agent.name)
|
||||
.join(Agent, Agent.id == FaqHotCandidate.agent_id)
|
||||
.filter(
|
||||
FaqHotCandidate.status == 'candidate',
|
||||
or_(FaqHotCandidate.expires_at.is_(None), FaqHotCandidate.expires_at >= now),
|
||||
)
|
||||
)
|
||||
if agent_id is not None:
|
||||
query = query.filter(FaqHotCandidate.agent_id == agent_id)
|
||||
rows = query.order_by(desc(FaqHotCandidate.ask_count_7d), desc(FaqHotCandidate.updated_at)).all()
|
||||
return [cls._serialize(candidate, agent_name) for candidate, agent_name in rows]
|
||||
|
||||
@classmethod
|
||||
def summarize(cls, candidates: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
汇总候选池统计。
|
||||
@returns total / total_ask_count / estimated_tokens_saved
|
||||
"""
|
||||
rows = candidates if candidates is not None else cls.list_candidates()
|
||||
total_ask = sum(int(r.get('ask_count_7d') or 0) for r in rows)
|
||||
est_saved = sum(int(r.get('ask_count_7d') or 0) * int(r.get('avg_tokens') or 0) for r in rows)
|
||||
return {
|
||||
'total_candidates': len(rows),
|
||||
'total_ask_count_7d': total_ask,
|
||||
'estimated_tokens_if_cached': est_saved,
|
||||
'storage': 'postgresql',
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
backend/app/services/redis_client.py
|
||||
|
||||
用途:Redis 连接封装,供热点 FAQ 候选池等模块使用。
|
||||
依赖:redis、Flask current_app/config。
|
||||
逻辑:连接失败时返回 None,调用方降级处理,不阻断主业务。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
import redis
|
||||
except ImportError: # pragma: no cover
|
||||
redis = None # type: ignore
|
||||
|
||||
|
||||
_redis_client: Any = None
|
||||
|
||||
|
||||
def get_redis_client():
|
||||
"""
|
||||
获取进程内 Redis 客户端单例。
|
||||
核心逻辑:读取 REDIS_URL;未配置或连接失败时返回 None。
|
||||
@returns redis.Redis 或 None
|
||||
"""
|
||||
global _redis_client
|
||||
if redis is None:
|
||||
return None
|
||||
if _redis_client is not None:
|
||||
return _redis_client
|
||||
|
||||
from flask import current_app
|
||||
|
||||
redis_url = None
|
||||
if current_app:
|
||||
redis_url = current_app.config.get('REDIS_URL')
|
||||
if not redis_url:
|
||||
return None
|
||||
|
||||
try:
|
||||
client = redis.from_url(redis_url, decode_responses=True)
|
||||
client.ping()
|
||||
_redis_client = client
|
||||
return _redis_client
|
||||
except Exception:
|
||||
_redis_client = None
|
||||
return None
|
||||
|
||||
|
||||
def reset_redis_client() -> None:
|
||||
"""测试或配置变更时重置单例。"""
|
||||
global _redis_client
|
||||
_redis_client = None
|
||||
@@ -0,0 +1,69 @@
|
||||
"""extend quick_questions for FAQ cache
|
||||
|
||||
Revision ID: a1b2c3d4e5f7
|
||||
Revises: f2a3b4c5d6e8
|
||||
Create Date: 2026-06-16 10:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "a1b2c3d4e5f7"
|
||||
down_revision = "f2a3b4c5d6e8"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
columns = {c["name"] for c in insp.get_columns("quick_questions")}
|
||||
|
||||
if "answer" not in columns:
|
||||
op.add_column("quick_questions", sa.Column("answer", sa.Text(), nullable=True))
|
||||
if "aliases" not in columns:
|
||||
op.add_column("quick_questions", sa.Column("aliases", sa.JSON(), nullable=True))
|
||||
if "cache_enabled" not in columns:
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("cache_enabled", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
)
|
||||
if "is_enabled" not in columns:
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
|
||||
)
|
||||
if "hit_count" not in columns:
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("hit_count", sa.Integer(), nullable=False, server_default="0"),
|
||||
)
|
||||
if "retriever_resources" not in columns:
|
||||
op.add_column("quick_questions", sa.Column("retriever_resources", sa.JSON(), nullable=True))
|
||||
if "expires_at" not in columns:
|
||||
op.add_column("quick_questions", sa.Column("expires_at", sa.DateTime(), nullable=True))
|
||||
if "updated_at" not in columns:
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
columns = {c["name"] for c in insp.get_columns("quick_questions")}
|
||||
|
||||
for col in (
|
||||
"updated_at",
|
||||
"expires_at",
|
||||
"retriever_resources",
|
||||
"hit_count",
|
||||
"is_enabled",
|
||||
"cache_enabled",
|
||||
"aliases",
|
||||
"answer",
|
||||
):
|
||||
if col in columns:
|
||||
op.drop_column("quick_questions", col)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""add faq_hot_candidates table
|
||||
|
||||
Revision ID: b2c3d4e5f6a8
|
||||
Revises: a1b2c3d4e5f7
|
||||
Create Date: 2026-06-16 14:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "b2c3d4e5f6a8"
|
||||
down_revision = "a1b2c3d4e5f7"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "faq_hot_candidates" in insp.get_table_names():
|
||||
return
|
||||
|
||||
op.create_table(
|
||||
"faq_hot_candidates",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("agent_id", sa.Integer(), nullable=False),
|
||||
sa.Column("q_norm", sa.String(length=255), nullable=False),
|
||||
sa.Column("canonical_query", sa.Text(), nullable=False),
|
||||
sa.Column("answer", sa.Text(), nullable=False),
|
||||
sa.Column("source_chat_log_id", sa.Integer(), nullable=True),
|
||||
sa.Column("ask_count_7d", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("user_count_7d", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("avg_tokens", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("avg_latency_ms", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("answer_dominance", sa.Float(), nullable=False, server_default="0"),
|
||||
sa.Column("sample_queries", sa.JSON(), nullable=True),
|
||||
sa.Column("retriever_resources", sa.JSON(), nullable=True),
|
||||
sa.Column("last_asked_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("status", sa.String(length=20), nullable=False, server_default="candidate"),
|
||||
sa.Column("promoted_quick_question_id", sa.Integer(), nullable=True),
|
||||
sa.Column("deny_until", sa.DateTime(), nullable=True),
|
||||
sa.Column("expires_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.ForeignKeyConstraint(["agent_id"], ["agents.id"]),
|
||||
sa.ForeignKeyConstraint(["source_chat_log_id"], ["chat_logs.id"]),
|
||||
sa.ForeignKeyConstraint(["promoted_quick_question_id"], ["quick_questions.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("agent_id", "q_norm", name="uq_faq_hot_candidates_agent_qnorm"),
|
||||
)
|
||||
op.create_index("ix_faq_hot_candidates_agent_id", "faq_hot_candidates", ["agent_id"])
|
||||
op.create_index("ix_faq_hot_candidates_status_expires", "faq_hot_candidates", ["status", "expires_at"])
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "faq_hot_candidates" not in insp.get_table_names():
|
||||
return
|
||||
op.drop_index("ix_faq_hot_candidates_status_expires", table_name="faq_hot_candidates")
|
||||
op.drop_index("ix_faq_hot_candidates_agent_id", table_name="faq_hot_candidates")
|
||||
op.drop_table("faq_hot_candidates")
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
backend/tests/test_hot_faq_aggregator.py
|
||||
|
||||
测试热点 FAQ 离线聚合的核心规则:问句归一化、答案聚类与代表答案选取。
|
||||
"""
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator, _LogRow
|
||||
|
||||
|
||||
def test_normalize_faq_query_strips_punctuation_and_space():
|
||||
"""归一化后「公司几点上班?」与「公司 几点上班」应相同。"""
|
||||
assert normalize_faq_query('公司几点上班?') == normalize_faq_query('公司 几点上班')
|
||||
|
||||
|
||||
def test_answer_cluster_merges_similar_answers():
|
||||
"""相似度≥阈值的答案应归入同一簇。"""
|
||||
rows = [
|
||||
_LogRow(1, 1, 1, 'q', '工作日8:30到17:30', 100, 10, datetime.utcnow()),
|
||||
_LogRow(2, 2, 1, 'q', '工作日 8:30 到 17:30', 100, 10, datetime.utcnow()),
|
||||
]
|
||||
clusters = HotFaqAggregator._cluster_answers(rows)
|
||||
assert len(clusters) == 1
|
||||
assert len(clusters[0]['rows']) == 2
|
||||
|
||||
|
||||
def test_pick_representative_prefers_good_feedback():
|
||||
"""有好评时优先选高分记录。"""
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(1, 1, 1, 'q', 'answer A', 100, 10, now, feedback_score=3),
|
||||
_LogRow(2, 2, 1, 'q', 'answer B', 100, 10, now, feedback_score=5),
|
||||
]
|
||||
picked = HotFaqAggregator._pick_representative_answer(rows)
|
||||
assert picked is not None
|
||||
assert picked.chat_log_id == 2
|
||||
assert picked.answer == 'answer B'
|
||||
|
||||
|
||||
def test_build_candidate_rejects_divergent_answers(app, monkeypatch):
|
||||
"""答案分歧过大时应跳过该热点组。"""
|
||||
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
|
||||
with app.app_context():
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
|
||||
for i in range(6)
|
||||
]
|
||||
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
|
||||
assert candidate is None
|
||||
assert reason and reason.startswith('answer_divergence')
|
||||
@@ -0,0 +1,415 @@
|
||||
# FAQ 缓存与热点发现 — 运维手册
|
||||
|
||||
> 面向运维与管理员:部署、定时聚合、审核晋升、监控与排障。
|
||||
> 功能背景见上文设计;代码入口见 `backend/app/services/faq_cache.py`、`hot_faq_aggregator.py`、`hot_faq_candidate_store.py`。
|
||||
|
||||
---
|
||||
|
||||
## 1. 能力边界(运维必读)
|
||||
|
||||
| 能力 | 存储 | 在线生效 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| L1 人工 FAQ | `quick_questions` | ✅ | 用户提问时 `FaqCacheService.try_match` 命中即 SSE 直答 |
|
||||
| L2 热点候选 | `faq_hot_candidates` | ❌ | 仅管理端展示;**必须晋升**后才进入 L1 |
|
||||
| 离线聚合 | ChatLog → PG | — | `flask faq-aggregate-hot` 或管理端「刷新聚合」 |
|
||||
|
||||
**不需要 Redis**(热点功能已全走 PostgreSQL)。知识库 worker 若单独使用 Redis,与 FAQ 无关。
|
||||
|
||||
---
|
||||
|
||||
## 2. 首次部署 Checklist
|
||||
|
||||
### 2.1 数据库迁移
|
||||
|
||||
```bash
|
||||
# 本地
|
||||
cd backend
|
||||
flask --app manage.py db upgrade
|
||||
|
||||
# Docker 生产(与 deploy_compose.sh 一致)
|
||||
docker compose exec -T hxops-backend flask --app manage.py db upgrade
|
||||
```
|
||||
|
||||
涉及迁移(按顺序):
|
||||
|
||||
- `a1b2c3d4e5f7` — 扩展 `quick_questions`(answer、aliases、cache_enabled 等)
|
||||
- `b2c3d4e5f6a8` — 新建 `faq_hot_candidates`
|
||||
|
||||
### 2.2 环境变量
|
||||
|
||||
在 `.env.shared`(各环境继承)确认以下项已配置:
|
||||
|
||||
```env
|
||||
FAQ_HOT_ENABLED=true
|
||||
FAQ_HOT_WINDOW_DAYS=7
|
||||
FAQ_HOT_MIN_COUNT=5
|
||||
FAQ_HOT_MIN_USERS=3
|
||||
FAQ_HOT_MIN_AVG_TOKENS=0
|
||||
FAQ_HOT_MAX_QUERY_LEN=200
|
||||
FAQ_HOT_MIN_QUERY_LEN=4
|
||||
FAQ_HOT_MIN_ANSWER_LEN=8
|
||||
FAQ_HOT_TTL_SECONDS=604800
|
||||
FAQ_HOT_ANSWER_SIMILARITY=0.95
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6
|
||||
FAQ_HOT_GOOD_SCORE=4
|
||||
FAQ_HOT_BAD_SCORE=2
|
||||
```
|
||||
|
||||
修改 `.env.shared` 或环境覆盖项后 **必须重启后端**。
|
||||
|
||||
### 2.3 冒烟验证
|
||||
|
||||
```bash
|
||||
# 1) 预览聚合(不写库)
|
||||
flask --app manage.py faq-aggregate-hot --dry-run
|
||||
|
||||
# 2) 正式写入候选表
|
||||
flask --app manage.py faq-aggregate-hot
|
||||
|
||||
# 3) 管理端:系统管理 → 常用问题 → 「热点发现」Tab → 刷新聚合
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 定时任务(推荐)
|
||||
|
||||
热点发现 **无内置 cron**;过期 `candidate` 的物理清理也发生在聚合开始时。建议至少 **每天 1 次** 跑聚合。
|
||||
|
||||
### 3.1 Docker 环境(宿主机 crontab)
|
||||
|
||||
```cron
|
||||
# 每天 02:30 聚合热点 FAQ(stdout 追加到日志)
|
||||
30 2 * * * cd /path/to/hxops && docker compose exec -T hxops-backend flask --app manage.py faq-aggregate-hot >> /var/log/hxops/faq-aggregate-hot.log 2>&1
|
||||
```
|
||||
|
||||
### 3.2 裸机 / systemd timer
|
||||
|
||||
```bash
|
||||
# 手动试跑
|
||||
cd /path/to/hxops/backend
|
||||
source venv/bin/activate
|
||||
flask --app manage.py faq-aggregate-hot
|
||||
```
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/hxops-faq-aggregate.service
|
||||
[Unit]
|
||||
Description=HXOPS FAQ hot aggregation
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=/path/to/hxops/backend
|
||||
EnvironmentFile=/path/to/hxops/.env.prod
|
||||
ExecStart=/path/to/hxops/backend/venv/bin/flask --app manage.py faq-aggregate-hot
|
||||
```
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/hxops-faq-aggregate.timer
|
||||
[Unit]
|
||||
Description=Daily FAQ hot aggregation
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 02:30:00
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
```
|
||||
|
||||
```bash
|
||||
sudo systemctl enable --now hxops-faq-aggregate.timer
|
||||
```
|
||||
|
||||
### 3.3 按 Agent 拆分(可选)
|
||||
|
||||
大租户可分开跑,减轻单次扫描量:
|
||||
|
||||
```bash
|
||||
flask --app manage.py faq-aggregate-hot --agent-id 12
|
||||
```
|
||||
|
||||
### 3.4 与「排程管理」的关系
|
||||
|
||||
管理端 **排程(Schedule)** 用于 Dify Workflow / 文件检核等,**不能**直接触发 `faq-aggregate-hot`。FAQ 聚合请用 crontab / systemd / CI 定时 Job。
|
||||
|
||||
---
|
||||
|
||||
## 4. 管理员 SOP:热点审核与晋升
|
||||
|
||||
### 4.1 日常流程
|
||||
|
||||
```
|
||||
定时聚合(或手动刷新)
|
||||
→ 管理端「热点发现」查看候选列表
|
||||
→ 核对 canonical_query / 推荐答案 / 7 日提问人数
|
||||
→ 晋升 或 忽略
|
||||
```
|
||||
|
||||
路径:**管理后台 → 常用问题 → 热点发现**。
|
||||
|
||||
### 4.2 晋升前检查清单
|
||||
|
||||
| 检查项 | 说明 |
|
||||
| --- | --- |
|
||||
| 问句是否稳定 | 同一业务含义是否已有多种写法;晋升后会把 `sample_queries` 写入 `aliases` |
|
||||
| 答案是否准确 | 来自 Dify 历史;答案分歧过大时聚合器已过滤(dominance < 60% 不会入池) |
|
||||
| 是否已有 FAQ | 同 Agent 下人工 FAQ 已覆盖则聚合会跳过;晋升前可在「常用问题」Tab 搜索 |
|
||||
| 是否有时效 | 政策类 FAQ 可在晋升后编辑 `expires_at` |
|
||||
| Agent 是否正确 | 候选按 `agent_id` 隔离,勿跨应用晋升 |
|
||||
|
||||
### 4.3 晋升操作
|
||||
|
||||
- **UI**:热点发现 → 选择行 → 「晋升为 FAQ」
|
||||
- **API**:`POST /api/admin/faq-candidates/promote`
|
||||
|
||||
```json
|
||||
{
|
||||
"agent_id": 1,
|
||||
"q_norm": "上班时间",
|
||||
"title": "上班时间(可选,默认用 canonical_query)"
|
||||
}
|
||||
```
|
||||
|
||||
效果(单事务):
|
||||
|
||||
1. 插入 `quick_questions`(`user_id=NULL`,`cache_enabled=true`,`is_enabled=true`)
|
||||
2. 候选行 `status=promoted`,写入 `promoted_quick_question_id`
|
||||
|
||||
### 4.4 忽略操作
|
||||
|
||||
- **UI**:「忽略」
|
||||
- **API**:`POST /api/admin/faq-candidates/dismiss`
|
||||
|
||||
效果:`status=dismissed`,`deny_until = now + FAQ_HOT_TTL_SECONDS`(默认 7 天内不再入池)。
|
||||
|
||||
### 4.5 人工 FAQ 维护(L1)
|
||||
|
||||
路径:**常用问题** Tab(非热点发现)。
|
||||
|
||||
| 操作 | 说明 |
|
||||
| --- | --- |
|
||||
| 新建/编辑 | 填写 question、answer、aliases;开启「启用缓存」 |
|
||||
| 关闭缓存 | `cache_enabled=false` 后不再在线命中,但不删 ChatLog |
|
||||
| 设置过期 | `expires_at` 到期后 `try_match` 自动跳过 |
|
||||
| 查看命中 | 列表字段 `hit_count` |
|
||||
|
||||
---
|
||||
|
||||
## 5. 与 ChatLog / 审计的关系
|
||||
|
||||
### 5.1 数据来源
|
||||
|
||||
离线聚合 **只读** `chat_logs`(近 N 天、`tokens_used > 0`),并关联 `feedbacks` 选最佳答案。
|
||||
|
||||
### 5.2 写入标记(识别 FAQ 命中)
|
||||
|
||||
| 场景 | ChatLog 特征 |
|
||||
| --- | --- |
|
||||
| L1 FAQ 直答 | `tokens_used=0`,`payload.source=faq_cache`,`payload.faq_id=<QuickQuestion.id>` |
|
||||
| Dify 正常对话 | `tokens_used>0`,无 `faq_cache` source |
|
||||
| 不参与聚合 | `payload.source` 为 `faq_cache` / `hot_faq_cache` |
|
||||
|
||||
晋升后用户再问同类问题 → 新 ChatLog 为 `faq_cache` → **不会再被算进热点**(避免循环)。
|
||||
|
||||
### 5.3 报表与估算
|
||||
|
||||
| 位置 | 内容 |
|
||||
| --- | --- |
|
||||
| 热点发现页 stats | `total_candidates`、`total_ask_count_7d`、`estimated_tokens_if_cached`(估算值) |
|
||||
| `/api/admin/reports/usage` | ChatLog 总量按用户/Agent 分布(**不区分** faq_cache) |
|
||||
| `quick_questions.hit_count` | L1 实际命中次数 |
|
||||
|
||||
**Token 节省估算 SQL(管理参考)**:
|
||||
|
||||
```sql
|
||||
-- 近 7 日:若全部走 FAQ,理论节省 token(与热点页 estimated 逻辑类似)
|
||||
SELECT SUM(cl.tokens_used) AS dify_tokens_7d
|
||||
FROM chat_logs cl
|
||||
WHERE cl.created_at >= NOW() - INTERVAL '7 days'
|
||||
AND cl.tokens_used > 0
|
||||
AND (cl.payload IS NULL OR cl.payload->>'source' NOT IN ('faq_cache', 'hot_faq_cache'));
|
||||
|
||||
-- L1 实际命中次数(累计)
|
||||
SELECT id, title, question, hit_count, cache_enabled
|
||||
FROM quick_questions
|
||||
WHERE user_id IS NULL AND cache_enabled = true
|
||||
ORDER BY hit_count DESC;
|
||||
```
|
||||
|
||||
### 5.4 数据保留
|
||||
|
||||
删除 `chat_logs` **不会**自动删除已晋升的 FAQ,但会影响后续热点再发现。批量删日志前请评估热点与审计需求(管理端 `/api/admin/database/chat_logs/batch-delete`)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 配置调优指南
|
||||
|
||||
| 变量 | 默认 | 调大效果 | 调小效果 |
|
||||
| --- | --- | --- | --- |
|
||||
| `FAQ_HOT_ENABLED` | true | — | false 时 CLI/刷新立即返回 disabled |
|
||||
| `FAQ_HOT_WINDOW_DAYS` | 7 | 看更长历史 | 更偏近期热点 |
|
||||
| `FAQ_HOT_MIN_COUNT` | 5 | 更少出现候选 | 更多低频次问题入池 |
|
||||
| `FAQ_HOT_MIN_USERS` | 3 | 允许更少用户重复问 | 防刷、更严格 |
|
||||
| `FAQ_HOT_ANSWER_DOMINANCE` | 0.6 | 允许答案分歧更大 | 只保留高度一致答案 |
|
||||
| `FAQ_HOT_TTL_SECONDS` | 604800 | 候选/忽略黑名单更长 | 更快过期清理 |
|
||||
| `FAQ_HOT_MIN_AVG_TOKENS` | 0 | 过滤低 token 对话 | 0=不限制 |
|
||||
|
||||
**典型场景**:
|
||||
|
||||
- 问答量少:可将 `MIN_COUNT` 降为 3、`MIN_USERS` 降为 2(需业务认可)。
|
||||
- 答案版本多:提高 `ANSWER_DOMINANCE` 到 0.7–0.8。
|
||||
- 政策类短期活动:晋升 FAQ 时设 `expires_at`,不必改热点 TTL。
|
||||
|
||||
---
|
||||
|
||||
## 7. 运维监控
|
||||
|
||||
### 7.1 CLI 输出解读
|
||||
|
||||
```
|
||||
scanned=1234 groups=89 promoted=12 skipped=77 dry_run=False
|
||||
```
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `scanned` | 通过基础过滤的 ChatLog 条数 |
|
||||
| `groups` | (agent_id, q_norm) 分组数 |
|
||||
| `promoted` | 本次产出候选数(dry-run 也统计,但不写库) |
|
||||
| `skipped` | 未入池原因(deny、已有 FAQ、频次不足、答案分歧等) |
|
||||
|
||||
### 7.2 PostgreSQL 巡检 SQL
|
||||
|
||||
```sql
|
||||
-- 当前有效候选数
|
||||
SELECT COUNT(*) FROM faq_hot_candidates
|
||||
WHERE status = 'candidate'
|
||||
AND (expires_at IS NULL OR expires_at >= NOW());
|
||||
|
||||
-- 各状态分布
|
||||
SELECT status, COUNT(*) FROM faq_hot_candidates GROUP BY status;
|
||||
|
||||
-- 即将过期(24h 内)
|
||||
SELECT agent_id, canonical_query, expires_at
|
||||
FROM faq_hot_candidates
|
||||
WHERE status = 'candidate'
|
||||
AND expires_at IS NOT NULL
|
||||
AND expires_at < NOW() + INTERVAL '24 hours'
|
||||
ORDER BY expires_at;
|
||||
|
||||
-- 已晋升但未删候选(正常,应保留审计)
|
||||
SELECT id, agent_id, q_norm, promoted_quick_question_id, updated_at
|
||||
FROM faq_hot_candidates
|
||||
WHERE status = 'promoted'
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 20;
|
||||
```
|
||||
|
||||
### 7.3 日志关键字
|
||||
|
||||
后端日志搜索:
|
||||
|
||||
- `[hot-faq-store]` — 候选表读写/清理失败
|
||||
- `[faq-cache]` — L1 命中计数更新失败(不影响直答)
|
||||
|
||||
### 7.4 健康标准(建议)
|
||||
|
||||
| 指标 | 建议 |
|
||||
| --- | --- |
|
||||
| 聚合任务 | 每日成功至少 1 次;连续 2 天 `promoted=0` 且业务活跃 → 查阈值或 ChatLog |
|
||||
| 候选池 | `candidate` 总量稳定;长期堆积未审核 → 提醒管理员处理 |
|
||||
| L1 命中 | 晋升后 1–2 周内 `hit_count` 应 > 0(否则检查 aliases / 问句写法) |
|
||||
|
||||
---
|
||||
|
||||
## 8. 过期与清理机制
|
||||
|
||||
| status | expires_at 到期后 |
|
||||
| --- | --- |
|
||||
| `candidate` | 列表不可见;**下次非 dry-run 聚合** 时 `purge_expired()` 物理 DELETE |
|
||||
| `promoted` | **不删除**(保留晋升历史) |
|
||||
| `dismissed` | **不删除**;靠 `deny_until` 控制是否再入池 |
|
||||
|
||||
长期不跑聚合 → 过期 candidate 行会留在表中(只是 API/UI 查不到)。这也是必须配置 cron 的原因之一。
|
||||
|
||||
手动清理过期 candidate(慎用,一般不必):
|
||||
|
||||
```sql
|
||||
DELETE FROM faq_hot_candidates
|
||||
WHERE status = 'candidate'
|
||||
AND expires_at IS NOT NULL
|
||||
AND expires_at < NOW();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 故障排查
|
||||
|
||||
| 现象 | 可能原因 | 处理 |
|
||||
| --- | --- | --- |
|
||||
| CLI 提示 `FAQ_HOT_ENABLED is false` | 环境变量关闭 | 设 `FAQ_HOT_ENABLED=true` 并重启 |
|
||||
| 热点列表始终为空 | 未跑聚合 / 阈值过高 / 窗口内无 Dify 对话 | `--dry-run` 看 skipped reason;调低 MIN_COUNT |
|
||||
| 晋升后仍走 Dify | 问句与 FAQ 归一化不一致 | 检查 aliases;用户问法是否在 aliases 中 |
|
||||
| 同问题重复出现在热点 | 未晋升也未忽略;或 deny 已过期 | 晋升或 dismiss |
|
||||
| 聚合很慢 | ChatLog 量大 | 按 `--agent-id` 拆分;错峰 cron |
|
||||
| `purge_expired` 报错 | DB 连接/迁移未执行 | 查日志;确认 `faq_hot_candidates` 表存在 |
|
||||
| 管理端刷新 403 | 非管理员 | 需 admin 角色 |
|
||||
|
||||
**调试单条 skip 原因**:调用 refresh API 时传 `"dry_run": true`,响应 `skipped` 数组含 `reason` 字段。
|
||||
|
||||
---
|
||||
|
||||
## 10. 关闭与回滚
|
||||
|
||||
### 10.1 仅关闭热点发现(保留 L1)
|
||||
|
||||
```env
|
||||
FAQ_HOT_ENABLED=false
|
||||
```
|
||||
|
||||
已晋升 FAQ 不受影响;候选表数据保留但不再更新。
|
||||
|
||||
### 10.2 关闭某条 L1 缓存
|
||||
|
||||
管理端编辑该 FAQ → 关闭「启用缓存」,或设 `expires_at` 为过去时间。
|
||||
|
||||
### 10.3 数据库回滚(极端情况)
|
||||
|
||||
回滚迁移会 drop `faq_hot_candidates` 并回退 `quick_questions` 新列 — **生产慎用**,需 DBA 评估。优先用业务开关而非 down migration。
|
||||
|
||||
---
|
||||
|
||||
## 11. API 速查(管理员 Token)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/admin/faq-candidates?agent_id=` | 列表 + stats + rules |
|
||||
| POST | `/api/admin/faq-candidates/refresh` | `{ "agent_id?", "dry_run?" }` |
|
||||
| POST | `/api/admin/faq-candidates/promote` | `{ "agent_id", "q_norm", "title?" }` |
|
||||
| POST | `/api/admin/faq-candidates/dismiss` | `{ "agent_id", "q_norm" }` |
|
||||
| GET/POST/PUT/DELETE | `/api/admin/quick-questions` | L1 人工 FAQ CRUD |
|
||||
|
||||
---
|
||||
|
||||
## 12. 相关代码与文档
|
||||
|
||||
| 模块 | 路径 |
|
||||
| --- | --- |
|
||||
| L1 在线匹配 | `backend/app/services/faq_cache.py` |
|
||||
| 离线聚合 | `backend/app/services/hot_faq_aggregator.py` |
|
||||
| PG 候选存储 | `backend/app/services/hot_faq_candidate_store.py` |
|
||||
| CLI | `backend/app/cli/faq_commands.py` |
|
||||
| 管理 API | `backend/app/api/admin.py` |
|
||||
| 对话入口 | `backend/app/api/chat.py`(Dify 前 `try_match`) |
|
||||
| 管理 UI | `frontend/src/features/admin/modules/questions/` |
|
||||
| 环境变量 | `.env.shared` → `FAQ_HOT_*` |
|
||||
|
||||
---
|
||||
|
||||
## 13. 建议运维节奏(参考)
|
||||
|
||||
| 频率 | 动作 | 负责人 |
|
||||
| --- | --- | --- |
|
||||
| 每日 | cron 跑 `faq-aggregate-hot` | 运维 |
|
||||
| 每周 | 管理员审核热点发现,晋升高质量 FAQ | 业务管理员 |
|
||||
| 每月 | 查看 `hit_count`、清理过期/错误 FAQ | 业务管理员 |
|
||||
| 变更前 | 改 `FAQ_HOT_*` 先在 test 环境 `--dry-run` 对比 | 运维 + 开发 |
|
||||
@@ -204,3 +204,40 @@ export const saveAdminQuickQuestion = (url: string, method: string, payload: Rec
|
||||
requestJson(url, { method, ...jsonAuth(), body: JSON.stringify(payload) });
|
||||
export const deleteAdminQuickQuestion = (id: number) =>
|
||||
requestJson(`/api/admin/quick-questions/${id}`, { method: 'DELETE', ...auth() });
|
||||
|
||||
// Hot FAQ candidates (offline aggregation)
|
||||
export const listAdminFaqCandidates = (agentId?: number) => {
|
||||
const query = agentId ? `?agent_id=${agentId}` : '';
|
||||
return requestJson<any>(`/api/admin/faq-candidates${query}`, auth());
|
||||
};
|
||||
|
||||
export const refreshAdminFaqCandidates = (payload?: { agent_id?: number; dry_run?: boolean }) =>
|
||||
requestJson<{
|
||||
promoted_count?: number;
|
||||
scanned_logs?: number;
|
||||
enabled?: boolean;
|
||||
dry_run?: boolean;
|
||||
}>('/api/admin/faq-candidates/refresh', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
|
||||
export const promoteAdminFaqCandidate = (payload: {
|
||||
agent_id: number;
|
||||
q_norm: string;
|
||||
title?: string;
|
||||
sort_order?: number;
|
||||
}) =>
|
||||
requestJson('/api/admin/faq-candidates/promote', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const dismissAdminFaqCandidate = (payload: { agent_id: number; q_norm: string }) =>
|
||||
requestJson('/api/admin/faq-candidates/dismiss', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
@@ -1,174 +1,455 @@
|
||||
/**
|
||||
|
||||
* features/admin/modules/questions/QuestionsPage.vue
|
||||
* 常用问题管理独立页面。路由:/admin/questions
|
||||
|
||||
* 常用问题管理:Tab「常用问题」+「热点发现」(离线聚合候选)。
|
||||
|
||||
* 依赖:useQuestionsAdmin、HotFaqCandidatesPanel、QuestionFormModal。
|
||||
|
||||
* 逻辑:路由 /admin/questions;热点候选晋升后写入 QuickQuestion 并由 Phase 1 FAQ 在线命中。
|
||||
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Edit, Trash2 } from 'lucide-vue-next';
|
||||
|
||||
import { Edit, Plus, Trash2, Zap } from 'lucide-vue-next';
|
||||
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
|
||||
import HotFaqCandidatesPanel from './components/HotFaqCandidatesPanel.vue';
|
||||
|
||||
import QuestionFormModal from './components/QuestionFormModal.vue';
|
||||
|
||||
import { useQuestionsAdmin } from './composables/useQuestionsAdmin';
|
||||
|
||||
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const activeTab = ref<'manual' | 'hot'>('manual');
|
||||
|
||||
|
||||
|
||||
const {
|
||||
questions,
|
||||
|
||||
filteredQuestions,
|
||||
|
||||
agents,
|
||||
|
||||
form,
|
||||
isEditing,
|
||||
|
||||
isLoading,
|
||||
|
||||
isSaving,
|
||||
|
||||
showFormModal,
|
||||
|
||||
showDeleteConfirmDialog,
|
||||
|
||||
deleteConfirmMessage,
|
||||
|
||||
filterAgentId,
|
||||
|
||||
filterCacheOnly,
|
||||
|
||||
searchKeyword,
|
||||
|
||||
loadAll,
|
||||
resetForm,
|
||||
editQuestion,
|
||||
|
||||
openCreateModal,
|
||||
|
||||
openEditModal,
|
||||
|
||||
closeFormModal,
|
||||
|
||||
saveQuestion,
|
||||
|
||||
deleteQuestion,
|
||||
|
||||
closeDeleteConfirm,
|
||||
|
||||
confirmDelete,
|
||||
|
||||
truncateQuestionPreview,
|
||||
|
||||
truncateAnswerPreview,
|
||||
|
||||
} = useQuestionsAdmin();
|
||||
|
||||
|
||||
|
||||
onMounted(() => {
|
||||
|
||||
void loadAll();
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<template>
|
||||
<section class="section-gap animate-fade-in-up">
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-20">
|
||||
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||
|
||||
<section class="admin-table-section animate-fade-in-up">
|
||||
|
||||
<div class="admin-table-header admin-table-header--stacked mb-4">
|
||||
|
||||
<div>
|
||||
|
||||
<h2 class="section-title">{{ t('admin.question.title') }}</h2>
|
||||
|
||||
<p class="section-desc mt-1">{{ t('admin.question.subtitle') }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
<button
|
||||
|
||||
v-if="activeTab === 'manual'"
|
||||
|
||||
type="button"
|
||||
|
||||
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
|
||||
|
||||
@click="openCreateModal"
|
||||
|
||||
>
|
||||
|
||||
<Plus class="w-4 h-4" />
|
||||
|
||||
<span>{{ t('admin.question.add') }}</span>
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="mb-6 flex gap-1 border-b border-default">
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
|
||||
|
||||
:class="activeTab === 'manual' ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
|
||||
|
||||
@click="activeTab = 'manual'"
|
||||
|
||||
>
|
||||
|
||||
{{ t('admin.question.tabs.manual') }}
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
|
||||
|
||||
:class="activeTab === 'hot' ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
|
||||
|
||||
@click="activeTab = 'hot'"
|
||||
|
||||
>
|
||||
|
||||
{{ t('admin.question.tabs.hotDiscovery') }}
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<HotFaqCandidatesPanel v-if="activeTab === 'hot'" />
|
||||
|
||||
|
||||
|
||||
<template v-else>
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 class="section-title">{{ t('admin.question.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.question.subtitle') }}</p>
|
||||
</div>
|
||||
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-20">
|
||||
|
||||
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
|
||||
<h3 class="font-bold text-primary mb-4">
|
||||
{{ isEditing ? t('admin.question.edit') : t('admin.question.add') }}
|
||||
</h3>
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.title') }}</label>
|
||||
<input
|
||||
v-model="form.title"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.question.fields.titlePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.targetAgent') }}</label>
|
||||
<select v-model="form.agent_id" class="input-field text-sm">
|
||||
<option :value="undefined" disabled>{{ t('admin.perm.batchModal.selectAgents') }}</option>
|
||||
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
|
||||
{{ agent.name }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>
|
||||
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.content') }}</label>
|
||||
<textarea
|
||||
v-model="form.question"
|
||||
rows="4"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.question.fields.contentPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 pt-2">
|
||||
<button
|
||||
v-if="isEditing"
|
||||
type="button"
|
||||
class="btn-ghost btn-sm"
|
||||
@click="resetForm"
|
||||
>
|
||||
{{ t('admin.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary btn-sm disabled:opacity-50"
|
||||
:disabled="isSaving"
|
||||
@click="saveQuestion"
|
||||
>
|
||||
{{ isSaving ? t('admin.save') + '...' : (isEditing ? t('admin.update') : t('admin.add')) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
|
||||
<div class="mb-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
|
||||
<div class="flex flex-1 flex-wrap items-center gap-3">
|
||||
|
||||
<input
|
||||
|
||||
v-model="searchKeyword"
|
||||
|
||||
type="search"
|
||||
|
||||
class="input-field text-sm w-full max-w-xs"
|
||||
|
||||
:placeholder="t('admin.question.filters.search')"
|
||||
|
||||
/>
|
||||
|
||||
<select v-model="filterAgentId" class="input-field text-sm w-full max-w-[200px]">
|
||||
|
||||
<option value="">{{ t('admin.question.filters.allAgents') }}</option>
|
||||
|
||||
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
|
||||
|
||||
{{ agent.name }}
|
||||
|
||||
</option>
|
||||
|
||||
</select>
|
||||
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary whitespace-nowrap">
|
||||
|
||||
<input v-model="filterCacheOnly" type="checkbox" class="accent-brand-600" />
|
||||
|
||||
<span>{{ t('admin.question.filters.cacheOnly') }}</span>
|
||||
|
||||
</label>
|
||||
|
||||
</div>
|
||||
|
||||
<p class="text-xs text-muted">
|
||||
|
||||
{{ t('admin.question.filters.resultCount', { count: filteredQuestions.length }) }}
|
||||
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="lg:col-span-2 admin-table-section">
|
||||
<div v-if="questions.length === 0" class="p-8 text-center text-muted">
|
||||
{{ t('admin.question.noData') }}
|
||||
</div>
|
||||
<table v-else class="admin-table">
|
||||
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
|
||||
<table class="admin-table">
|
||||
|
||||
<thead>
|
||||
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
||||
{{ t('admin.question.headers.title') }}
|
||||
</th>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
||||
{{ t('admin.question.headers.agent') }}
|
||||
</th>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
||||
{{ t('admin.question.headers.order') }}
|
||||
</th>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right">
|
||||
{{ t('admin.question.headers.actions') }}
|
||||
</th>
|
||||
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.title') }}</th>
|
||||
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.agent') }}</th>
|
||||
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.content') }}</th>
|
||||
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.question.headers.answer') }}</th>
|
||||
|
||||
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.question.headers.cache') }}</th>
|
||||
|
||||
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.question.headers.hits') }}</th>
|
||||
|
||||
<th class="px-6 py-4 text-left text-xs w-16">{{ t('admin.question.headers.order') }}</th>
|
||||
|
||||
<th class="px-6 py-4 text-right text-xs w-28">{{ t('admin.question.headers.actions') }}</th>
|
||||
|
||||
</tr>
|
||||
|
||||
</thead>
|
||||
<tbody class="divide-y divide-subtle">
|
||||
<tr v-for="q in questions" :key="q.id">
|
||||
<td class="px-6 py-4">
|
||||
<div class="font-medium text-primary text-sm">{{ q.title }}</div>
|
||||
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ q.question }}</div>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<span
|
||||
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100"
|
||||
>
|
||||
{{ q.agent_name || 'Unknown' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted">{{ q.sort_order }}</td>
|
||||
<td class="px-6 py-4 text-right flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
|
||||
@click="editQuestion(q)"
|
||||
>
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
@click="deleteQuestion(q.id)"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
</td>
|
||||
|
||||
<tbody>
|
||||
|
||||
<tr v-if="filteredQuestions.length === 0">
|
||||
|
||||
<td colspan="8" class="px-6 admin-table-empty">{{ t('admin.question.noData') }}</td>
|
||||
|
||||
</tr>
|
||||
|
||||
<tr v-for="q in filteredQuestions" :key="q.id" class="group">
|
||||
|
||||
<td class="px-6 py-4">
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
|
||||
<div class="font-medium text-primary text-sm">{{ q.title }}</div>
|
||||
|
||||
<span
|
||||
|
||||
v-if="!q.is_enabled"
|
||||
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium bg-surface-soft text-muted border border-default"
|
||||
|
||||
>
|
||||
|
||||
{{ t('admin.question.badges.disabled') }}
|
||||
|
||||
</span>
|
||||
|
||||
</div>
|
||||
|
||||
</td>
|
||||
|
||||
<td class="px-6 py-4">
|
||||
|
||||
<span
|
||||
|
||||
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100"
|
||||
|
||||
>
|
||||
|
||||
{{ q.agent_name || 'Unknown' }}
|
||||
|
||||
</span>
|
||||
|
||||
</td>
|
||||
|
||||
<td class="px-6 py-4">
|
||||
|
||||
<p class="text-sm text-secondary truncate max-w-[180px]" :title="q.question">
|
||||
|
||||
{{ truncateQuestionPreview(q.question) }}
|
||||
|
||||
</p>
|
||||
|
||||
</td>
|
||||
|
||||
<td class="px-6 py-4">
|
||||
|
||||
<p
|
||||
|
||||
v-if="q.cache_enabled && q.answer"
|
||||
|
||||
class="text-sm text-secondary truncate max-w-[160px]"
|
||||
|
||||
:title="q.answer"
|
||||
|
||||
>
|
||||
|
||||
{{ truncateAnswerPreview(q.answer) }}
|
||||
|
||||
</p>
|
||||
|
||||
<span v-else class="text-xs text-muted">—</span>
|
||||
|
||||
</td>
|
||||
|
||||
<td class="px-6 py-4">
|
||||
|
||||
<span
|
||||
|
||||
v-if="q.cache_enabled"
|
||||
|
||||
class="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium bg-emerald-50 text-emerald-700 border border-emerald-100"
|
||||
|
||||
>
|
||||
|
||||
<Zap class="w-3 h-3" />
|
||||
|
||||
{{ t('admin.question.badges.cacheOn') }}
|
||||
|
||||
</span>
|
||||
|
||||
<span
|
||||
|
||||
v-else
|
||||
|
||||
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-muted border border-default"
|
||||
|
||||
>
|
||||
|
||||
{{ t('admin.question.badges.cacheOff') }}
|
||||
|
||||
</span>
|
||||
|
||||
</td>
|
||||
|
||||
<td class="px-6 py-4 text-sm text-muted tabular-nums">{{ q.hit_count || 0 }}</td>
|
||||
|
||||
<td class="px-6 py-4 text-sm text-muted tabular-nums">{{ q.sort_order }}</td>
|
||||
|
||||
<td class="px-6 py-4">
|
||||
|
||||
<div class="flex justify-end gap-1">
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
|
||||
|
||||
@click="openEditModal(q)"
|
||||
|
||||
>
|
||||
|
||||
<Edit class="w-4 h-4" />
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
|
||||
@click="deleteQuestion(q.id)"
|
||||
|
||||
>
|
||||
|
||||
<Trash2 class="w-4 h-4" />
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</td>
|
||||
|
||||
</tr>
|
||||
|
||||
</tbody>
|
||||
|
||||
</table>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
|
||||
<QuestionFormModal
|
||||
|
||||
:visible="showFormModal"
|
||||
|
||||
:form="form"
|
||||
|
||||
:agents="agents"
|
||||
|
||||
:is-saving="isSaving"
|
||||
|
||||
@close="closeFormModal"
|
||||
|
||||
@save="saveQuestion"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<DeleteConfirmDialog
|
||||
|
||||
v-model="showDeleteConfirmDialog"
|
||||
|
||||
:message="deleteConfirmMessage"
|
||||
|
||||
@cancel="closeDeleteConfirm"
|
||||
|
||||
@confirm="confirmDelete"
|
||||
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showDeleteConfirmDialog"
|
||||
:message="deleteConfirmMessage"
|
||||
@cancel="closeDeleteConfirm"
|
||||
@confirm="confirmDelete"
|
||||
/>
|
||||
</section>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* features/admin/modules/questions/components/HotFaqCandidatesPanel.vue
|
||||
* 热点 FAQ 候选列表:离线聚合结果展示、刷新、晋升、忽略。
|
||||
* 依赖:useHotFaqCandidates。
|
||||
* 逻辑:QuestionsPage「热点发现」Tab 挂载本组件。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowUpCircle, Info, RefreshCw, XCircle } from 'lucide-vue-next';
|
||||
import { useHotFaqCandidates } from '../composables/useHotFaqCandidates';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const {
|
||||
filteredItems,
|
||||
agents,
|
||||
stats,
|
||||
rules,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
filterAgentId,
|
||||
searchKeyword,
|
||||
showRules,
|
||||
loadAll,
|
||||
loadCandidates,
|
||||
refreshCandidates,
|
||||
promoteCandidate,
|
||||
dismissCandidate,
|
||||
truncatePreview,
|
||||
} = useHotFaqCandidates();
|
||||
|
||||
onMounted(() => {
|
||||
void loadAll();
|
||||
});
|
||||
|
||||
const onAgentFilterChange = () => {
|
||||
void loadCandidates();
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4 text-sm text-secondary">
|
||||
<p>{{ t('admin.hotFaq.intro') }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-2 inline-flex items-center gap-1 text-xs font-medium text-brand-600 hover:underline"
|
||||
@click="showRules = !showRules"
|
||||
>
|
||||
<Info class="w-3.5 h-3.5" />
|
||||
{{ showRules ? t('admin.hotFaq.hideRules') : t('admin.hotFaq.showRules') }}
|
||||
</button>
|
||||
<div v-if="showRules && rules" class="mt-3 space-y-2 text-xs text-muted border-t border-subtle pt-3">
|
||||
<div>
|
||||
<span class="font-semibold text-secondary">{{ t('admin.hotFaq.rules.selection') }}</span>
|
||||
{{ (rules as any).selection?.description }}
|
||||
</div>
|
||||
<ul class="list-disc pl-5 space-y-0.5">
|
||||
<li>{{ t('admin.hotFaq.rules.windowDays', { n: (rules as any).selection?.window_days }) }}</li>
|
||||
<li>{{ t('admin.hotFaq.rules.minCount', { n: (rules as any).selection?.min_count }) }}</li>
|
||||
<li>{{ t('admin.hotFaq.rules.minUsers', { n: (rules as any).selection?.min_users }) }}</li>
|
||||
</ul>
|
||||
<div class="pt-1">
|
||||
<span class="font-semibold text-secondary">{{ t('admin.hotFaq.rules.answer') }}</span>
|
||||
{{ (rules as any).answer?.description }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div class="flex flex-1 flex-wrap items-center gap-3">
|
||||
<input
|
||||
v-model="searchKeyword"
|
||||
type="search"
|
||||
class="input-field text-sm w-full max-w-xs"
|
||||
:placeholder="t('admin.hotFaq.filters.search')"
|
||||
/>
|
||||
<select
|
||||
v-model="filterAgentId"
|
||||
class="input-field text-sm w-full max-w-[200px]"
|
||||
@change="onAgentFilterChange"
|
||||
>
|
||||
<option value="">{{ t('admin.hotFaq.filters.allAgents') }}</option>
|
||||
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
|
||||
{{ agent.name }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs text-muted">
|
||||
{{ t('admin.hotFaq.stats.summary', {
|
||||
count: stats.total_candidates ?? 0,
|
||||
asks: stats.total_ask_count_7d ?? 0,
|
||||
}) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-ghost text-sm"
|
||||
:disabled="isRefreshing"
|
||||
@click="refreshCandidates(true)"
|
||||
>
|
||||
{{ t('admin.hotFaq.actions.dryRun') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 text-sm font-medium disabled:opacity-70"
|
||||
:disabled="isRefreshing"
|
||||
@click="refreshCandidates(false)"
|
||||
>
|
||||
<RefreshCw class="w-4 h-4" :class="{ 'animate-spin': isRefreshing }" />
|
||||
{{ t('admin.hotFaq.actions.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-16">
|
||||
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||
</div>
|
||||
|
||||
<div v-else class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.hotFaq.headers.query') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.hotFaq.headers.agent') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.hotFaq.headers.answer') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.hotFaq.headers.asks') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.hotFaq.headers.users') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs w-24">{{ t('admin.hotFaq.headers.tokens') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs w-20">{{ t('admin.hotFaq.headers.dominance') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs w-36">{{ t('admin.hotFaq.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="filteredItems.length === 0">
|
||||
<td colspan="8" class="px-6 admin-table-empty">{{ t('admin.hotFaq.noData') }}</td>
|
||||
</tr>
|
||||
<tr v-for="row in filteredItems" :key="`${row.agent_id}-${row.q_norm}`">
|
||||
<td class="px-6 py-4">
|
||||
<div class="font-medium text-primary text-sm">{{ row.canonical_query }}</div>
|
||||
<p v-if="row.sample_queries?.length" class="text-[11px] text-muted mt-1 truncate max-w-[200px]">
|
||||
{{ row.sample_queries.slice(0, 2).join(' / ') }}
|
||||
</p>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<span class="inline-flex px-2.5 py-0.5 rounded-full text-xs bg-blue-50 text-blue-700 border border-blue-100">
|
||||
{{ row.agent_name || row.agent_id }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<p class="text-sm text-secondary truncate max-w-[180px]" :title="row.answer">
|
||||
{{ truncatePreview(row.answer) }}
|
||||
</p>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm tabular-nums text-muted">{{ row.ask_count_7d }}</td>
|
||||
<td class="px-6 py-4 text-sm tabular-nums text-muted">{{ row.user_count_7d }}</td>
|
||||
<td class="px-6 py-4 text-sm tabular-nums text-muted">{{ row.avg_tokens }}</td>
|
||||
<td class="px-6 py-4 text-sm tabular-nums text-muted">
|
||||
{{ row.answer_dominance != null ? `${Math.round(row.answer_dominance * 100)}%` : '—' }}
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<div class="flex justify-end gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium text-emerald-700 bg-emerald-50 hover:bg-emerald-100 rounded-lg border border-emerald-100"
|
||||
:title="t('admin.hotFaq.actions.promote')"
|
||||
@click="promoteCandidate(row)"
|
||||
>
|
||||
<ArrowUpCircle class="w-3.5 h-3.5" />
|
||||
{{ t('admin.hotFaq.actions.promote') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg"
|
||||
:title="t('admin.hotFaq.actions.dismiss')"
|
||||
@click="dismissCandidate(row)"
|
||||
>
|
||||
<XCircle class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* features/admin/modules/questions/components/QuestionFormModal.vue
|
||||
* 常用问题 / FAQ 缓存创建与编辑居中弹窗。
|
||||
* 依赖:QuestionFormState、admin 通用 modal 样式。
|
||||
* 逻辑:QuestionsPage 打开本组件;提交时 emit save,由 composable 调 API。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
|
||||
import type { QuestionFormState } from '@/features/admin/types/question.types';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
form: QuestionFormState;
|
||||
agents: AdminAgentOption[];
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
save: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** 启用 FAQ 缓存时标准答案为必填。 */
|
||||
const answerRequired = computed(() => props.form.cache_enabled);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
||||
<div class="admin-modal-panel max-w-3xl max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">
|
||||
{{ form.id ? t('admin.question.edit') : t('admin.question.add') }}
|
||||
</h3>
|
||||
<p class="text-sm text-muted mt-1">{{ t('admin.question.formHint') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="px-5 sm:px-8 py-5 space-y-6 overflow-y-auto">
|
||||
<section class="space-y-4">
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
|
||||
{{ t('admin.question.sections.basic') }}
|
||||
</h4>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-1.5 md:col-span-2">
|
||||
<label class="label-field">{{ t('admin.question.fields.title') }}</label>
|
||||
<input
|
||||
v-model="form.title"
|
||||
type="text"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.question.fields.titlePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.targetAgent') }}</label>
|
||||
<select v-model="form.agent_id" class="input-field text-sm">
|
||||
<option :value="undefined" disabled>{{ t('admin.perm.batchModal.selectAgents') }}</option>
|
||||
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
|
||||
{{ agent.name }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>
|
||||
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="md:col-span-2 flex flex-wrap gap-6">
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.is_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<span>{{ t('admin.question.fields.isEnabled') }}</span>
|
||||
</label>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.cache_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<span>{{ t('admin.question.fields.cacheEnabled') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-4">
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
|
||||
{{ t('admin.question.sections.matching') }}
|
||||
</h4>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.content') }}</label>
|
||||
<textarea
|
||||
v-model="form.question"
|
||||
rows="3"
|
||||
class="input-field text-sm resize-y min-h-[88px]"
|
||||
:placeholder="t('admin.question.fields.contentPlaceholder')"
|
||||
/>
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.contentHelp') }}</p>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.aliases') }}</label>
|
||||
<textarea
|
||||
v-model="form.aliasesText"
|
||||
rows="3"
|
||||
class="input-field text-sm resize-y min-h-[88px] font-mono"
|
||||
:placeholder="t('admin.question.fields.aliasesPlaceholder')"
|
||||
/>
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.aliasesHelp') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-4 rounded-2xl border border-default bg-surface-soft/60 p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
|
||||
{{ t('admin.question.sections.cache') }}
|
||||
</h4>
|
||||
<p class="text-xs text-muted mt-1">{{ t('admin.question.fields.cacheHelp') }}</p>
|
||||
</div>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
|
||||
:class="form.cache_enabled ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-surface-soft text-muted border border-default'"
|
||||
>
|
||||
{{ form.cache_enabled ? t('admin.question.badges.cacheOn') : t('admin.question.badges.cacheOff') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">
|
||||
{{ t('admin.question.fields.answer') }}
|
||||
<span v-if="answerRequired" class="text-red-500">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
v-model="form.answer"
|
||||
rows="6"
|
||||
class="input-field text-sm resize-y min-h-[140px]"
|
||||
:placeholder="t('admin.question.fields.answerPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.expiresAt') }}</label>
|
||||
<input v-model="form.expires_at" type="datetime-local" class="input-field text-sm" />
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.expiresAtHelp') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
|
||||
{{
|
||||
isSaving
|
||||
? t('admin.save') + '...'
|
||||
: form.id
|
||||
? t('admin.update')
|
||||
: t('admin.add')
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* features/admin/modules/questions/composables/useHotFaqCandidates.ts
|
||||
* 热点 FAQ 候选(离线聚合)管理:列表、刷新、晋升、忽略。
|
||||
* 依赖:admin.api、useMessage。
|
||||
* 逻辑:QuestionsPage「热点发现」Tab 调用本 composable。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
dismissAdminFaqCandidate,
|
||||
listAdminAgents,
|
||||
listAdminFaqCandidates,
|
||||
promoteAdminFaqCandidate,
|
||||
refreshAdminFaqCandidates,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
|
||||
|
||||
export interface HotFaqCandidateRow {
|
||||
agent_id: number;
|
||||
agent_name?: string;
|
||||
q_norm: string;
|
||||
canonical_query: string;
|
||||
answer: string;
|
||||
ask_count_7d: number;
|
||||
user_count_7d: number;
|
||||
avg_tokens: number;
|
||||
avg_latency_ms?: number;
|
||||
answer_dominance?: number;
|
||||
last_asked_at?: string;
|
||||
sample_queries?: string[];
|
||||
}
|
||||
|
||||
const PREVIEW_MAX = 56;
|
||||
|
||||
export function useHotFaqCandidates() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const items = ref<HotFaqCandidateRow[]>([]);
|
||||
const agents = ref<AdminAgentOption[]>([]);
|
||||
const stats = ref<Record<string, unknown>>({});
|
||||
const rules = ref<Record<string, unknown> | null>(null);
|
||||
const isLoading = ref(true);
|
||||
const isRefreshing = ref(false);
|
||||
const filterAgentId = ref<number | ''>('');
|
||||
const searchKeyword = ref('');
|
||||
const showRules = ref(false);
|
||||
|
||||
const filteredItems = computed(() => {
|
||||
const keyword = searchKeyword.value.trim().toLowerCase();
|
||||
return items.value.filter((row) => {
|
||||
if (filterAgentId.value !== '' && row.agent_id !== filterAgentId.value) return false;
|
||||
if (!keyword) return true;
|
||||
const haystack = [
|
||||
row.canonical_query,
|
||||
row.answer,
|
||||
...(row.sample_queries || []),
|
||||
]
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
return haystack.includes(keyword);
|
||||
});
|
||||
});
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
agents.value = await listAdminAgents();
|
||||
} catch {
|
||||
agents.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadCandidates = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const agentId = filterAgentId.value === '' ? undefined : Number(filterAgentId.value);
|
||||
const data = await listAdminFaqCandidates(agentId);
|
||||
items.value = Array.isArray(data.items) ? data.items : [];
|
||||
stats.value = data.stats || {};
|
||||
rules.value = data.rules || null;
|
||||
} catch (e) {
|
||||
console.error('Failed to load FAQ candidates', e);
|
||||
items.value = [];
|
||||
stats.value = {};
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadAll = async (): Promise<void> => {
|
||||
await Promise.all([loadAgents(), loadCandidates()]);
|
||||
};
|
||||
|
||||
/**
|
||||
* 触发离线聚合刷新。
|
||||
* @param dryRun - 为 true 时仅预览统计
|
||||
*/
|
||||
const refreshCandidates = async (dryRun = false): Promise<void> => {
|
||||
isRefreshing.value = true;
|
||||
try {
|
||||
const agentId = filterAgentId.value === '' ? undefined : Number(filterAgentId.value);
|
||||
const result = await refreshAdminFaqCandidates({
|
||||
agent_id: agentId,
|
||||
dry_run: dryRun,
|
||||
});
|
||||
if (dryRun) {
|
||||
msg.info(
|
||||
t('admin.hotFaq.msg.dryRunDone', {
|
||||
promoted: result.promoted_count ?? 0,
|
||||
scanned: result.scanned_logs ?? 0,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
msg.success(t('admin.hotFaq.msg.refreshed'));
|
||||
await loadCandidates();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
} finally {
|
||||
isRefreshing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 晋升候选为全局 FAQ(QuickQuestion + cache_enabled)。
|
||||
*/
|
||||
const promoteCandidate = async (row: HotFaqCandidateRow): Promise<void> => {
|
||||
try {
|
||||
await promoteAdminFaqCandidate({
|
||||
agent_id: row.agent_id,
|
||||
q_norm: row.q_norm,
|
||||
title: row.canonical_query.slice(0, 100),
|
||||
});
|
||||
msg.success(t('admin.hotFaq.msg.promoted'));
|
||||
await loadCandidates();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 忽略候选并加入 deny 黑名单。
|
||||
*/
|
||||
const dismissCandidate = async (row: HotFaqCandidateRow): Promise<void> => {
|
||||
try {
|
||||
await dismissAdminFaqCandidate({ agent_id: row.agent_id, q_norm: row.q_norm });
|
||||
msg.success(t('admin.hotFaq.msg.dismissed'));
|
||||
await loadCandidates();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const truncatePreview = (text: string): string => {
|
||||
const value = String(text || '').trim();
|
||||
if (value.length <= PREVIEW_MAX) return value;
|
||||
return `${value.slice(0, PREVIEW_MAX)}…`;
|
||||
};
|
||||
|
||||
return {
|
||||
items,
|
||||
filteredItems,
|
||||
agents,
|
||||
stats,
|
||||
rules,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
filterAgentId,
|
||||
searchKeyword,
|
||||
showRules,
|
||||
loadAll,
|
||||
loadCandidates,
|
||||
refreshCandidates,
|
||||
promoteCandidate,
|
||||
dismissCandidate,
|
||||
truncatePreview,
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* features/admin/modules/questions/composables/useQuestionsAdmin.ts
|
||||
* 常用问题管理:列表、创建、编辑、删除。
|
||||
* 常用问题 / FAQ 缓存管理:列表筛选、创建/编辑弹窗、删除。
|
||||
* 依赖:admin.api、question.types、useMessage。
|
||||
* 逻辑:QuestionsPage 调用本 composable 驱动表格与居中表单弹窗。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
deleteAdminQuickQuestion,
|
||||
@@ -13,11 +15,16 @@ import {
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
|
||||
import {
|
||||
aliasesToText,
|
||||
buildQuestionPayload,
|
||||
createEmptyQuestionForm,
|
||||
type AdminQuickQuestionRow,
|
||||
type QuestionFormState,
|
||||
} from '@/features/admin/types/question.types';
|
||||
|
||||
const QUESTION_PREVIEW_MAX_LEN = 60;
|
||||
const ANSWER_PREVIEW_MAX_LEN = 48;
|
||||
|
||||
export function useQuestionsAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
@@ -25,14 +32,31 @@ export function useQuestionsAdmin() {
|
||||
const questions = ref<AdminQuickQuestionRow[]>([]);
|
||||
const agents = ref<AdminAgentOption[]>([]);
|
||||
const form = ref<QuestionFormState>(createEmptyQuestionForm());
|
||||
const isEditing = ref(false);
|
||||
const isLoading = ref(true);
|
||||
const isSaving = ref(false);
|
||||
const showFormModal = ref(false);
|
||||
const filterAgentId = ref<number | ''>('');
|
||||
const filterCacheOnly = ref(false);
|
||||
const searchKeyword = ref('');
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
const filteredQuestions = computed(() => {
|
||||
const keyword = searchKeyword.value.trim().toLowerCase();
|
||||
return questions.value.filter((q) => {
|
||||
if (filterAgentId.value !== '' && q.agent_id !== filterAgentId.value) return false;
|
||||
if (filterCacheOnly.value && !q.cache_enabled) return false;
|
||||
if (!keyword) return true;
|
||||
const haystack = [q.title, q.question, q.answer, ...(q.aliases || [])]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
return haystack.includes(keyword);
|
||||
});
|
||||
});
|
||||
|
||||
const loadQuestions = async (): Promise<void> => {
|
||||
try {
|
||||
questions.value = await listAdminQuickQuestions();
|
||||
@@ -77,38 +101,88 @@ export function useQuestionsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置表单为空白状态。
|
||||
*/
|
||||
const resetForm = (): void => {
|
||||
form.value = createEmptyQuestionForm();
|
||||
isEditing.value = false;
|
||||
};
|
||||
|
||||
const editQuestion = (q: AdminQuickQuestionRow): void => {
|
||||
/** 打开「添加问题」弹窗并重置表单。 */
|
||||
const openCreateModal = (): void => {
|
||||
resetForm();
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开「编辑问题」弹窗并回填选中行数据。
|
||||
* @param q - 表格行数据
|
||||
*/
|
||||
const openEditModal = (q: AdminQuickQuestionRow): void => {
|
||||
form.value = {
|
||||
id: q.id,
|
||||
title: q.title,
|
||||
question: q.question,
|
||||
answer: q.answer || '',
|
||||
aliasesText: aliasesToText(q.aliases),
|
||||
cache_enabled: q.cache_enabled,
|
||||
is_enabled: q.is_enabled,
|
||||
agent_id: q.agent_id,
|
||||
sort_order: q.sort_order,
|
||||
expires_at: q.expires_at ? q.expires_at.slice(0, 16) : '',
|
||||
};
|
||||
isEditing.value = true;
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
/** 关闭表单弹窗并重置表单。 */
|
||||
const closeFormModal = (): void => {
|
||||
showFormModal.value = false;
|
||||
resetForm();
|
||||
};
|
||||
|
||||
/**
|
||||
* 截断文本用于表格预览列。
|
||||
* @param text - 完整文本
|
||||
* @param maxLen - 最大长度
|
||||
* @returns 截断后的预览文本
|
||||
*/
|
||||
const truncatePreview = (text: string, maxLen: number): string => {
|
||||
const value = String(text || '').trim();
|
||||
if (value.length <= maxLen) return value;
|
||||
return `${value.slice(0, maxLen)}…`;
|
||||
};
|
||||
|
||||
const truncateQuestionPreview = (text: string): string =>
|
||||
truncatePreview(text, QUESTION_PREVIEW_MAX_LEN);
|
||||
|
||||
const truncateAnswerPreview = (text: string): string =>
|
||||
truncatePreview(text, ANSWER_PREVIEW_MAX_LEN);
|
||||
|
||||
/**
|
||||
* 校验并提交创建/更新请求,成功后刷新列表并关闭弹窗。
|
||||
*/
|
||||
const saveQuestion = async (): Promise<void> => {
|
||||
if (!form.value.title || !form.value.question || !form.value.agent_id) {
|
||||
msg.warning(t('admin.question.msg.fillAll'));
|
||||
return;
|
||||
}
|
||||
if (form.value.cache_enabled && !form.value.answer.trim()) {
|
||||
msg.warning(t('admin.question.msg.answerRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
const isEditing = Boolean(form.value.id);
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const url = isEditing.value
|
||||
const url = isEditing
|
||||
? `/api/admin/quick-questions/${form.value.id}`
|
||||
: '/api/admin/quick-questions';
|
||||
const method = isEditing.value ? 'PUT' : 'POST';
|
||||
const method = isEditing ? 'PUT' : 'POST';
|
||||
|
||||
await saveAdminQuickQuestion(url, method, form.value as Record<string, unknown>);
|
||||
await saveAdminQuickQuestion(url, method, buildQuestionPayload(form.value));
|
||||
await loadQuestions();
|
||||
resetForm();
|
||||
closeFormModal();
|
||||
msg.success(t('admin.question.msg.saved'));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
@@ -131,19 +205,26 @@ export function useQuestionsAdmin() {
|
||||
|
||||
return {
|
||||
questions,
|
||||
filteredQuestions,
|
||||
agents,
|
||||
form,
|
||||
isEditing,
|
||||
isLoading,
|
||||
isSaving,
|
||||
showFormModal,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
filterAgentId,
|
||||
filterCacheOnly,
|
||||
searchKeyword,
|
||||
loadAll,
|
||||
resetForm,
|
||||
editQuestion,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
saveQuestion,
|
||||
deleteQuestion,
|
||||
closeDeleteConfirm,
|
||||
confirmDelete,
|
||||
truncateQuestionPreview,
|
||||
truncateAnswerPreview,
|
||||
};
|
||||
}
|
||||
@@ -1,28 +1,76 @@
|
||||
/**
|
||||
* features/admin/types/question.types.ts
|
||||
* 常用问题管理类型。
|
||||
* 常用问题 / FAQ 缓存管理类型。
|
||||
*/
|
||||
|
||||
export interface AdminQuickQuestionRow {
|
||||
id: number;
|
||||
title: string;
|
||||
question: string;
|
||||
answer?: string | null;
|
||||
aliases?: string[];
|
||||
cache_enabled: boolean;
|
||||
is_enabled: boolean;
|
||||
hit_count: number;
|
||||
agent_id: number;
|
||||
agent_name?: string;
|
||||
sort_order: number;
|
||||
expires_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface QuestionFormState {
|
||||
id?: number;
|
||||
title: string;
|
||||
question: string;
|
||||
answer: string;
|
||||
aliasesText: string;
|
||||
cache_enabled: boolean;
|
||||
is_enabled: boolean;
|
||||
agent_id?: number;
|
||||
sort_order: number;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
export const createEmptyQuestionForm = (): QuestionFormState => ({
|
||||
title: '',
|
||||
question: '',
|
||||
answer: '',
|
||||
aliasesText: '',
|
||||
cache_enabled: false,
|
||||
is_enabled: true,
|
||||
agent_id: undefined,
|
||||
sort_order: 0,
|
||||
expires_at: '',
|
||||
});
|
||||
|
||||
/** 将别名数组转为表单 textarea 文本(每行一条)。 */
|
||||
export const aliasesToText = (aliases?: string[] | null): string =>
|
||||
Array.isArray(aliases) ? aliases.filter(Boolean).join('\n') : '';
|
||||
|
||||
/** 将 textarea 文本解析为别名字符串数组。 */
|
||||
export const textToAliases = (text: string): string[] => {
|
||||
const seen = new Set<string>();
|
||||
const result: string[] = [];
|
||||
for (const line of String(text || '').split('\n')) {
|
||||
const value = line.trim();
|
||||
if (value && !seen.has(value)) {
|
||||
seen.add(value);
|
||||
result.push(value);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/** 构建提交 API 的 payload。 */
|
||||
export const buildQuestionPayload = (form: QuestionFormState): Record<string, unknown> => ({
|
||||
title: form.title,
|
||||
question: form.question,
|
||||
answer: form.answer || null,
|
||||
aliases: textToAliases(form.aliasesText),
|
||||
cache_enabled: form.cache_enabled,
|
||||
is_enabled: form.is_enabled,
|
||||
agent_id: form.agent_id,
|
||||
sort_order: form.sort_order,
|
||||
expires_at: form.expires_at || null,
|
||||
});
|
||||
@@ -197,27 +197,115 @@
|
||||
},
|
||||
"question": {
|
||||
"title": "Common Questions",
|
||||
"subtitle": "Manage global quick questions for all users",
|
||||
"subtitle": "Manage global quick questions with optional FAQ cache to skip Dify on match",
|
||||
"formHint": "When FAQ cache is enabled, matched questions return the preset answer without consuming tokens.",
|
||||
"edit": "Edit Question",
|
||||
"add": "Add New Question",
|
||||
"noData": "No common questions configured.",
|
||||
"headers": {
|
||||
"title": "Title",
|
||||
"agent": "Agent",
|
||||
"content": "Match Query",
|
||||
"answer": "Preset Answer",
|
||||
"cache": "FAQ Cache",
|
||||
"hits": "Hits",
|
||||
"order": "Order",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"sections": {
|
||||
"basic": "Basic Info",
|
||||
"matching": "Query Matching",
|
||||
"cache": "FAQ Cached Answer"
|
||||
},
|
||||
"fields": {
|
||||
"title": "Title",
|
||||
"titlePlaceholder": "e.g. Write Report",
|
||||
"titlePlaceholder": "e.g. Working Hours",
|
||||
"targetAgent": "Target Agent",
|
||||
"sortOrder": "Sort Order",
|
||||
"content": "Question Content",
|
||||
"contentPlaceholder": "Enter the prompt content..."
|
||||
"content": "Canonical Query",
|
||||
"contentPlaceholder": "e.g. What time does work start?",
|
||||
"contentHelp": "Users sending this normalized query will hit the cache.",
|
||||
"aliases": "Alternative Phrasings",
|
||||
"aliasesPlaceholder": "One per line, e.g.:\nWhat time do we start?\nOffice hours?",
|
||||
"aliasesHelp": "Optional. Each line is an alternative phrasing that maps to the same answer.",
|
||||
"answer": "Preset Answer",
|
||||
"answerPlaceholder": "Full answer returned directly on cache hit…",
|
||||
"cacheEnabled": "Enable FAQ cache (skip Dify)",
|
||||
"isEnabled": "Show on workspace",
|
||||
"cacheHelp": "When enabled, matched queries return the preset answer below without calling Dify.",
|
||||
"expiresAt": "Expires At",
|
||||
"expiresAtHelp": "Optional. After expiry the entry will not match. Leave empty for no expiry."
|
||||
},
|
||||
"filters": {
|
||||
"search": "Search title, query or answer…",
|
||||
"allAgents": "All agents",
|
||||
"cacheOnly": "Cache enabled only",
|
||||
"resultCount": "{count} item(s)"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "Cached",
|
||||
"cacheOff": "Not cached",
|
||||
"disabled": "Disabled"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} alias(es)"
|
||||
},
|
||||
"confirmDelete": "Are you sure you want to delete this question?",
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"confirmDelete": "Are you sure?",
|
||||
"msg": {
|
||||
"fillAll": "Please fill all fields"
|
||||
"fillAll": "Please fill in title, query and target agent",
|
||||
"answerRequired": "Preset answer is required when FAQ cache is enabled",
|
||||
"saved": "Saved successfully"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "Common Questions",
|
||||
"hotDiscovery": "Hot Discovery"
|
||||
}
|
||||
},
|
||||
"hotFaq": {
|
||||
"intro": "Discovers frequent queries from recent ChatLogs and stores candidates in PostgreSQL. Promote to FAQ after review.",
|
||||
"showRules": "View aggregation rules",
|
||||
"hideRules": "Hide rules",
|
||||
"redisUnavailable": "Redis is not configured or unavailable.",
|
||||
"noData": "No hot candidates yet. Click Refresh to aggregate from ChatLog.",
|
||||
"headers": {
|
||||
"query": "Hot Query",
|
||||
"agent": "Agent",
|
||||
"answer": "Suggested Answer",
|
||||
"asks": "7d Asks",
|
||||
"users": "Users",
|
||||
"tokens": "Avg Tokens",
|
||||
"dominance": "Consensus",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"filters": {
|
||||
"search": "Search query or answer…",
|
||||
"allAgents": "All agents"
|
||||
},
|
||||
"stats": {
|
||||
"summary": "{count} candidate(s), {asks} asks in 7 days"
|
||||
},
|
||||
"rules": {
|
||||
"selection": "Selection:",
|
||||
"answer": "Best answer:",
|
||||
"windowDays": "Last {n} days, tokens_used>0 (Dify only)",
|
||||
"minCount": "At least {n} asks per normalized query",
|
||||
"minUsers": "At least {n} distinct users"
|
||||
},
|
||||
"actions": {
|
||||
"refresh": "Refresh",
|
||||
"dryRun": "Preview",
|
||||
"promote": "Promote to FAQ",
|
||||
"dismiss": "Dismiss"
|
||||
},
|
||||
"msg": {
|
||||
"refreshed": "Hot FAQ aggregation completed",
|
||||
"dryRunDone": "Preview done: {promoted} group(s) would promote ({scanned} logs scanned)",
|
||||
"promoted": "Promoted to common question FAQ",
|
||||
"dismissed": "Hot candidate dismissed"
|
||||
}
|
||||
},
|
||||
"announcement": {
|
||||
|
||||
@@ -197,27 +197,115 @@
|
||||
},
|
||||
"question": {
|
||||
"title": "คำถามทั่วไป",
|
||||
"subtitle": "จัดการคำถามด่วนทั่วโลก",
|
||||
"subtitle": "จัดการคำถามด่วนทั่วโลก พร้อม FAQ cache เพื่อข้าม Dify เมื่อจับคู่ได้",
|
||||
"formHint": "เมื่อเปิด FAQ cache คำถามที่จับคู่ได้จะส่งคำตอบที่กำหนดไว้โดยไม่ใช้ Token",
|
||||
"edit": "แก้ไขคำถาม",
|
||||
"add": "เพิ่มคำถามใหม่",
|
||||
"noData": "ไม่มีคำถามทั่วไป",
|
||||
"headers": {
|
||||
"title": "หัวข้อ",
|
||||
"agent": "ตัวแทน",
|
||||
"content": "คำถามจับคู่",
|
||||
"answer": "คำตอบมาตรฐาน",
|
||||
"cache": "FAQ Cache",
|
||||
"hits": "จำนวนครั้ง",
|
||||
"order": "ลำดับ",
|
||||
"actions": "การกระทำ"
|
||||
},
|
||||
"sections": {
|
||||
"basic": "ข้อมูลพื้นฐาน",
|
||||
"matching": "การจับคู่คำถาม",
|
||||
"cache": "คำตอบ FAQ Cache"
|
||||
},
|
||||
"fields": {
|
||||
"title": "หัวข้อ",
|
||||
"titlePlaceholder": "เช่น เขียนรายงาน",
|
||||
"titlePlaceholder": "เช่น เวลาทำงาน",
|
||||
"targetAgent": "ตัวแทนเป้าหมาย",
|
||||
"sortOrder": "ลำดับการเรียง",
|
||||
"content": "เนื้อหาคำถาม",
|
||||
"contentPlaceholder": "กรอกเนื้อหาคำถาม..."
|
||||
"content": "คำถามมาตรฐาน",
|
||||
"contentPlaceholder": "เช่น บริษัทเปิดกี่โมง?",
|
||||
"contentHelp": "ผู้ใช้ที่ส่งคำถามที่ตรงกัน (หลัง normalize) จะโดน cache",
|
||||
"aliases": "คำถามทางเลือก",
|
||||
"aliasesPlaceholder": "หนึ่งบรรทัดต่อหนึ่งคำถาม เช่น:\nกี่โมงเข้างาน\nเวลาเข้างานคืออะไร",
|
||||
"aliasesHelp": "ไม่บังคับ แต่ละบรรทัดเป็นคำถามทางเลือกที่ได้คำตอบเดียวกัน",
|
||||
"answer": "คำตอบมาตรฐาน",
|
||||
"answerPlaceholder": "คำตอบเต็มที่ส่งกลับเมื่อ cache hit…",
|
||||
"cacheEnabled": "เปิด FAQ cache (ข้าม Dify)",
|
||||
"isEnabled": "แสดงในหน้า workspace",
|
||||
"cacheHelp": "เมื่อเปิดใช้ คำถามที่จับคู่ได้จะส่งคำตอบด้านล่างโดยไม่เรียก Dify",
|
||||
"expiresAt": "หมดอายุเมื่อ",
|
||||
"expiresAtHelp": "ไม่บังคับ หลังหมดอายุจะไม่จับคู่ ปล่อยว่างหากไม่มีวันหมดอายุ"
|
||||
},
|
||||
"filters": {
|
||||
"search": "ค้นหาหัวข้อ คำถาม หรือคำตอบ…",
|
||||
"allAgents": "ตัวแทนทั้งหมด",
|
||||
"cacheOnly": "เฉพาะที่เปิด cache",
|
||||
"resultCount": "{count} รายการ"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "Cache แล้ว",
|
||||
"cacheOff": "ยังไม่ cache",
|
||||
"disabled": "ปิดใช้งาน"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} คำถามทางเลือก"
|
||||
},
|
||||
"confirmDelete": "คุณแน่ใจหรือไม่ว่าต้องการลบคำถามนี้?",
|
||||
"actions": {
|
||||
"edit": "แก้ไข",
|
||||
"delete": "ลบ"
|
||||
},
|
||||
"confirmDelete": "คุณแน่ใจหรือไม่?",
|
||||
"msg": {
|
||||
"fillAll": "กรุณากรอกข้อมูลให้ครบถ้วน"
|
||||
"fillAll": "กรุณากรอกหัวข้อ คำถาม และตัวแทนเป้าหมาย",
|
||||
"answerRequired": "ต้องกรอกคำตอบมาตรฐานเมื่อเปิด FAQ cache",
|
||||
"saved": "บันทึกสำเร็จ"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "คำถามทั่วไป",
|
||||
"hotDiscovery": "ค้นพบ Hotspot"
|
||||
}
|
||||
},
|
||||
"hotFaq": {
|
||||
"intro": "ค้นหาคำถามที่พบบ่อยจาก ChatLog 7 วันล่าสุด เก็บในตาราง PostgreSQL แล้วส่งเสริมเป็น FAQ",
|
||||
"showRules": "ดูกฎการรวม",
|
||||
"hideRules": "ซ่อนกฎ",
|
||||
"redisUnavailable": "Redis ไม่พร้อมใช้งาน",
|
||||
"noData": "ยังไม่มี candidate กด Refresh เพื่อรวมจาก ChatLog",
|
||||
"headers": {
|
||||
"query": "คำถาม Hot",
|
||||
"agent": "ตัวแทน",
|
||||
"answer": "คำตอบแนะนำ",
|
||||
"asks": "ถาม 7 วัน",
|
||||
"users": "ผู้ใช้",
|
||||
"tokens": "Token เฉลี่ย",
|
||||
"dominance": "ความสอดคล้อง",
|
||||
"actions": "การกระทำ"
|
||||
},
|
||||
"filters": {
|
||||
"search": "ค้นหาคำถามหรือคำตอบ…",
|
||||
"allAgents": "ตัวแทนทั้งหมด"
|
||||
},
|
||||
"stats": {
|
||||
"summary": "{count} candidate, ถามรวม {asks} ครั้งใน 7 วัน"
|
||||
},
|
||||
"rules": {
|
||||
"selection": "การเลือก hotspot:",
|
||||
"answer": "คำตอบที่ดีที่สุด:",
|
||||
"windowDays": "สถิติ {n} วันล่าสุด tokens_used>0",
|
||||
"minCount": "ถามอย่างน้อย {n} ครั้งต่อคำถาม normalize",
|
||||
"minUsers": "ผู้ใช้ต่างกันอย่างน้อย {n} คน"
|
||||
},
|
||||
"actions": {
|
||||
"refresh": "รีเฟรช",
|
||||
"dryRun": "ดูตัวอย่าง",
|
||||
"promote": "ส่งเสริงเป็น FAQ",
|
||||
"dismiss": "ละเว้น"
|
||||
},
|
||||
"msg": {
|
||||
"refreshed": "รวม hotspot FAQ เสร็จแล้ว",
|
||||
"dryRunDone": "ดูตัวอย่างเสร็จ: promote {promoted} กลุ่ม (สแกน {scanned} log)",
|
||||
"promoted": "ส่งเสริงเป็นคำถามทั่วไป FAQ แล้ว",
|
||||
"dismissed": "ละเว้น hotspot แล้ว"
|
||||
}
|
||||
},
|
||||
"announcement": {
|
||||
|
||||
@@ -198,27 +198,115 @@
|
||||
},
|
||||
"question": {
|
||||
"title": "常用问题",
|
||||
"subtitle": "管理全局常用问题",
|
||||
"subtitle": "管理全局常用问题,可配置标准答案并启用 FAQ 缓存,优先命中、跳过 Dify",
|
||||
"formHint": "启用 FAQ 缓存后,用户提问匹配成功时将直接返回标准答案,不消耗 Token。",
|
||||
"edit": "编辑问题",
|
||||
"add": "添加问题",
|
||||
"noData": "暂无常用问题配置",
|
||||
"headers": {
|
||||
"title": "标题",
|
||||
"agent": "所属应用",
|
||||
"content": "匹配问句",
|
||||
"answer": "标准答案",
|
||||
"cache": "FAQ 缓存",
|
||||
"hits": "命中",
|
||||
"order": "排序",
|
||||
"actions": "操作"
|
||||
},
|
||||
"sections": {
|
||||
"basic": "基础信息",
|
||||
"matching": "问句匹配",
|
||||
"cache": "FAQ 缓存答案"
|
||||
},
|
||||
"fields": {
|
||||
"title": "标题",
|
||||
"titlePlaceholder": "例如:写日报",
|
||||
"titlePlaceholder": "例如:上班时间",
|
||||
"targetAgent": "目标应用",
|
||||
"sortOrder": "排序",
|
||||
"content": "问题内容",
|
||||
"contentPlaceholder": "请输入完整的问题提示词..."
|
||||
"content": "标准问句",
|
||||
"contentPlaceholder": "例如:公司几点上班?",
|
||||
"contentHelp": "用户发送与此问句一致(归一化后)的文本时将命中缓存。",
|
||||
"aliases": "同义问法",
|
||||
"aliasesPlaceholder": "每行一条,例如:\n几点上班\n上班时间是什么",
|
||||
"aliasesHelp": "可选。每行填写一种同义问法,命中后同样返回标准答案。",
|
||||
"answer": "标准答案",
|
||||
"answerPlaceholder": "填写命中后直接返回给用户的完整回答…",
|
||||
"cacheEnabled": "启用 FAQ 缓存(跳过 Dify)",
|
||||
"isEnabled": "在前台展示",
|
||||
"cacheHelp": "开启后,匹配成功的问题将直接返回下方标准答案,不再调用 Dify。",
|
||||
"expiresAt": "过期时间",
|
||||
"expiresAtHelp": "可选。到期后不再命中缓存,留空表示长期有效。"
|
||||
},
|
||||
"filters": {
|
||||
"search": "搜索标题、问句或答案…",
|
||||
"allAgents": "全部应用",
|
||||
"cacheOnly": "仅显示已启用缓存",
|
||||
"resultCount": "共 {count} 条"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "已缓存",
|
||||
"cacheOff": "未缓存",
|
||||
"disabled": "已停用"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} 条同义问法"
|
||||
},
|
||||
"confirmDelete": "确定删除该常用问题吗?",
|
||||
"actions": {
|
||||
"edit": "编辑",
|
||||
"delete": "删除"
|
||||
},
|
||||
"confirmDelete": "确定删除吗?",
|
||||
"msg": {
|
||||
"fillAll": "请填写所有必填项"
|
||||
"fillAll": "请填写标题、问句和目标应用",
|
||||
"answerRequired": "启用 FAQ 缓存时必须填写标准答案",
|
||||
"saved": "保存成功"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "常用问题",
|
||||
"hotDiscovery": "热点发现"
|
||||
}
|
||||
},
|
||||
"hotFaq": {
|
||||
"intro": "系统从近 7 天 ChatLog 自动发现高频问句,写入数据库候选表;审核后可「晋升为 FAQ」,启用常用问题缓存。",
|
||||
"showRules": "查看聚合规则",
|
||||
"hideRules": "收起规则",
|
||||
"redisUnavailable": "Redis 未配置或不可用,无法存储热点候选。请配置 REDIS_URL 后重试。",
|
||||
"noData": "暂无热点候选,可点击「刷新聚合」从 ChatLog 统计。",
|
||||
"headers": {
|
||||
"query": "热点问句",
|
||||
"agent": "所属应用",
|
||||
"answer": "推荐答案",
|
||||
"asks": "7日提问",
|
||||
"users": "独立用户",
|
||||
"tokens": "均Token",
|
||||
"dominance": "答案一致率",
|
||||
"actions": "操作"
|
||||
},
|
||||
"filters": {
|
||||
"search": "搜索问句或答案…",
|
||||
"allAgents": "全部应用"
|
||||
},
|
||||
"stats": {
|
||||
"summary": "共 {count} 条候选,7日合计 {asks} 次提问"
|
||||
},
|
||||
"rules": {
|
||||
"selection": "热点选取:",
|
||||
"answer": "最佳答案:",
|
||||
"windowDays": "统计近 {n} 天且 tokens_used>0 的 Dify 对话",
|
||||
"minCount": "同一归一化问句至少 {n} 次提问",
|
||||
"minUsers": "至少 {n} 个不同用户提问"
|
||||
},
|
||||
"actions": {
|
||||
"refresh": "刷新聚合",
|
||||
"dryRun": "预览统计",
|
||||
"promote": "晋升为 FAQ",
|
||||
"dismiss": "忽略"
|
||||
},
|
||||
"msg": {
|
||||
"refreshed": "热点聚合已完成",
|
||||
"dryRunDone": "预览完成:扫描记录参与统计,晋升 {promoted} 组(扫描 {scanned} 条日志)",
|
||||
"promoted": "已晋升为常用问题 FAQ",
|
||||
"dismissed": "已忽略该热点"
|
||||
}
|
||||
},
|
||||
"announcement": {
|
||||
|
||||
@@ -197,27 +197,115 @@
|
||||
},
|
||||
"question": {
|
||||
"title": "常用問題",
|
||||
"subtitle": "管理全局常用問題",
|
||||
"subtitle": "管理全局常用問題,可配置標準答案並啟用 FAQ 快取,優先命中、跳過 Dify",
|
||||
"formHint": "啟用 FAQ 快取後,使用者提問匹配成功時將直接返回標準答案,不消耗 Token。",
|
||||
"edit": "編輯問題",
|
||||
"add": "添加問題",
|
||||
"noData": "暫無常用問題配置",
|
||||
"headers": {
|
||||
"title": "標題",
|
||||
"agent": "所屬應用",
|
||||
"content": "匹配問句",
|
||||
"answer": "標準答案",
|
||||
"cache": "FAQ 快取",
|
||||
"hits": "命中",
|
||||
"order": "排序",
|
||||
"actions": "操作"
|
||||
},
|
||||
"sections": {
|
||||
"basic": "基礎資訊",
|
||||
"matching": "問句匹配",
|
||||
"cache": "FAQ 快取答案"
|
||||
},
|
||||
"fields": {
|
||||
"title": "標題",
|
||||
"titlePlaceholder": "例如:寫日報",
|
||||
"titlePlaceholder": "例如:上班時間",
|
||||
"targetAgent": "目標應用",
|
||||
"sortOrder": "排序",
|
||||
"content": "問題內容",
|
||||
"contentPlaceholder": "請輸入完整的問題提示詞..."
|
||||
"content": "標準問句",
|
||||
"contentPlaceholder": "例如:公司幾點上班?",
|
||||
"contentHelp": "使用者發送與此問句一致(歸一化後)的文本時將命中快取。",
|
||||
"aliases": "同義問法",
|
||||
"aliasesPlaceholder": "每行一條,例如:\n幾點上班\n上班時間是什麼",
|
||||
"aliasesHelp": "可選。每行填寫一種同義問法,命中後同樣返回標準答案。",
|
||||
"answer": "標準答案",
|
||||
"answerPlaceholder": "填寫命中後直接返回給使用者的完整回答…",
|
||||
"cacheEnabled": "啟用 FAQ 快取(跳過 Dify)",
|
||||
"isEnabled": "在前台展示",
|
||||
"cacheHelp": "開啟後,匹配成功的問題將直接返回下方標準答案,不再呼叫 Dify。",
|
||||
"expiresAt": "過期時間",
|
||||
"expiresAtHelp": "可選。到期後不再命中快取,留空表示長期有效。"
|
||||
},
|
||||
"filters": {
|
||||
"search": "搜尋標題、問句或答案…",
|
||||
"allAgents": "全部應用",
|
||||
"cacheOnly": "僅顯示已啟用快取",
|
||||
"resultCount": "共 {count} 條"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "已快取",
|
||||
"cacheOff": "未快取",
|
||||
"disabled": "已停用"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} 條同義問法"
|
||||
},
|
||||
"confirmDelete": "確定刪除該常用問題嗎?",
|
||||
"actions": {
|
||||
"edit": "編輯",
|
||||
"delete": "刪除"
|
||||
},
|
||||
"confirmDelete": "確定刪除嗎?",
|
||||
"msg": {
|
||||
"fillAll": "請填寫所有必填項"
|
||||
"fillAll": "請填寫標題、問句和目標應用",
|
||||
"answerRequired": "啟用 FAQ 快取時必須填寫標準答案",
|
||||
"saved": "儲存成功"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "常用問題",
|
||||
"hotDiscovery": "熱點發現"
|
||||
}
|
||||
},
|
||||
"hotFaq": {
|
||||
"intro": "系統從近 7 天 ChatLog 自動發現高頻問句,寫入資料庫候選表;審核後可「晉升為 FAQ」。",
|
||||
"showRules": "查看聚合規則",
|
||||
"hideRules": "收起規則",
|
||||
"redisUnavailable": "Redis 未配置或不可用,無法儲存熱點候選。",
|
||||
"noData": "暫無熱點候選,可點擊「刷新聚合」。",
|
||||
"headers": {
|
||||
"query": "熱點問句",
|
||||
"agent": "所屬應用",
|
||||
"answer": "推薦答案",
|
||||
"asks": "7日提問",
|
||||
"users": "獨立用戶",
|
||||
"tokens": "均Token",
|
||||
"dominance": "答案一致率",
|
||||
"actions": "操作"
|
||||
},
|
||||
"filters": {
|
||||
"search": "搜尋問句或答案…",
|
||||
"allAgents": "全部應用"
|
||||
},
|
||||
"stats": {
|
||||
"summary": "共 {count} 條候選,7日合計 {asks} 次提問"
|
||||
},
|
||||
"rules": {
|
||||
"selection": "熱點選取:",
|
||||
"answer": "最佳答案:",
|
||||
"windowDays": "統計近 {n} 天且 tokens_used>0 的 Dify 對話",
|
||||
"minCount": "同一歸一化問句至少 {n} 次提問",
|
||||
"minUsers": "至少 {n} 個不同用戶提問"
|
||||
},
|
||||
"actions": {
|
||||
"refresh": "刷新聚合",
|
||||
"dryRun": "預覽統計",
|
||||
"promote": "晉升為 FAQ",
|
||||
"dismiss": "忽略"
|
||||
},
|
||||
"msg": {
|
||||
"refreshed": "熱點聚合已完成",
|
||||
"dryRunDone": "預覽完成:晉升 {promoted} 組(掃描 {scanned} 條日誌)",
|
||||
"promoted": "已晉升為常用問題 FAQ",
|
||||
"dismissed": "已忽略該熱點"
|
||||
}
|
||||
},
|
||||
"announcement": {
|
||||
|
||||
@@ -17,5 +17,6 @@
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user