Merge branch 'dev' into hugo

This commit is contained in:
hugo committed 2026-06-17 22:29:48 +08:00
commit 97a5a1f106
35 files changed
+3749 -259

No files matched your search

+2
View File
@@ -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():
+243 -26
View File
@@ -596,11 +596,11 @@ def create_user():
@require_admin
def update_user(id):
"""
管理端编辑用户:本地变更 commit 前先同步 Casdoor update-user / set-password。
核心逻辑:应用本地字段 → _sync_casdoor_update_user → commit;Casdoor 失败则 rollback。
管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。
核心逻辑:应用本地字段 →(有 new_password 时)_sync_casdoor_update_user → commit。
Request JSON: email, department, role, status, password 等;password 为空表示不改密
Returns:
{ status: ok };Casdoor/唯一约束失败时抛出 AppError/ConflictError
{ status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError
"""
from app.api import user as user_api
user = db.session.get(User, id)
@@ -611,8 +611,6 @@ def update_user(id):
email = _empty_to_none(data.get('email'))
if email is not None and (not _is_valid_email(email)):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
profile_field_keys = {'email', 'department', 'status', 'real_name', 'phone_number'}
sync_profile = any(k in data for k in profile_field_keys)
new_password = _empty_to_none(data.get('password'))
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
if k in data:
@@ -626,12 +624,8 @@ def update_user(id):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
try:
if sync_profile or new_password:
user_api._sync_casdoor_update_user(
user,
new_password=new_password,
sync_profile=sync_profile,
)
if new_password:
user_api._sync_casdoor_update_user(user, new_password=new_password)
db.session.commit()
except IntegrityError as e:
db.session.rollback()
@@ -641,7 +635,7 @@ def update_user(id):
raise
except RuntimeError as e:
db.session.rollback()
user_api._raise_casdoor_update_user_error(e)
user_api._raise_casdoor_set_password_error(e)
return jsonify({'status': 'ok'})
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
@@ -808,39 +802,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'})
@@ -853,6 +956,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
View File
@@ -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:
+18 -39
View File
@@ -463,22 +463,19 @@ def _sync_casdoor_admin_set_password(user: User, new_password: str):
_raise_casdoor_user_not_in_idp(exc)
_raise_casdoor_set_password_error(exc)
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None, sync_profile: bool = True):
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
"""
管理端编辑用户时同步 Casdoor:资料走 update-user,密码走 set-password(管理员 override)。
核心逻辑:Casdoor 已配置则必须成功;IdP 无账号且请求含新密码时 fallback add-user 补建。
管理端编辑用户时同步 Casdoor:仅改密时 set-password;IdP 无账号则 add-user 补建。
核心逻辑:资料字段只写本地库,不调用 update-user;无新密码则跳过 Casdoor。
@param user: 已应用本地变更但未 commit 的 User 实例
@param new_password: 管理员设置的新密码;None 表示不改密
@param sync_profile: 是否同步资料字段(email/姓名/手机/部门/状态)
Raises:
AppError / ConflictError: Casdoor 同步失败
AppError / ConflictError: Casdoor 改密或补建失败
"""
if not _is_casdoor_configured():
if not _is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
if not new_password:
_raise_casdoor_user_not_in_idp()
_sync_casdoor_create_user(
username=user.username,
password=new_password,
@@ -489,36 +486,13 @@ def _sync_casdoor_update_user(user: User, *, new_password: str | None = None, sy
department=user.department,
)
if sync_profile:
profile_payload = _build_casdoor_user_profile_payload(
username=user.username,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
)
try:
_casdoor_update_user(profile_payload)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
except RuntimeError as exc:
if _is_casdoor_user_missing_error(str(exc)):
_provision_missing_user_in_casdoor()
return
_raise_casdoor_update_user_error(exc)
if new_password:
try:
_sync_casdoor_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
try:
_sync_casdoor_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
def _is_casdoor_password_error(message: str) -> bool:
lowered = (message or '').lower()
@@ -1652,7 +1626,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()
+1
View File
@@ -0,0 +1 @@
"""FAQ CLI 包。"""
+44
View File
@@ -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
View File
@@ -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):
"""
+70 -3
View File
@@ -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,
+187
View File
@@ -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"
+29
View File
@@ -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
+20
View File
@@ -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
+449
View File
@@ -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',
}
+54
View File
@@ -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")
+25 -26
View File
@@ -137,9 +137,9 @@ def _create_local_user(username: str, email: str) -> User:
return user
def test_admin_update_user_syncs_casdoor_profile(client, admin_headers, monkeypatch):
def test_admin_update_user_skips_casdoor_profile_sync(client, admin_headers, monkeypatch):
"""
编辑资料时应调用 update-user,且本地库成功更新。
编辑资料时不应调用 Casdoor update-user,仅更新本地库。
"""
user = _create_local_user('edit_profile', 'edit_profile@example.com')
client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test'
@@ -147,13 +147,16 @@ def test_admin_update_user_syncs_casdoor_profile(client, admin_headers, monkeypa
client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret'
client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX'
casdoor_calls = {'update_user': 0, 'payload': None}
casdoor_calls = {'update_user': 0, 'set_password': 0}
def fake_update_user(payload):
def fake_update_user(_payload):
casdoor_calls['update_user'] += 1
casdoor_calls['payload'] = payload
def fake_set_password(*_args, **_kwargs):
casdoor_calls['set_password'] += 1
monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user)
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
res = client.put(
f'/api/admin/users/{user.id}',
@@ -161,11 +164,7 @@ def test_admin_update_user_syncs_casdoor_profile(client, admin_headers, monkeypa
headers=admin_headers,
)
assert res.status_code == 200
assert casdoor_calls['update_user'] == 1
assert casdoor_calls['payload']['name'] == 'edit_profile'
assert casdoor_calls['payload']['email'] == 'updated@example.com'
assert casdoor_calls['payload']['displayName'] == 'Updated Name'
assert casdoor_calls['payload']['phone'] == '13800002222'
assert casdoor_calls == {'update_user': 0, 'set_password': 0}
db.session.refresh(user)
assert user.email == 'updated@example.com'
@@ -201,9 +200,9 @@ def test_admin_update_user_syncs_casdoor_password(client, admin_headers, monkeyp
assert user.check_password('new-admin-password')
def test_admin_update_user_rolls_back_when_casdoor_fails(client, admin_headers, monkeypatch):
def test_admin_update_user_rolls_back_when_casdoor_password_fails(client, admin_headers, monkeypatch):
"""
Casdoor 更新失败时不应保留本地变更。
Casdoor 改密失败时不应保留本地变更。
"""
user = _create_local_user('rollback_edit', 'rollback_edit@example.com')
client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test'
@@ -211,28 +210,28 @@ def test_admin_update_user_rolls_back_when_casdoor_fails(client, admin_headers,
client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret'
client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX'
def fake_update_user(_payload):
def fake_set_password(_owner, _name, _old, _new):
raise user_api.AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system.',
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to update password in authentication system.',
http_status=502,
)
monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user)
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
res = client.put(
f'/api/admin/users/{user.id}',
json={'email': 'should-not-save@example.com'},
json={'password': 'should-not-save'},
headers=admin_headers,
)
assert res.status_code == 502
db.session.refresh(user)
assert user.email == 'rollback_edit@example.com'
assert user.check_password('old-password')
def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, admin_headers, monkeypatch):
"""
IdP 无账号且管理员同时提供新密码时,应 fallback 至 add-user 补建。
IdP 无账号且管理员改密时,应 set-password 失败后 fallback 至 add-user,不调用 update-user。
"""
user = _create_local_user('legacy_user', 'legacy_user@example.com')
client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test'
@@ -240,21 +239,21 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client,
client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret'
client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX'
casdoor_calls = {'update_user': 0, 'add_user': 0}
casdoor_calls = {'update_user': 0, 'add_user': 0, 'set_password': 0}
def fake_update_user(_payload):
casdoor_calls['update_user'] += 1
raise user_api.AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system.',
http_status=409,
)
def fake_add_user(_payload):
casdoor_calls['add_user'] += 1
def fake_set_password(_owner, _name, _old, _new):
casdoor_calls['set_password'] += 1
raise RuntimeError("Casdoor set-password failed: {'status': 'error', 'msg': \"The user: organization_HX/legacy_user doesn't exist\"}")
monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user)
monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user)
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
res = client.put(
f'/api/admin/users/{user.id}',
@@ -262,7 +261,7 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client,
headers=admin_headers,
)
assert res.status_code == 200
assert casdoor_calls == {'update_user': 1, 'add_user': 1}
assert casdoor_calls == {'update_user': 0, 'add_user': 1, 'set_password': 1}
db.session.refresh(user)
assert user.real_name == 'Legacy Updated'
+131
View File
@@ -0,0 +1,131 @@
"""
backend/tests/test_dify_token_usage.py
测试 Dify SSE 事件 token 解析与 ChatLog 回写逻辑。
"""
import pytest
from app import create_app, db
from app.models import Agent, ChatLog, User
from app.services.dify import DifyService
@pytest.fixture
def app():
app = create_app('testing')
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
def test_extract_token_usage_from_message_end_metadata():
"""Chatbot message_end:token 在 metadata.usage.total_tokens。"""
data = {'metadata': {'usage': {'total_tokens': 88}}}
assert DifyService._extract_token_usage(data) == 88
def test_extract_token_usage_from_workflow_finished_payload():
"""Chatflow workflow_finished:token 在 data.total_tokens。"""
data = {
'event': 'workflow_finished',
'data': {
'status': 'succeeded',
'total_tokens': 3068,
},
}
assert DifyService._extract_token_usage(data) == 3068
def test_extract_token_usage_from_execution_metadata():
"""部分 Workflow 版本 token 在 data.execution_metadata.total_tokens。"""
data = {
'data': {
'execution_metadata': {'total_tokens': 1200},
},
}
assert DifyService._extract_token_usage(data) == 1200
def test_extract_token_usage_prefers_positive_metadata_over_zero_payload():
"""metadata 有值时优先使用(兼容 Chatbot)。"""
data = {
'metadata': {'usage': {'total_tokens': 50}},
'data': {'total_tokens': 0},
}
assert DifyService._extract_token_usage(data) == 50
def test_persist_stream_chat_record_uses_workflow_finished_tokens(app):
"""workflow_finished 首次落库应写入 data.total_tokens。"""
with app.app_context():
user = User(username='u1', role='user', email='u1@example.com')
agent = Agent(name='wf_agent', dify_app_id='wf-1')
db.session.add_all([user, agent])
db.session.commit()
result = DifyService._persist_stream_chat_record(
data={
'event': 'workflow_finished',
'conversation_id': 'conv-wf-1',
'data': {'status': 'succeeded', 'total_tokens': 3068},
},
event_name='workflow_finished',
request_id='req-wf',
user_id=user.id,
agent=agent,
session_id='sess-wf',
hxops_turn_id=None,
normalized_conversation_id='conv-wf-1',
query='上班时间',
answer_text='白班 8:00-17:00',
latency=20000,
retriever_resources=[],
attribution_parts=[],
)
assert result and result.get('chat_log_id')
log = db.session.get(ChatLog, result['chat_log_id'])
assert log is not None
assert log.tokens_used == 3068
def test_update_chat_log_tokens_backfills_after_message_end(app):
"""message_end 先落库 tokens=0 后,workflow_finished 应回写 token。"""
with app.app_context():
user = User(username='u2', role='user', email='u2@example.com')
agent = Agent(name='wf_agent2', dify_app_id='wf-2')
db.session.add_all([user, agent])
db.session.commit()
first = DifyService._persist_stream_chat_record(
data={
'event': 'message_end',
'conversation_id': 'conv-wf-2',
'metadata': {},
},
event_name='message_end',
request_id='req-wf-2',
user_id=user.id,
agent=agent,
session_id='sess-wf-2',
hxops_turn_id=None,
normalized_conversation_id='conv-wf-2',
query='上班时间',
answer_text='白班 8:00-17:00',
latency=15000,
retriever_resources=[],
attribution_parts=[],
)
chat_log_id = first['chat_log_id']
assert db.session.get(ChatLog, chat_log_id).tokens_used == 0
updated = DifyService._update_chat_log_tokens(chat_log_id, 3068)
assert updated is True
assert db.session.get(ChatLog, chat_log_id).tokens_used == 3068
# 不应被更小的值覆盖
assert DifyService._update_chat_log_tokens(chat_log_id, 100) is False
+53
View File
@@ -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')