The platform for continuously improving AI agents.
"""The daily check that the ledger matches what the providers billed this environment.
It reads Modal's billing report and the usage of this environment's OpenRouter key, compares
each with the ledger's charges of the same provider and window, and logs an error when they
differ by more than ``TOLERANCE``. It never changes the ledger. What the platform absorbs
(gateways, internal checks, unattributed calls) shows up here as a difference.
"""
from __future__ import annotations
import asyncio
import logging
from datetime import UTC, datetime, timedelta
from decimal import Decimal
import httpx
import modal
from asgiref.sync import async_to_sync
from django.conf import settings
from django.db.models import Sum
from overbae.core.model_registry import OPENROUTER_BASE_URL
from overbae.models import BillingTelemetry
logger = logging.getLogger(__name__)
TOLERANCE = Decimal("0.02")
MODAL_DAYS = 7
def _ledger(prefix: str, **window) -> Decimal:
total = BillingTelemetry.objects.filter(resource__startswith=prefix, **window).aggregate(
total=Sum("amount")
)["total"]
return -(total or Decimal(0))
def modal_billed(start: datetime, end: datetime) -> Decimal:
async def fetch():
report = modal.Workspace.from_context().billing.report
return await asyncio.wait_for(report.aio(start=start, end=end, resolution="d"), timeout=60)
items = async_to_sync(fetch)()
environment = settings.MODAL_ENVIRONMENT
return sum(
(
Decimal(str(item.cost))
for item in items
if not environment or getattr(item, "environment_name", "") == environment
),
Decimal(0),
)
def openrouter_billed() -> tuple[Decimal, datetime]:
"""This key's usage this UTC month, and the month's start."""
response = httpx.get(
f"{OPENROUTER_BASE_URL}/key",
headers={"Authorization": f"Bearer {settings.OPENROUTER_API_KEY}"},
timeout=30,
)
response.raise_for_status()
now = datetime.now(UTC)
month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
return Decimal(str(response.json()["data"]["usage_monthly"])), month
def _compare(provider: str, billed: Decimal, charged: Decimal, window: str) -> dict:
difference = charged - billed
off = billed and abs(difference) / billed > TOLERANCE or not billed and charged > 0
result = {
"provider": provider,
"window": window,
"billed_usd": str(billed),
"charged_usd": str(charged),
"within_tolerance": not off,
}
if off:
logger.error(
"Ledger differs from the provider bill by more than 2%%: %s %s billed %s charged %s",
provider,
window,
billed,
charged,
)
return result
def check() -> list[dict]:
results = []
end = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
start = end - timedelta(days=MODAL_DAYS)
try:
billed = modal_billed(start, end)
# A container row is dated by when it stopped; one that spans the window's edge
# moves cost across it, which the seven days dilute.
charged = _ledger("modal", ended_at__gte=start, ended_at__lt=end)
results.append(_compare("modal", billed, charged, f"{start:%Y-%m-%d}..{end:%Y-%m-%d}"))
except Exception:
logger.exception("Modal billing report unavailable for the provider check")
if settings.OPENROUTER_API_KEY:
try:
billed, month = openrouter_billed()
charged = _ledger("openrouter", timestamp__gte=month)
results.append(_compare("openrouter", billed, charged, f"{month:%Y-%m} to date"))
except Exception:
logger.exception("OpenRouter key usage unavailable for the provider check")
return results