fix(chat): 修复dify有token,chat_logs表却记录tokens_used为0
This commit is contained in:
1 parent
66410c9a27
commit
93f4ea5537
3 files changed
+216
-17
No files matched your search
+15
-14
@@ -123,17 +123,18 @@ SRM_SQLSERVER_TIMEOUT=10
|
|||||||
ERP_DB_DSN=192.168.8.24:1521/topprod
|
ERP_DB_DSN=192.168.8.24:1521/topprod
|
||||||
TEXT2SQL_SCHEMA_PATH=
|
TEXT2SQL_SCHEMA_PATH=
|
||||||
|
|
||||||
# Hot FAQ offline aggregation (ChatLog -> PostgreSQL faq_hot_candidates table)
|
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
|
||||||
FAQ_HOT_ENABLED=true
|
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
|
||||||
FAQ_HOT_WINDOW_DAYS=7
|
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
|
||||||
FAQ_HOT_MIN_COUNT=5
|
FAQ_HOT_WINDOW_DAYS=7 # 统计时间窗口(天),仅扫描近 N 天 ChatLog
|
||||||
FAQ_HOT_MIN_USERS=3
|
FAQ_HOT_MIN_COUNT=5 # 同一应用+问句最少提问次数,低于此不进入候选
|
||||||
FAQ_HOT_MIN_AVG_TOKENS=0
|
FAQ_HOT_MIN_USERS=3 # 最少独立用户数,防止单人刷榜
|
||||||
FAQ_HOT_MAX_QUERY_LEN=200
|
FAQ_HOT_MIN_AVG_TOKENS=0 # 组内平均 token 下限(0=不限制;须 tokens_used>0 才纳入)
|
||||||
FAQ_HOT_MIN_QUERY_LEN=4
|
FAQ_HOT_MAX_QUERY_LEN=200 # 问句最大字符数,过长跳过
|
||||||
FAQ_HOT_MIN_ANSWER_LEN=8
|
FAQ_HOT_MIN_QUERY_LEN=4 # 问句最短字符数,过短跳过
|
||||||
FAQ_HOT_TTL_SECONDS=604800
|
FAQ_HOT_MIN_ANSWER_LEN=8 # 答案最短字符数,过短跳过
|
||||||
FAQ_HOT_ANSWER_SIMILARITY=0.95
|
FAQ_HOT_TTL_SECONDS=604800 # 候选/忽略黑名单有效期(秒),默认 7 天
|
||||||
FAQ_HOT_ANSWER_DOMINANCE=0.6
|
FAQ_HOT_ANSWER_SIMILARITY=0.95 # 答案聚类相似度阈值(0~1),RAG 长文可适当调低至 0.80~0.85
|
||||||
FAQ_HOT_GOOD_SCORE=4
|
FAQ_HOT_ANSWER_DOMINANCE=0.6 # 最大答案簇占比下限(0~1),分歧过大则跳过;可降至 0.4 便于测试
|
||||||
FAQ_HOT_BAD_SCORE=2
|
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||||
|
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||||
@@ -602,6 +602,12 @@ class DifyService:
|
|||||||
nonlocal chat_persist_started, chat_log_id_persisted, run_id_persisted
|
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:
|
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()
|
run_id = _resolve_persist_run_id()
|
||||||
if run_id and run_id != run_id_persisted:
|
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
|
from app.services.file_check_tools.chat_log_run_binding import update_chat_log_run_id
|
||||||
@@ -873,6 +879,66 @@ class DifyService:
|
|||||||
|
|
||||||
return None
|
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
|
@staticmethod
|
||||||
def _persist_stream_chat_record(
|
def _persist_stream_chat_record(
|
||||||
*,
|
*,
|
||||||
@@ -908,7 +974,7 @@ class DifyService:
|
|||||||
data['metadata'] = metadata
|
data['metadata'] = metadata
|
||||||
data['retriever_resources'] = retriever_resources
|
data['retriever_resources'] = retriever_resources
|
||||||
|
|
||||||
usage = metadata.get('usage', {}) or {}
|
tokens_used = DifyService._extract_token_usage(data)
|
||||||
db_write_started = time.time()
|
db_write_started = time.time()
|
||||||
run_id = None
|
run_id = None
|
||||||
try:
|
try:
|
||||||
@@ -931,7 +997,7 @@ class DifyService:
|
|||||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=answer_text,
|
answer=answer_text,
|
||||||
tokens=usage.get('total_tokens', 0),
|
tokens=tokens_used,
|
||||||
latency=latency,
|
latency=latency,
|
||||||
retriever_resources=retriever_resources,
|
retriever_resources=retriever_resources,
|
||||||
attribution_parts=attribution_parts,
|
attribution_parts=attribution_parts,
|
||||||
@@ -940,12 +1006,13 @@ class DifyService:
|
|||||||
)
|
)
|
||||||
if chat_log_id and current_app:
|
if chat_log_id and current_app:
|
||||||
current_app.logger.info(
|
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,
|
request_id,
|
||||||
event_name,
|
event_name,
|
||||||
latency,
|
latency,
|
||||||
int((time.time() - db_write_started) * 1000),
|
int((time.time() - db_write_started) * 1000),
|
||||||
len(answer_text),
|
len(answer_text),
|
||||||
|
tokens_used,
|
||||||
data.get('conversation_id') or normalized_conversation_id,
|
data.get('conversation_id') or normalized_conversation_id,
|
||||||
chat_log_id,
|
chat_log_id,
|
||||||
run_id,
|
run_id,
|
||||||
|
|||||||
@@ -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
|
||||||
Reference in new issue
Block a user