from __future__ import annotations from datetime import datetime from sqlalchemy import DateTime, ForeignKey, Index, Integer, String from sqlalchemy.orm import Mapped, mapped_column from app.enums.llm_billing import LlmCallAttemptStatus from app.models.base import Base, TimestampMixin class LlmCallAttempt(Base, TimestampMixin): __tablename__ = "llm_call_attempts" __table_args__ = ( Index("uq_llm_call_attempts_sequence", "billing_execution_id", "call_sequence", unique=True), Index("ix_llm_call_attempts_execution_time", "billing_execution_id", "created_at"), Index("ix_llm_call_attempts_provider_request", "provider_request_id"), ) id: Mapped[str] = mapped_column(String(32), primary_key=True) billing_execution_id: Mapped[str] = mapped_column( String(32), ForeignKey("llm_billing_executions.id", ondelete="CASCADE"), nullable=False ) call_sequence: Mapped[int] = mapped_column(nullable=False) retry_sequence: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") model_config_id: Mapped[str | None] = mapped_column( String(32), ForeignKey("model_configs.id", ondelete="SET NULL"), nullable=True ) model_name_snapshot: Mapped[str | None] = mapped_column(String(128), nullable=True) provider_snapshot: Mapped[str | None] = mapped_column(String(64), nullable=True) provider_request_id: Mapped[str | None] = mapped_column(String(160), nullable=True) request_started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) response_received_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) duration_ms: Mapped[int | None] = mapped_column(Integer, nullable=True) status: Mapped[str] = mapped_column( String(24), nullable=False, default=LlmCallAttemptStatus.STARTED.value, server_default=LlmCallAttemptStatus.STARTED.value, ) input_tokens: Mapped[int | None] = mapped_column(Integer, nullable=True) output_tokens: Mapped[int | None] = mapped_column(Integer, nullable=True) total_tokens: Mapped[int | None] = mapped_column(Integer, nullable=True) token_usage_id: Mapped[str | None] = mapped_column( String(32), ForeignKey("token_usage.id", ondelete="SET NULL"), nullable=True ) http_status: Mapped[int | None] = mapped_column(Integer, nullable=True) provider_error_code: Mapped[str | None] = mapped_column(String(128), nullable=True) error_message: Mapped[str | None] = mapped_column(String(1000), nullable=True) token_unavailable_reason: Mapped[str | None] = mapped_column(String(256), nullable=True) postprocess_status: Mapped[str | None] = mapped_column(String(32), nullable=True) postprocess_error: Mapped[str | None] = mapped_column(String(1000), nullable=True)