Files
ai_api_web/backend/models/usage_log.py
2026-01-22 18:26:47 +08:00

50 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from models import db
from datetime import datetime
class UsageLog(db.Model):
__tablename__ = 'usage_logs'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
token_id = db.Column(db.Integer, db.ForeignKey('tokens.id'), nullable=False)
token_name = db.Column(db.String(100), nullable=True)
group = db.Column(db.String(100), nullable=True)
log_type = db.Column(db.String(50), nullable=False) # chat, image, task等
model = db.Column(db.String(100), nullable=False)
duration = db.Column(db.Float, nullable=True) # 用时(秒)
first_token_time = db.Column(db.Float, nullable=True) # 首字时间(秒)
input_tokens = db.Column(db.Integer, default=0)
output_tokens = db.Column(db.Integer, default=0)
cost = db.Column(db.Numeric(10, 4), default=0.0000)
ip_address = db.Column(db.String(50), nullable=True)
details = db.Column(db.Text, nullable=True) # JSON字符串存储详细信息
created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
def to_dict(self):
"""转换为字典"""
return {
'id': self.id,
'token_name': self.token_name,
'group': self.group,
'log_type': self.log_type,
'model': self.model,
'duration': self.duration,
'first_token_time': self.first_token_time,
'time_display': self.time_display,
'input_tokens': self.input_tokens,
'output_tokens': self.output_tokens,
'cost': float(self.cost),
'ip_address': self.ip_address,
'details': self.details,
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
}
@property
def time_display(self):
"""时间显示文本"""
if self.duration is not None:
return f'{self.duration:.2f}s'
if self.first_token_time is not None:
return f'{self.first_token_time:.2f}s'
return '-'