Skip to content

The platform for continuously improving AI agents.

4.8 KB
Raw Blame
"""The one meter for OpenRouter. Every request the provider answered is charged at what it
billed (`usage.cost`), keyed by its generation id, to the cause the caller set with
`billed`. A generation whose cost did not arrive, as when a stream was cut, is priced later
from `/generation`. A request with no cause is our cost: it is logged, never charged to
anyone."""

from __future__ import annotations

import asyncio
import logging
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from contextvars import ContextVar, copy_context
from decimal import Decimal
from typing import Any

import httpx
from django.conf import settings

from overbae.core.model_registry import OPENROUTER_BASE_URL
from overbae.services.billing_ledger import Cause, charge

logger = logging.getLogger(__name__)

_CAUSE: ContextVar[Cause | None] = ContextVar("billing_cause", default=None)


@contextmanager
def billed(found: Cause) -> Iterator[Cause]:
    """Charge the model calls made inside the block, in this thread and the tasks and
    threads it starts with its context, to ``found``."""
    token = _CAUSE.set(found)
    try:
        yield found
    finally:
        _CAUSE.reset(token)


def current() -> Cause | None:
    return _CAUSE.get()


def carried(fn: Callable[..., Any], found: Cause | None = None) -> Callable[..., Any]:
    """``fn`` with this context's cause, or ``found``, for a thread pool, which starts its
    threads without it."""
    context = copy_context()

    def run(*args, **kwargs):
        if found is None:
            return fn(*args, **kwargs)
        with billed(found):
            return fn(*args, **kwargs)

    return lambda *args, **kwargs: context.run(run, *args, **kwargs)


def _cost(value: Any) -> Decimal | None:
    if isinstance(value, bool) or not isinstance(value, int | float | str | Decimal):
        return None
    try:
        cost = Decimal(str(value))
    except ArithmeticError:
        return None
    return cost if cost.is_finite() and cost >= 0 else None


def settle(
    generation: str | None,
    cost: Any,
    *,
    model: str,
    prompt_tokens: int | None = None,
    completion_tokens: int | None = None,
    found: Cause | None = None,
) -> None:
    """Charge one answered OpenRouter request. Never raises: the provider has billed it,
    and the caller's work goes on."""
    found = found or _CAUSE.get()
    if not generation:
        logger.warning("OpenRouter answer without a generation id for model %s", model)
        return
    if found is None:
        logger.error("OpenRouter generation without a billing cause: %s", generation)
        return
    usage = {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens}
    priced = _cost(cost)
    try:
        asyncio.get_running_loop()
        on_loop = True
    except RuntimeError:
        on_loop = False
    try:
        if priced is None or on_loop:
            # An unpriced generation waits for the provider; an event loop cannot write.
            # Lazy: tasks import services.
            from overbae.tasks.billing import price_generation

            price_generation.delay(
                found.as_dict(), generation, model, None if priced is None else str(priced), usage
            )
            return
        charge_generation(found, generation, priced, model, usage)
    except Exception:
        logger.exception("Charging OpenRouter generation %s failed; it is retried", generation)
        _retry(found, generation, model, priced, usage)


def _retry(found: Cause, generation: str, model: str, priced: Decimal | None, usage) -> None:
    # Lazy: tasks import services.
    from overbae.tasks.billing import price_generation

    try:
        price_generation.delay(
            found.as_dict(), generation, model, None if priced is None else str(priced), usage
        )
    except Exception:
        logger.exception("OpenRouter generation charge is lost: %s", generation)


def charge_generation(
    found: Cause, generation: str, cost: Decimal, model: str, usage: dict[str, Any]
) -> None:
    charge(
        found,
        cost,
        key=f"openrouter:{generation}",
        resource=f"openrouter {model}",
        quantity=Decimal(1),
        unit="generation",
        unit_usd=cost,
        provider_ref=generation,
        metadata={key: value for key, value in usage.items() if value is not None},
    )


def generation_cost(generation: str) -> Decimal | None:
    """What OpenRouter billed for a generation; None while it has not priced it yet."""
    response = httpx.get(
        f"{OPENROUTER_BASE_URL}/generation",
        params={"id": generation},
        headers={"Authorization": f"Bearer {settings.OPENROUTER_API_KEY}"},
        timeout=30,
    )
    if response.status_code == 404:
        return None
    response.raise_for_status()
    return _cost(response.json()["data"].get("total_cost"))