Skip to content

The platform for continuously improving AI agents.

5.5 KB
Raw Blame
from __future__ import annotations

import uuid

from django.conf import settings
from django.db import models


class BillingService(models.TextChoices):
    GRANT = "grant", "Grant"
    PURCHASE = "purchase", "Purchase"
    FINETUNING_JOB = "finetuning-job", "Training"
    INFERENCE = "inference", "Inference"
    INFERENCE_FT_MODEL = "inference-ft-model", "Fine-tuned inference"
    DEDICATED_INFERENCE = "dedicated-inference", "Dedicated inference"
    # Rows written before the assistant charged as its own service.
    DATA_WORKSHOP = "data-workshop", "Data workshop"
    RESEARCH = "research", "Research"
    EVALUATION = "evaluation", "Evaluation"
    SCORING = "scoring", "Scoring"
    ASSISTANT = "assistant", "Assistant"
    WORKSPACE = "workspace", "Assistant workspace"


# Money in; every other row is one measured provider cost of a project's work.
CREDIT_SERVICES = (BillingService.GRANT, BillingService.PURCHASE)


class BillingTelemetry(models.Model):
    """Credits ledger. Balance = SUM(amount) per user. A usage row is one provider cost at
    the provider's price: ``quantity`` ``unit`` at ``unit_usd`` each. A container row grows
    while the container runs; every other row is written once."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="billing_telemetry",
    )
    # Who started the work; the user above pays, the project's owner.
    actor = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="+",
    )
    # No database constraint: a deleted project's charges keep naming it.
    project = models.ForeignKey(
        "overbae.Project",
        on_delete=models.DO_NOTHING,
        db_constraint=False,
        null=True,
        blank=True,
        related_name="billing_telemetry",
    )
    amount = models.DecimalField(max_digits=12, decimal_places=7)
    timestamp = models.DateTimeField(auto_now_add=True, db_index=True)
    service = models.CharField(max_length=32, choices=BillingService.choices)
    # What caused the cost, such as ``eval_run`` and its id.
    cause_kind = models.CharField(max_length=32, blank=True, default="")
    cause_id = models.CharField(max_length=64, blank=True, default="")
    experiment = models.ForeignKey(
        "overbae.Experiment",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="+",
    )
    run = models.ForeignKey(
        "overbae.ExperimentRun",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="+",
    )
    # What the provider billed: a model, or a container's GPU, CPU and memory.
    resource = models.CharField(max_length=128, blank=True, default="")
    quantity = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
    unit = models.CharField(max_length=16, blank=True, default="")
    unit_usd = models.DecimalField(max_digits=20, decimal_places=12, null=True, blank=True)
    # The provider's own id for what it billed: a generation, a container.
    provider_ref = models.CharField(max_length=255, blank=True, default="")
    started_at = models.DateTimeField(null=True, blank=True)
    ended_at = models.DateTimeField(null=True, blank=True)
    idempotency_key = models.CharField(max_length=255, null=True, blank=True, unique=True)
    metadata = models.JSONField(default=dict, blank=True)

    class Meta:
        ordering = ["-timestamp"]
        indexes = [
            models.Index(fields=["user", "timestamp"], name="billing_tel_user_ts_idx"),
            models.Index(fields=["project", "timestamp"], name="billing_tel_project_ts_idx"),
            models.Index(fields=["cause_kind", "cause_id"], name="billing_tel_cause_idx"),
        ]

    def __str__(self) -> str:
        return f"BillingTelemetry({self.user_id}, {self.service}, {self.amount})"


class WorkspaceSandbox(models.Model):
    """A provider sandbox of a project workspace, metered from its start until it ends."""

    sandbox_id = models.CharField(max_length=64, unique=True)
    project = models.ForeignKey(
        "overbae.Project",
        on_delete=models.SET_NULL,
        null=True,
        related_name="workspace_sandboxes",
    )
    # The project's owner when the sandbox started; empty for a sandbox of no project, such
    # as the provider's own checks.
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True,
        related_name="workspace_sandboxes",
    )
    started_at = models.DateTimeField(auto_now_add=True)
    billed_until = models.DateTimeField()
    finished = models.BooleanField(default=False, db_index=True)


class MeteredContainer(models.Model):
    """A Modal container's report, as far as it is charged: the totals it had reported then,
    and the ref its idle time goes to (modal_shared/container_meter.py)."""

    container_id = models.CharField(max_length=64, primary_key=True)
    function = models.CharField(max_length=128, blank=True, default="")
    started_at = models.DateTimeField()
    # The report time up to which the container is charged.
    charged_until = models.DateTimeField()
    # Cumulative report values already charged: wall, GPU, CPU and memory seconds, and seconds
    # per ref.
    charged = models.JSONField(default=dict)
    last_ref = models.CharField(max_length=255, blank=True, default="")
    finished = models.BooleanField(default=False, db_index=True)