Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 68 additions & 16 deletions app/nullius/prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

A row is USD per million tokens: ``input`` and ``output``, optionally
``cached`` (input a cache served), ``cache_write``, ``cache_write_1h``, and ``max_output``,
the model's output limit in tokens. A model is priced by exactly its name or
the model's output limit in tokens; and ``above``, the rates of a call whose prompt
is over a size, ``[{"tokens": 100000, "input": 0.5, ...}]`` (:func:`rates`). A model is priced by exactly its name or
not at all: a name that only starts like another's is another model.

A run reads the file; ``cli run`` fetches the list first when the run has a spending cap.
Expand All @@ -27,6 +28,7 @@
nullius prices list MODEL ... # those models' rows
nullius prices update [--from URL-or-file]
nullius prices set MODEL INPUT OUTPUT [--cached X] [--cache-write X] [--cache-write-1h X] [--max-output N]
[--above TOKENS=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H] ...]
nullius prices remove MODEL
"""
from __future__ import annotations
Expand All @@ -35,6 +37,7 @@
import contextlib
import json
import os
import re
import time
import urllib.request
from typing import Callable, Dict, Iterable, Optional, Tuple
Expand All @@ -46,6 +49,7 @@
_LISTED = {"input": "input_cost_per_token", "output": "output_cost_per_token",
"cached": "cache_read_input_token_cost", "cache_write": "cache_creation_input_token_cost",
"cache_write_1h": "cache_creation_input_token_cost_above_1hr"}
_ABOVE = re.compile(r"^(.+)_above_(\d+)(k?)_tokens$") # a listed rate past a prompt size: output_cost_per_token_above_100k_tokens
_MOST = 64 * 1024 * 1024 # a list larger than this is not a price list


Expand Down Expand Up @@ -100,14 +104,32 @@ def load(env=None) -> dict:
def problems(env=None) -> list:
"""What keeps one of the user's rows from pricing, one line each: kept as written, never dropped."""
rows, why = _own(env)
return ([why] if why else []) + [f"{n} prices nothing: set its input and output prices again"
return ([why] if why else []) + [f"{n} prices nothing: " + ("its rates past a prompt size do not read" if _rated(r)
else "set its input and output prices again")
for n, r in sorted(rows.items()) if not _usable(r)]


def _usable(r) -> bool:
return _rated(r) and ("above" not in r or isinstance(r["above"], list) and all(
isinstance(a, dict) and type(a.get("tokens")) is int and a["tokens"] > 0 and any(k in a for k in RATES)
and all(_number(a[k]) for k in RATES if k in a) for a in r["above"])
and len({a["tokens"] for a in r["above"]}) == len(r["above"])) # one set of rates a size


def _rated(r) -> bool:
return isinstance(r, dict) and all(_number(r.get(k)) for k in ("input", "output"))


def rates(r: dict, prompt: int) -> dict:
"""Row ``r``'s rates for a call whose prompt, cache reads and writes in, is ``prompt`` tokens: past each
``above`` it is over, that size's rates; a rate a size leaves out, the one below it. ``r`` itself under them all."""
out = r
for a in sorted(r.get("above") or (), key=lambda a: a["tokens"]):
if prompt > a["tokens"]:
out = {**out, **{k: a[k] for k in RATES if k in a}}
return out


def _number(v) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0

Expand All @@ -131,8 +153,9 @@ def given(names: Iterable[Optional[str]], prices: Optional[Dict[str, dict]]) ->
return {n: prices[n] for n in dict.fromkeys(n for n in names if n) if n in prices}


def row(input, output, cached=None, cache_write=None, max_output=None, *, cache_write_1h=None) -> dict:
"""One row, checked: rates are numbers not below zero, the limit a whole number above it."""
def row(input, output, cached=None, cache_write=None, max_output=None, *, cache_write_1h=None, above=()) -> dict:
"""One row, checked: rates are numbers not below zero, the limit a whole number above it.
``above``: ``TOKENS=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]`` each, the rates of a prompt over TOKENS."""
out = {}
for name, v in (("input", input), ("output", output), ("cached", cached), ("cache_write", cache_write), ("cache_write_1h", cache_write_1h)):
if v is None:
Expand All @@ -152,25 +175,43 @@ def row(input, output, cached=None, cache_write=None, max_output=None, *, cache_
if n <= 0:
raise ValueError(f"max_output: the model's output limit in tokens, not {max_output!r}")
out["max_output"] = n
sizes = []
for size in above or ():
tokens, eq, rest = str(size).partition("=")
bits = [b.strip() for b in rest.split(",")] if eq else []
if not tokens.strip().isdecimal() or not int(tokens) > 0 or not 2 <= len(bits) <= 5 or not all(bits[:2]):
raise ValueError(f"above {size!r}: TOKENS=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H], a prompt size and its rates")
if int(tokens) in (a["tokens"] for a in sizes):
raise ValueError(f"above {size!r}: a second set of rates for {int(tokens)} tokens")
sizes.append({"tokens": int(tokens), **row(**{k: v or None for k, v in zip(RATES, bits)})})
if sizes:
out["above"] = sorted(sizes, key=lambda a: a["tokens"])
return out


def parse(text: str) -> Tuple[str, dict]:
"""``MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]``, a run's ``--price``.
Optional rates may be left empty; existing two/three-rate rows keep their meaning."""
"""``MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...]``, a run's ``--price``: after
each ``/``, the rates of a prompt over TOKENS. Optional rates may be left empty; existing two/three-rate rows keep their meaning."""
name, eq, rest = str(text).partition("=")
bits = [b.strip() for b in rest.split(",")] if eq else []
first, *sizes = rest.split("/")
bits = [b.strip() for b in first.split(",")] if eq else []
if not name.strip() or not 2 <= len(bits) <= 5 or not all(bits[:2]):
raise ValueError(f"--price {text!r}: MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H], in USD per million tokens")
raise ValueError(f"--price {text!r}: MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...], in USD per million tokens")
try:
return name.strip(), row(**{k: v or None for k, v in zip(RATES, bits)})
return name.strip(), row(**{k: v or None for k, v in zip(RATES, bits)}, above=sizes)
except ValueError as e:
raise ValueError(f"--price {text!r}: {e}")


def text(r: dict) -> str:
"""Row ``r`` as ``--price`` takes it after ``MODEL=``, each size with the rates it prices at."""
said = lambda x: ",".join(str(x.get(k, "")) for k in RATES).rstrip(",")
return "/".join([said(r)] + [f"{a['tokens']}={said(rates(r, a['tokens'] + 1))}" for a in r.get("above") or ()])


def convert(listing) -> Dict[str, dict]:
"""LiteLLM's list as rows: its costs are per token, a row's per million.
An entry with no input price is not a priced model (the list's own
"""LiteLLM's list as rows: its costs are per token, a row's per million; its
``..._above_<N>k_tokens`` costs, a row's ``above``. An entry with no input price is not a priced model (the list's own
sample, an image model priced per picture) and is left out."""
if not isinstance(listing, dict):
raise ValueError("not a price list: a JSON object of models was expected")
Expand All @@ -183,6 +224,15 @@ def convert(listing) -> Dict[str, dict]:
for k in ("cached", "cache_write", "cache_write_1h"):
if _number(e.get(_LISTED[k])):
r[k] = round(e[_LISTED[k]] * 1e6, 6)
sizes = {}
for key, v in e.items(): # a size is named by any of its rates, not by the input's alone
over = _ABOVE.match(key)
rate = next((k for k in RATES if _LISTED[k] == over.group(1)), None) if over else None
if rate and _number(v) and int(over.group(2)) > 0: # a size of none is no size: left out, the row kept
tokens = int(over.group(2)) * (1000 if over.group(3) else 1)
sizes.setdefault(tokens, {"tokens": tokens})[rate] = round(v * 1e6, 6)
if sizes:
r["above"] = [sizes[n] for n in sorted(sizes)]
limit = e.get("max_output_tokens")
if isinstance(limit, int) and not isinstance(limit, bool) and limit > 0:
r["max_output"] = limit
Expand Down Expand Up @@ -268,12 +318,12 @@ def state(env=None) -> dict:


def said(name: str, r: dict) -> str:
bits = [f"input {r['input']:g}", f"output {r['output']:g}"]
bits += [f"{label} {r[k]:g}" for k, label in (("cached", "cached"), ("cache_write", "cache write"),
("cache_write_1h", "cache write 1h")) if k in r]
each = lambda x: [f"{label} {x[k]:g}" for k, label in (("input", "input"), ("output", "output"), ("cached", "cached"),
("cache_write", "cache write"), ("cache_write_1h", "cache write 1h")) if k in x]
bits = each(r)
if "max_output" in r:
bits.append(f"output limit {r['max_output']}")
return f"{name}: " + ", ".join(bits)
return f"{name}: " + "; ".join([", ".join(bits)] + [f"over {a['tokens']} tokens, " + ", ".join(each(a)) for a in r.get("above") or ()])


def main(argv=None) -> int:
Expand All @@ -293,6 +343,8 @@ def main(argv=None) -> int:
st.add_argument("--cache-write")
st.add_argument("--cache-write-1h")
st.add_argument("--max-output")
st.add_argument("--above", action="append", metavar="TOKENS=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]",
help="the rates of a call whose prompt, cache reads and writes in, is over TOKENS (repeatable)")
rm = sub.add_parser("remove", help="remove one of the user's own prices")
rm.add_argument("model")
a = ap.parse_args(argv)
Expand All @@ -302,7 +354,7 @@ def main(argv=None) -> int:
print(f"{got['n']} models priced, from {got['from']}")
return 0
if a.cmd == "set":
r = row(a.input, a.output, a.cached, a.cache_write, a.max_output, cache_write_1h=a.cache_write_1h)
r = row(a.input, a.output, a.cached, a.cache_write, a.max_output, cache_write_1h=a.cache_write_1h, above=a.above)
set_own(a.model, r)
print(said(a.model.strip(), r))
return 0
Expand Down
5 changes: 3 additions & 2 deletions app/nullius/standard/calls/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
import uuid
from typing import Optional, Tuple

from nullius import ondisk
from nullius import ondisk, prices

OUTPUT = 4096 # output tokens booked for a call before the run has had a reply from its model
ERROR = "SpendingCapError" # what a unit the cap ended carries: its own outcome outside the rate, never a miss (runs.classify)
Expand Down Expand Up @@ -85,13 +85,14 @@ def unit_of(tag: str) -> Optional[str]:

def bound(req: dict, raw: bytes, row: dict, path: str = "", seen: Optional[int] = None, output: bool = True) -> float:
"""What a call is likely to cost, in USD, at ``row`` (a price row, USD
per million tokens). Input: the request's characters over three - its
per million tokens), at its rates for a prompt that size (``prices.rates``). Input: the request's characters over three - its
JSON whole, less what it carries as base64 - at the dearer of the input
and the cache-write price. Output: ``seen``, the average reply the run
has had from this model, or ``OUTPUT`` before any; never more than the
limit the call names or the row's own. An embeddings call has none.
``output`` False: the request alone, which is no guess."""
tokens = math.ceil(max(0, len(raw) - _blobs(req)) / 3)
row = prices.rates(row, tokens)
rate = max(row["input"], row.get("cache_write") or 0, row.get("cache_write_1h") or 0)
out = 0
if output and not path.split("?")[0].endswith("/embeddings"):
Expand Down
2 changes: 2 additions & 0 deletions app/nullius/standard/calls/relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Dict, List, Optional

from nullius import prices as price_list
from nullius.redact import redact
from nullius.standard.calls import exchanges as exchange_store, ledger as ledgers

Expand Down Expand Up @@ -853,6 +854,7 @@ def _cost(self, model: str, usage: Optional[dict]):
p = self.prices.get(model) # exactly this model: one whose name only starts the same is another
if not p:
return None, None
p = price_list.rates(p, usage["input"]) # the rates of a prompt this size: input counts every prompt token
written = min(usage.get("cache_write") or 0, max(0, usage["input"] - usage["cached"]))
hour = min(usage.get("cache_write_1h") or 0, written)
fresh = max(0, usage["input"] - usage["cached"] - written)
Expand Down
10 changes: 5 additions & 5 deletions app/nullius/standard/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
PYTHONPATH=app python3 -m nullius.standard.cli new benchmark|agent|capability KEY [--family F] [--port P]
PYTHONPATH=app python3 -m nullius.standard.cli new version KEY VERSION
PYTHONPATH=app python3 -m nullius.standard.cli conform AGENT|CAPABILITY --model M [--provider P] [--port PORT ...] [--attempts K] [--option NAME=VALUE ...] [--unsandboxed | --backend container | --backend boat]
PYTHONPATH=app python3 -m nullius.standard.cli run BENCHMARK[@VERSION] AGENT|CAPABILITY --model M [--provider P] [--units FILE] [--limit N] [-j N] [--option NAME=VALUE ...] [--bench-option NAME=VALUE ...] [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H] ...] [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS ...] [--max-turns N] [--max-calls N] [--constraint KEY=VALUE ...] [--served-by [MODEL=]SLUG[,SLUG...] ...] [--exchanges whole|text|off] [--exchanges-max-mb N] [--unsandboxed | --backend container | --backend boat [--boat-size SIZE]]
PYTHONPATH=app python3 -m nullius.standard.cli run BENCHMARK[@VERSION] AGENT|CAPABILITY --model M [--provider P] [--units FILE] [--limit N] [-j N] [--option NAME=VALUE ...] [--bench-option NAME=VALUE ...] [--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...] ...] [--max-usd USD] [--max-usd-per-unit USD] [--timeout PHASE=SECONDS ...] [--max-turns N] [--max-calls N] [--constraint KEY=VALUE ...] [--served-by [MODEL=]SLUG[,SLUG...] ...] [--exchanges whole|text|off] [--exchanges-max-mb N] [--unsandboxed | --backend container | --backend boat [--boat-size SIZE]]
PYTHONPATH=app python3 -m nullius.standard.cli run BENCHMARK[@VERSION] nop|oracle [--dataset D] [--units FILE] [--limit N]
PYTHONPATH=app python3 -m nullius.standard.cli prove BENCHMARK[@VERSION] [--dataset D] [--limit N] [--bench-option NAME=VALUE ...] [--job nop|oracle=JOB_DIR ...]
PYTHONPATH=app python3 -m nullius.standard.cli run ... --shard I/N [--launch ID]
Expand Down Expand Up @@ -514,7 +514,7 @@ def constraint_values(pairs) -> dict:


def prices(given) -> dict:
"""``--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]``, repeatable: this run's own prices, over the user's list."""
"""``--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...]``, repeatable: this run's own prices, over the user's list."""
out = {}
for p in given or []:
try:
Expand Down Expand Up @@ -695,7 +695,7 @@ def _boat_units(a, b, other) -> int:
explicit = prices(a.price)
for model, row in price_list.given(models, price_list.table()).items():
if model not in explicit:
words += ["--price", model + "=" + ",".join(str(row.get(k, "")) for k in price_list.RATES).rstrip(",")]
words += ["--price", model + "=" + price_list.text(row)]
if a.remove_images:
words.append("--remove-images")
try:
Expand Down Expand Up @@ -1140,8 +1140,8 @@ def main(argv=None):
p.add_argument("--launch", help="the launch id every shard records (default: the day, the benchmark, the agent, the model)")
p.add_argument("--bench-option", action="append", metavar="NAME=VALUE",
help="one of the benchmark's own options (repeatable: a search, a mode); the rest keep their defaults")
p.add_argument("--price", action="append", metavar="MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]",
help="this run's price for a model in USD per million tokens, over your price list (repeatable; nullius prices)")
p.add_argument("--price", action="append", metavar="MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...]",
help="this run's price for a model in USD per million tokens, over your price list; after each /, the rates of a prompt over TOKENS (repeatable; nullius prices)")
p.add_argument("--max-usd", type=float, metavar="USD",
help="the run's spending cap: no call goes out once the spend plus the calls in flight would pass it")
p.add_argument("--constraint", action="append", metavar="KEY=VALUE",
Expand Down
Loading
Loading