""" 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