statistics.py 2.9 KB
"""调用统计 SQLAlchemy 模型"""
import uuid
from datetime import datetime
from sqlalchemy import Integer, Float, DateTime
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.mysql import VARCHAR

from app.core.database import Base


class CallStatistics(Base):
    """调用统计聚合表"""
    __tablename__ = "ai_llmbase_call_statistics"

    id: Mapped[str] = mapped_column(
        VARCHAR(36), primary_key=True,
        default=lambda: str(uuid.uuid4())
    )
    agg_dimension: Mapped[str] = mapped_column(
        VARCHAR(10), nullable=False,
        comment="聚合维度:hourly/daily"
    )
    agg_time: Mapped[datetime] = mapped_column(
        DateTime, nullable=False,
        comment="聚合时间点"
    )
    model_name: Mapped[str | None] = mapped_column(
        VARCHAR(100), nullable=True,
        comment="模型名称(按模型维度聚合)"
    )
    account_id: Mapped[str | None] = mapped_column(
        VARCHAR(36), nullable=True,
        comment="账号 ID(按账号维度聚合)"
    )
    biz_type: Mapped[str | None] = mapped_column(
        VARCHAR(50), nullable=True,
        comment="业务类型(按业务维度聚合)"
    )
    total_calls: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="总调用次数"
    )
    success_calls: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="成功调用次数"
    )
    failed_calls: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="失败调用次数"
    )
    success_rate: Mapped[float] = mapped_column(
        Float, nullable=False, default=0.0,
        comment="成功率"
    )
    avg_duration_ms: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="平均耗时(毫秒)"
    )
    p50_duration_ms: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="P50 耗时(毫秒)"
    )
    p95_duration_ms: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="P95 耗时(毫秒)"
    )
    p99_duration_ms: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="P99 耗时(毫秒)"
    )
    total_prompt_tokens: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="Prompt Token 消耗总量"
    )
    total_completion_tokens: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="Completion Token 消耗总量"
    )
    total_tokens: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0,
        comment="Token 消耗总量"
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime, default=datetime.now,
        comment="创建时间"
    )

    def __repr__(self) -> str:
        return f"<CallStatistics {self.agg_dimension}@{self.agg_time}>"