fix(chat): 修复dify有token,chat_logs表却记录tokens_used为0

This commit is contained in:
sophie committed 2026-06-17 18:02:13 +08:00
1 parent 66410c9a27
commit 93f4ea5537
3 files changed
+216 -17

No files matched your search

+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,