""" API调用日志ORM定义 定义API调用日志的数据库表结构,用于记录每次API调用的详细信息 支持计费审计和调用统计功能 """ from sqlalchemy import Column, BigInteger, Integer, String, Boolean, DateTime, Text, Numeric, Index, ForeignKey from sqlalchemy.sql import func from app.database import Base class ApiCallLog(Base): """ API调用日志ORM类 记录每次API调用的详细信息,包括: - 调用用户和使用的API Key - 调用的模型信息(支持云端和本地模型) - Token用量和费用 - 调用状态和错误信息 """ __tablename__ = "api_call_log" # 主键ID(使用BigInteger支持大量日志) id = Column( BigInteger, primary_key=True, autoincrement=True, comment="主键ID" ) # 用户ID(外键关联users表) user_id = Column( String(50), ForeignKey("aigcspace.users.id", ondelete="CASCADE"), nullable=False, comment="用户ID" ) # API Key ID(外键关联platform_api_key表,删除时置空) api_key_id = Column( Integer, ForeignKey("aigcspace.platform_api_key.id", ondelete="SET NULL"), nullable=True, comment="API Key ID" ) # 模型ID(不再强制外键约束,中转站场景下模型可能不在本地表中) model_id = Column( Integer, nullable=True, comment="模型ID" ) # 模型名称(冗余存储,即使模型被删除也能查看历史记录) model_name = Column( String(255), nullable=False, comment="模型名称" ) # 是否为本地模型 is_local = Column( Boolean, nullable=False, default=False, comment="是否为本地模型" ) # 输入Token数量 input_tokens = Column( Integer, nullable=False, default=0, comment="输入Token数量" ) # 输出Token数量 output_tokens = Column( Integer, nullable=False, default=0, comment="输出Token数量" ) # 费用金额(精度12位,小数4位) bill = Column( Numeric(12, 4), nullable=False, default=0, comment="费用金额" ) # 调用状态:success/failed status = Column( String(20), nullable=False, default="success", comment="调用状态:success/failed" ) # 错误信息(调用失败时记录) error_message = Column( Text, nullable=True, comment="错误信息" ) # 请求IP地址 request_ip = Column( String(50), nullable=True, comment="请求IP地址" ) # 创建时间(自动设置) created_at = Column( DateTime, nullable=False, server_default=func.now(), comment="创建时间" ) # 表级配置 __table_args__ = ( Index('idx_api_call_log_user_id', 'user_id'), Index('idx_api_call_log_api_key_id', 'api_key_id'), Index('idx_api_call_log_model_id', 'model_id'), Index('idx_api_call_log_created_at', 'created_at'), Index('idx_api_call_log_is_local', 'is_local'), {'schema': 'aigcspace', 'comment': 'API调用日志表'} ) def __repr__(self): return f""