Skip to content

The platform for continuously improving AI agents.

4.1 KB
Raw Blame
import uuid
from decimal import Decimal

import pytest
from asgiref.sync import async_to_sync
from factories import make_member, make_project, make_span, make_user

from overbae.core.llms import IncompleteCompletionError, call_llm, stream_llm_tools
from overbae.innermind import span_processor
from overbae.models import BillingService, BillingTelemetry
from overbae.services import billing_ledger, model_meter
from overbae.tasks import billing as billing_tasks

pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]


@pytest.fixture
def owner():
    return make_user()


@pytest.fixture
def project(owner):
    return make_project(member=owner)


def usage_rows():
    return list(BillingTelemetry.objects.filter(amount__lt=0).order_by("timestamp"))


def test_an_answered_call_is_charged_to_the_owner_at_the_provider_cost(fake_llm, owner, project):
    member = make_user()
    make_member(member, project)
    fake_llm.on(lambda r: True, {"content": "ok", "usage": {"cost": 0.002}})
    found = billing_ledger.cause(project.pk, BillingService.SCORING, "span", "s-1", actor=member)
    with model_meter.billed(found):
        call_llm("hi")

    (row,) = usage_rows()
    assert (row.user_id, row.actor_id, row.project_id) == (owner.pk, member.pk, project.pk)
    assert (row.cause_kind, row.cause_id, row.service) == ("span", "s-1", "scoring")
    assert (row.quantity, row.unit, row.unit_usd, row.amount) == (
        Decimal(1),
        "generation",
        Decimal("0.002"),
        Decimal("-0.002"),
    )
    assert row.idempotency_key == f"openrouter:{row.provider_ref}"


def test_an_answer_cut_at_its_token_limit_is_still_charged(fake_llm, project):
    fake_llm.on(
        lambda r: True, {"content": "par", "finish_reason": "length", "usage": {"cost": 0.01}}
    )
    with (
        model_meter.billed(billing_ledger.cause(project.pk, "evaluation", "eval_run", "r")),
        pytest.raises(IncompleteCompletionError),
    ):
        call_llm("hi")
    assert [row.amount for row in usage_rows()] == [Decimal("-0.01")]


def test_an_unpriced_stream_is_charged_once_the_provider_prices_it(
    fake_llm, owner, project, monkeypatch
):
    later = []
    monkeypatch.setattr(billing_tasks.price_generation, "delay", lambda *a: later.append(a))
    fake_llm.stream_rounds([([], "Hello.")], cost=None)
    found = billing_ledger.cause(project.pk, "assistant", "assistant_thread", str(uuid.uuid4()))
    with model_meter.billed(found):
        stream_llm_tools([{"role": "user", "content": "hi"}], [])
    assert usage_rows() == []
    ((cause, generation, model, cost, usage),) = later
    assert cost is None

    fake_llm.generations[generation] = 0.02
    for _ in range(2):
        billing_tasks.price_generation.apply(args=(cause, generation, model, cost, usage))
    (row,) = usage_rows()
    assert (row.amount, row.user_id, row.cause_kind) == (
        Decimal("-0.02"),
        owner.pk,
        "assistant_thread",
    )


def test_a_deleted_projects_generation_keeps_its_project_and_owner(fake_llm, owner, project):
    cause = billing_ledger.cause(
        project.pk, "assistant", "assistant_thread", str(uuid.uuid4())
    ).as_dict()
    project_id = project.pk
    project.delete()
    fake_llm.generations["gen-gone"] = 0.03
    billing_tasks.price_generation.apply(args=(cause, "gen-gone", "m", None, {}))
    (row,) = usage_rows()
    assert (row.amount, row.user_id, row.project_id) == (Decimal("-0.03"), owner.pk, project_id)


def test_a_call_with_no_cause_is_named_and_charged_to_no_one(fake_llm, caplog):
    fake_llm.on(lambda r: True, {"content": "ok", "usage": {"cost": 0.002}})
    call_llm("hi")
    assert usage_rows() == []
    assert "OpenRouter generation without a billing cause" in caplog.text


def test_scoring_waits_while_the_owner_has_no_credits(fake_llm, owner, project):
    billing_ledger.append_entry(user=owner, amount=Decimal("-50"), service="assistant")
    span = make_span(project, trace_id="t-1")
    assert async_to_sync(span_processor.score_project_spans)(project.pk, [span]) == []
    assert fake_llm.requests == [] and fake_llm.decisions == []
    span.refresh_from_db()
    assert "score" not in span.eval_attributes