Merge branch 'dev' into hugo
This commit is contained in:
commit
97a5a1f106
35 files changed
+3749
-259
No files matched your search
@@ -602,6 +602,12 @@ class DifyService:
|
||||
nonlocal chat_persist_started, chat_log_id_persisted, run_id_persisted
|
||||
|
||||
if chat_persist_started and event_name == "workflow_finished" and chat_log_id_persisted:
|
||||
# [STEP 1] message_end 可能已落库但 tokens=0;workflow_finished 携带 data.total_tokens 时回写
|
||||
wf_tokens = DifyService._extract_token_usage(data)
|
||||
app_obj = current_app._get_current_object() if current_app else None
|
||||
if app_obj and wf_tokens > 0:
|
||||
with app_obj.app_context():
|
||||
DifyService._update_chat_log_tokens(chat_log_id_persisted, wf_tokens)
|
||||
run_id = _resolve_persist_run_id()
|
||||
if run_id and run_id != run_id_persisted:
|
||||
from app.services.file_check_tools.chat_log_run_binding import update_chat_log_run_id
|
||||
@@ -873,6 +879,66 @@ class DifyService:
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _extract_token_usage(data: dict) -> int:
|
||||
"""
|
||||
从 Dify SSE 事件 payload 提取 token 用量(best effort)。
|
||||
核心逻辑:Chatbot 在 metadata.usage.total_tokens;Chatflow/Workflow 在 data.total_tokens
|
||||
或 data.execution_metadata.total_tokens(与 chat_perf.ChatPerfTracker 对齐)。
|
||||
@param data - 单条 SSE 解析后的 dict
|
||||
@returns 非负整数 token 数;无法解析时返回 0
|
||||
"""
|
||||
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
|
||||
usage = metadata.get('usage') if isinstance(metadata.get('usage'), dict) else {}
|
||||
payload = data.get('data') if isinstance(data.get('data'), dict) else {}
|
||||
|
||||
candidates = [
|
||||
usage.get('total_tokens'),
|
||||
payload.get('total_tokens'),
|
||||
]
|
||||
exec_meta = payload.get('execution_metadata')
|
||||
if isinstance(exec_meta, dict):
|
||||
candidates.append(exec_meta.get('total_tokens'))
|
||||
|
||||
for raw in candidates:
|
||||
try:
|
||||
value = int(raw or 0)
|
||||
if value > 0:
|
||||
return value
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def _update_chat_log_tokens(chat_log_id: int, tokens: int) -> bool:
|
||||
"""
|
||||
回写已有 ChatLog 的 tokens_used。
|
||||
核心逻辑:message_end 先落库时可能尚无 token;workflow_finished 到达后补写更大值。
|
||||
@param chat_log_id - ChatLog 主键
|
||||
@param tokens - 从 Dify 事件解析出的 token 数
|
||||
@returns 是否成功更新
|
||||
"""
|
||||
if not chat_log_id or tokens <= 0:
|
||||
return False
|
||||
try:
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
if not log:
|
||||
return False
|
||||
if int(log.tokens_used or 0) >= tokens:
|
||||
return False
|
||||
log.tokens_used = tokens
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
'Failed to update chat log tokens chat_log_id=%s: %s',
|
||||
chat_log_id,
|
||||
e,
|
||||
)
|
||||
db.session.rollback()
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _persist_stream_chat_record(
|
||||
*,
|
||||
@@ -908,7 +974,7 @@ class DifyService:
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
tokens_used = DifyService._extract_token_usage(data)
|
||||
db_write_started = time.time()
|
||||
run_id = None
|
||||
try:
|
||||
@@ -931,7 +997,7 @@ class DifyService:
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=answer_text,
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
tokens=tokens_used,
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
@@ -940,12 +1006,13 @@ class DifyService:
|
||||
)
|
||||
if chat_log_id and current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s chat_log_id=%s run_id=%s",
|
||||
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s tokens=%s conversation_id=%s chat_log_id=%s run_id=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
latency,
|
||||
int((time.time() - db_write_started) * 1000),
|
||||
len(answer_text),
|
||||
tokens_used,
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
chat_log_id,
|
||||
run_id,
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user