132 lines
4.3 KiB
Python
132 lines
4.3 KiB
Python
"""
|
||
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
|