Spaces:
Running

Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
4.98 kB
"""Token -> USD cost accounting (Phase 15).
Every LLM call made inside a run reports its token usage (``core.agent.models``); the price
table below turns it into dollars, which are added to ``runs.cost_usd`` as they happen. The
gateway's per-run cost circuit breaker (``Gateway.run_cost`` -> ``max_run_cost_usd``) reads
that column, so a runaway loop is stopped mid-run, and the analytics endpoints sum it per
tenant.
**The built-in prices are UNVERIFIED placeholders** (USD per 1M tokens, [input, output]).
Check them against the provider's current price list and override them with
``WP_MODEL_PRICES='{"anthropic:claude-sonnet-5-5": [3.0, 15.0]}'``. Lookup is by the
longest matching prefix of the model string (``provider:model``), with and without the
provider prefix. Unknown models cost 0 and are logged once, so a missing price never blocks
a run but is visible.
"""
from __future__ import annotations
import logging
import uuid
from collections.abc import Mapping
from datetime import datetime
from functools import lru_cache
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from core.db.session import Database
log = logging.getLogger(__name__)
PRICES_VERIFIED = False # flip only after checking every row against the provider's page
# USD per 1M tokens: (input, output). Unverified placeholders, see the module docstring.
DEFAULT_PRICES: dict[str, tuple[float, float]] = {
"anthropic:claude-haiku": (1.0, 5.0),
"anthropic:claude-sonnet": (3.0, 15.0),
"anthropic:claude-opus": (15.0, 75.0),
"openai:gpt-4o-mini": (0.15, 0.6),
"openai:gpt-4o": (2.5, 10.0),
"scripted-priced": (1.0, 2.0), # test double (ScriptedLLM(name="scripted-priced"))
}
def price_table(
overrides: Mapping[str, list[float] | tuple[float, float]] | None = None,
) -> dict[str, tuple[float, float]]:
table = dict(DEFAULT_PRICES)
if overrides is None:
from core.config import get_settings
overrides = get_settings().model_prices
for k, v in overrides.items():
if len(v) == 2:
table[k] = (float(v[0]), float(v[1]))
return table
_warned: set[str] = set()
def price_for(model: str, table: Mapping[str, tuple[float, float]]) -> tuple[float, float] | None:
candidates = [model]
if ":" in model:
candidates.append(model.split(":", 1)[1])
best: tuple[int, tuple[float, float]] | None = None
for cand in candidates:
for prefix, price in table.items():
if cand.startswith(prefix) and (best is None or len(prefix) > best[0]):
best = (len(prefix), price)
return None if best is None else best[1]
def cost_usd(
model: str,
input_tokens: int,
output_tokens: int,
table: Mapping[str, tuple[float, float]] | None = None,
) -> float:
price = price_for(model, table if table is not None else _cached_table())
if price is None:
if model not in _warned and (input_tokens or output_tokens):
_warned.add(model)
log.warning("no price for model %s: its calls are counted as $0", model)
return 0.0
return (input_tokens * price[0] + output_tokens * price[1]) / 1_000_000
@lru_cache(maxsize=1)
def _cached_table() -> dict[str, tuple[float, float]]:
return price_table()
def reset_price_cache() -> None:
_cached_table.cache_clear()
# ------------------------------------------------------------------ persistence
def db_cost_sink(db: Database): # type: ignore[no-untyped-def]
"""A ``RunContext.cost_sink`` that adds each increment to ``runs.cost_usd`` atomically
(``cost_usd = cost_usd + x``) in its own short transaction under the tenant's RLS."""
from core.agent.runs import Run
async def sink(tenant_id: uuid.UUID, run_id: uuid.UUID, usd: float) -> None:
async with db.session(tenant_id=tenant_id) as s, s.begin():
await s.execute(update(Run).where(Run.id == run_id).values(cost_usd=Run.cost_usd + usd))
return sink
async def tenant_cost(session: AsyncSession, since: datetime) -> float:
"""Total run cost for the session's tenant (RLS) since ``since``."""
from core.agent.runs import Run
v = (
await session.execute(
select(func.coalesce(func.sum(Run.cost_usd), 0.0)).where(Run.started_at >= since)
)
).scalar_one()
return float(v or 0.0)
async def tenant_cost_totals(owner_session: AsyncSession, since: datetime) -> dict[str, float]:
"""Per-tenant totals across tenants (owner role only: used by the alert sweep)."""
from core.agent.runs import Run
rows = await owner_session.execute(
select(Run.tenant_id, func.coalesce(func.sum(Run.cost_usd), 0.0))
.where(Run.started_at >= since)
.group_by(Run.tenant_id)
)
return {str(t): float(c) for t, c in rows.all()}