diff --git a/app/nullius/prices.py b/app/nullius/prices.py index 934d3e93..c79011d5 100644 --- a/app/nullius/prices.py +++ b/app/nullius/prices.py @@ -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. @@ -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 @@ -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 @@ -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 @@ -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 @@ -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: @@ -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_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") @@ -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 @@ -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: @@ -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) @@ -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 diff --git a/app/nullius/standard/calls/ledger.py b/app/nullius/standard/calls/ledger.py index 6eb85de8..1d4b7eca 100644 --- a/app/nullius/standard/calls/ledger.py +++ b/app/nullius/standard/calls/ledger.py @@ -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) @@ -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"): diff --git a/app/nullius/standard/calls/relay.py b/app/nullius/standard/calls/relay.py index 34c2bdcf..2908c7ec 100644 --- a/app/nullius/standard/calls/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -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 @@ -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) diff --git a/app/nullius/standard/cli.py b/app/nullius/standard/cli.py index 7e9e2d01..4539bb59 100644 --- a/app/nullius/standard/cli.py +++ b/app/nullius/standard/cli.py @@ -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] @@ -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: @@ -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: @@ -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", diff --git a/app/tests/test_prices.py b/app/tests/test_prices.py index 9ae50e5b..7fd22bed 100644 --- a/app/tests/test_prices.py +++ b/app/tests/test_prices.py @@ -18,10 +18,13 @@ LISTING = { "sample_spec": {"input_cost_per_token": "a number", "max_output_tokens": "a number"}, "model-a": {"input_cost_per_token": 2.5e-06, "output_cost_per_token": 1e-05, "cache_read_input_token_cost": 1.25e-06, - "max_output_tokens": 16384, "litellm_provider": "one"}, + "max_output_tokens": 16384, "litellm_provider": "one", "output_cost_per_token_above_100k_tokens": 2e-05}, "model-b": {"input_cost_per_token": 3e-06, "output_cost_per_token": 1.5e-05, "cache_read_input_token_cost": 3e-07, - "cache_creation_input_token_cost": 3.75e-06, "cache_creation_input_token_cost_above_1hr": 6e-06, "max_output_tokens": 128000}, - "embedder": {"input_cost_per_token": 2e-08, "output_cost_per_token": 0.0}, + "cache_creation_input_token_cost": 3.75e-06, "cache_creation_input_token_cost_above_1hr": 6e-06, "max_output_tokens": 128000, + "input_cost_per_token_above_200k_tokens": 6e-06, "output_cost_per_token_above_200k_tokens": 2.25e-05, + "cache_read_input_token_cost_above_200k_tokens": 6e-07, "cache_creation_input_token_cost_above_200k_tokens": 7.5e-06, + "cache_creation_input_token_cost_above_1hr_above_200k_tokens": 1.2e-05, "input_cost_per_token_above_200k_tokens_priority": 1e-05}, + "embedder": {"input_cost_per_token": 2e-08, "output_cost_per_token": 0.0, "input_cost_per_token_above_0k_tokens": 4e-08}, "picture-model": {"output_cost_per_image": 0.04}, } @@ -63,8 +66,9 @@ def test_the_list_is_kept_per_million_tokens_with_its_source_and_day(self): got = prices.update(fetch=self.fetch(), today="2026-11-10") self.assertEqual(got, {"n": 3, "from": prices.SOURCE, "on": "2026-11-10"}) self.assertEqual(prices.table(), { - "model-a": {"input": 2.5, "output": 10.0, "cached": 1.25, "max_output": 16384}, - "model-b": {"input": 3.0, "output": 15.0, "cached": 0.3, "cache_write": 3.75, "cache_write_1h": 6.0, "max_output": 128000}, + "model-a": {"input": 2.5, "output": 10.0, "cached": 1.25, "max_output": 16384, "above": [{"tokens": 100000, "output": 20.0}]}, + "model-b": {"input": 3.0, "output": 15.0, "cached": 0.3, "cache_write": 3.75, "cache_write_1h": 6.0, "max_output": 128000, + "above": [{"tokens": 200000, "input": 6.0, "output": 22.5, "cached": 0.6, "cache_write": 7.5, "cache_write_1h": 12.0}]}, "embedder": {"input": 0.02, "output": 0.0}}) self.assertEqual(prices.path(), os.path.join(self.tmp, "config", "prices.json")) @@ -117,10 +121,12 @@ def test_the_users_own_price_wins_and_survives_an_update(self): prices.update(fetch=self.fetch()) prices.set_own("model-a", prices.row(1, 2)) prices.set_own("my-gateway/model", prices.row("0.5", "1.5", cached="0.05", max_output="4096")) + prices.set_own("long", prices.row(0.1, 0.5, above=["100000=0.5,2.5"])) prices.update(fetch=self.fetch()) t = prices.table() self.assertEqual(t["model-a"], {"input": 1.0, "output": 2.0}) self.assertEqual(t["my-gateway/model"], {"input": 0.5, "output": 1.5, "cached": 0.05, "max_output": 4096}) + self.assertEqual(t["long"], {"input": 0.1, "output": 0.5, "above": [{"tokens": 100000, "input": 0.5, "output": 2.5}]}) self.assertTrue(prices.remove_own("model-a")) self.assertFalse(prices.remove_own("model-a")) self.assertEqual(prices.table()["model-a"]["input"], 2.5) # the list's again @@ -140,10 +146,28 @@ def test_a_runs_price_is_model_input_output_and_optionally_cached(self): self.assertEqual(prices.parse("m=1,2,0.1,1.25,2"), ("m", {"input": 1.0, "output": 2.0, "cached": 0.1, "cache_write": 1.25, "cache_write_1h": 2.0})) self.assertEqual(prices.parse("m=1,2,,1.25")[1], {"input": 1.0, "output": 2.0, "cache_write": 1.25}) - for bad in ("m", "m=1", "=1,2", "m=1,2,3,4,5,6", "m=1,x", "m=1,", "m=-1,2", "m=1,2,,1,-2"): + self.assertEqual(prices.parse("m=0.1,0.5,0.01,0.125,0.2/100000=0.5,2.5,0.05,0.625,1")[1], + {"input": 0.1, "output": 0.5, "cached": 0.01, "cache_write": 0.125, "cache_write_1h": 0.2, + "above": [{"tokens": 100000, "input": 0.5, "output": 2.5, "cached": 0.05, "cache_write": 0.625, "cache_write_1h": 1.0}]}) + self.assertEqual(prices.parse("org/m=1,2/300=4,8/100=2,4")[1]["above"], + [{"tokens": 100, "input": 2.0, "output": 4.0}, {"tokens": 300, "input": 4.0, "output": 8.0}]) + for bad in ("m", "m=1", "=1,2", "m=1,2,3,4,5,6", "m=1,x", "m=1,", "m=-1,2", "m=1,2,,1,-2", + "m=1,2/", "m=1,2/100", "m=1,2/100=1", "m=1,2/0=1,2", "m=1,2/x=1,2", "m=1,2/100=-1,2", "m=1,2/100=1,2/100=3,4"): with self.assertRaises(ValueError, msg=bad): prices.parse(bad) + def test_over_a_rows_size_a_call_is_priced_at_its_rates_and_a_rate_it_leaves_out_is_the_one_below(self): + r = prices.row(1, 2, cached=0.1, above=["300=9,18,,20", "100=5,10"]) + self.assertIs(prices.rates(r, 100), r) # at the size, not over it: the row's own + rated = lambda n, row=r: {k: prices.rates(row, n).get(k) for k in prices.RATES} + self.assertEqual(rated(101), {"input": 5.0, "output": 10.0, "cached": 0.1, "cache_write": None, "cache_write_1h": None}) + self.assertEqual(rated(301), {"input": 9.0, "output": 18.0, "cached": 0.1, "cache_write": 20.0, "cache_write_1h": None}) + between = prices.row(1, 2, cached=0.1, above=["100=5,10,0.5", "300=9,18"]) + self.assertEqual(prices.rates(between, 301)["cached"], 0.5) # left out past 300: the rate past 100, not the row's + again = prices.parse("m=" + prices.text(r))[1] # a row as --price takes it reads back the same + self.assertEqual([rated(n, again) for n in (100, 101, 301)], [rated(n) for n in (100, 101, 301)]) + self.assertEqual(prices.text({"input": 1.0, "output": 2.0, "cache_write": 1.25}), "1.0,2.0,,1.25") # without a size, as before + def test_another_file_is_named_by_the_environment(self): other = os.path.join(self.tmp, "sent", "prices.json") with mock.patch.dict(os.environ, {"NULLIUS_PRICES": other}): @@ -223,10 +247,24 @@ def test_a_list_of_before_is_read_for_both_and_its_rows_move_at_their_first_chan def test_a_row_that_cannot_price_is_kept_and_said(self): os.makedirs(os.path.dirname(prices.own_path())) + sized = lambda above, **more: {"input": 1, "output": 2, **more, "above": above} + priced = {"output": sized([{"tokens": 100, "output": 10}]), "cache": sized([{"tokens": 100, "cached": 0.5}], cached=0.1)} + unread = {"sized": [{"tokens": "100", "input": 5}], "bare": [{"tokens": 100}], "word": [{"tokens": 100, "output": "bad"}], + "twice": [{"tokens": 100, "input": 5}, {"tokens": 100, "input": 9}], "zero": [{"tokens": 0, "output": 10}], + "negative": [{"tokens": -1, "output": 10}], "boolean": [{"tokens": True, "output": 10}], + "null": None, "object": {"tokens": 100, "output": 10}} with open(prices.own_path(), "w") as f: - json.dump({"own": {"typo": {"input": "1", "output": 2}, "fine": {"input": 1, "output": 2}}}, f) - self.assertEqual(prices.table(), {"fine": {"input": 1, "output": 2}}) - self.assertEqual(prices.state()["problems"], ["typo prices nothing: set its input and output prices again"]) + json.dump({"own": {"typo": {"input": "1", "output": 2}, "fine": {"input": 1, "output": 2}, **priced, + **{n: sized(above) for n, above in unread.items()}}}, f) + self.assertEqual(prices.table(), {"fine": {"input": 1, "output": 2}, **priced}) + self.assertEqual(prices.state()["problems"], sorted([f"{n} prices nothing: its rates past a prompt size do not read" for n in unread] + + ["typo prices nothing: set its input and output prices again"])) + alone = prices.table()["output"] # a size may leave out the input rate too + self.assertEqual({k: prices.rates(alone, 101)[k] for k in ("input", "output")}, {"input": 1, "output": 10}) + self.assertEqual([prices.rates(prices.table()["cache"], n)["cached"] for n in (100, 101)], [0.1, 0.5]) # or give a cache rate alone + self.assertEqual(prices.parse("m=" + prices.text(alone))[1]["above"], [{"tokens": 100, "input": 1.0, "output": 10.0}]) + for n in unread: # each kept as written + self.assertTrue(prices.remove_own(n)) prices.set_own("more", prices.row(3, 4)) with open(prices.own_path()) as f: self.assertEqual(json.load(f)["own"]["typo"], {"input": "1", "output": 2}) # still there @@ -280,6 +318,9 @@ def test_set_list_and_remove(self): self.assertEqual(prices.table()["m"], {"input": 1.0, "output": 2.0, "cache_write": 1.25, "cache_write_1h": 2.0}) self.assertEqual(prices.table()["old"], {"input": 1.0, "output": 2.0}) self.assertIn("cache write 1h 2", self.say("list", "m")[1]) + self.assertEqual(self.say("set", "h", "0.1", "0.5", "--above", "100000=0.5,2.5")[0], 0) + self.assertEqual(prices.table()["h"]["above"], [{"tokens": 100000, "input": 0.5, "output": 2.5}]) + self.assertIn("own h: input 0.1, output 0.5; over 100000 tokens, input 0.5, output 2.5", self.say("list")[1]) with open(prices.own_path()) as f: doc = json.load(f) doc["own"]["typo"] = {"input": 1} diff --git a/app/tests/test_standard_relay.py b/app/tests/test_standard_relay.py index b5c107c0..416e7a6a 100644 --- a/app/tests/test_standard_relay.py +++ b/app/tests/test_standard_relay.py @@ -6,6 +6,7 @@ import base64 import http.client import json +import math import os import shutil import socket @@ -325,10 +326,10 @@ def setUpClass(cls): def tearDownClass(cls): cls.up.shutdown() - def capped(self, cap): + def capped(self, cap, prices=None): tmp = tempfile.mkdtemp() led = ledger.Ledger.create(os.path.join(tmp, "ledger", "ledger.json"), cap) - r = relay.Relay(self.base, "sk-real", os.path.join(tmp, "relay"), prices=self.PRICES, ledger=led.path).start() + r = relay.Relay(self.base, "sk-real", os.path.join(tmp, "relay"), prices=prices or self.PRICES, ledger=led.path).start() self.addCleanup(r.stop) return r, led @@ -414,6 +415,25 @@ def test_a_call_is_booked_at_what_the_runs_replies_have_been_once_one_came_back( self.assertAlmostEqual(second["booked_usd"], ledger.bound(body, raw, self.PRICES["m"], seen=first["reply"]["usage"]["output"])) self.assertLess(second["booked_usd"], first["booked_usd"]) + def test_a_call_over_a_prices_size_is_booked_at_its_rates_and_not_sent_when_they_pass_the_cap(self): + """The same request under the same cap: let out at the first rates, refused before it is sent at the second; + under a cap that holds it, booked at the second, its output too.""" + body = {"model": "m", "messages": [{"role": "user", "content": "x" * 3000}]} + sized = {"m": dict(self.PRICES["m"], above=[{"tokens": 100, "input": 5.0, "output": 50.0}])} + least = ledger.bound(body, json.dumps(body).encode(), self.PRICES["m"], output=False) + self.assertAlmostEqual(ledger.bound(body, json.dumps(body).encode(), sized["m"], output=False), 5 * least) + sent = len(Upstream.seen) + r, _ = self.capped(2 * least) + self.assertEqual(self.post(r, "u1", body)[0], 200) + r, led = self.capped(2 * least, sized) + status, headers, _ = self.post(r, "u1", body) + self.assertEqual((status, headers.get("X-Nullius-Refused"), r.calls("u1")[-1]["refused"]), (402, "cap", "cap")) + self.assertEqual((len(Upstream.seen), led.state()["spent_usd"]), (sent + 1, 0.0)) + r, _ = self.capped(1.0, sized) + self.assertEqual(self.post(r, "u1", body)[0], 200) + raw = json.dumps(body).encode() # by hand: its characters over three, and the output booked before a reply + self.assertAlmostEqual(r.calls("u1")[-1]["booked_usd"], (math.ceil(len(raw) / 3) * 5.0 + ledger.OUTPUT * 50.0) / 1e6) + def test_a_units_own_cap_refuses_its_calls_and_its_simulated_users_not_its_judges_nor_another_units(self): tmp = tempfile.mkdtemp() led = ledger.Ledger.create(os.path.join(tmp, "ledger", "ledger.json"), None, 0.0005) @@ -954,6 +974,17 @@ def test_mixed_cache_lifetimes_reach_cost_ledger_totals_and_spans(self): self.assertAlmostEqual(r._cost("m", normalized)[0], (2048 * 3 + 1800 * 0.3 + 248 * 3.75 + 503 * 15) / 1e6) self.assertEqual(r._cost("m", dict(normalized, cost=0.02)), (0.02, "provider")) + def test_a_prompt_over_a_prices_size_is_priced_wholly_at_its_rates_its_cache_reads_and_writes_counted(self): + """A prompt of 100,000 tokens is priced at the first rates, one of 100,001 at the second, every part of it.""" + row = {"input": 0.1, "output": 0.5, "cached": 0.01, "cache_write": 0.125, + "above": [{"tokens": 100000, "input": 0.5, "output": 2.5, "cached": 0.05, "cache_write": 0.625}]} + r = self.relay(model="m", prices={"m": row}) + for written, (fresh, read, write, out) in ((39990, (0.1, 0.01, 0.125, 0.5)), (39991, (0.5, 0.05, 0.625, 2.5))): + usage = {"input_tokens": 10, "cache_read_input_tokens": 60000, "cache_creation_input_tokens": written, "output_tokens": 1000} + with mock.patch.dict(MSG, usage=usage): + self.assertEqual(self.post(r, "u", "/messages", {"model": "m", "max_tokens": 1000, "messages": []})[0], 200) + self.assertAlmostEqual(r.calls("u")[-1]["cost_usd"], (10 * fresh + 60000 * read + written * write + 1000 * out) / 1e6) + def test_anthropic_messages_streamed(self): r = self.relay(model="claude-x", key_header="x-api-key") _, _, body = self.post(r, "u", "/messages", {"model": "claude-x", "stream": True, "messages": []}, diff --git a/app/ui_tests/test_settings_page.py b/app/ui_tests/test_settings_page.py index 1c73464d..bd47b429 100644 --- a/app/ui_tests/test_settings_page.py +++ b/app/ui_tests/test_settings_page.py @@ -1137,6 +1137,9 @@ def test_the_price_list_is_updated_and_priced_only_from_this_machines_browser(se r = self.client.post("/settings/prices/set", data={"model": "model-a", "input": "1", "output": "2", "cache_write": "1.25", "cache_write_1h": "2"}, headers=headers); self.addCleanup(r.close) self.assertEqual(r.json["own"]["model-a"], {"input": 1.0, "output": 2.0, "cache_write": 1.25, "cache_write_1h": 2.0}) + prices.set_own("model-a", prices.row(1, 2, above=["100000=5,10"])) # rates past a prompt size, which the form has no field for + r = self.client.post("/settings/prices/set", data={"model": "model-a", "input": "3", "output": "4"}, headers=headers); self.addCleanup(r.close) + self.assertEqual(r.json["own"]["model-a"], {"input": 3.0, "output": 4.0, "above": [{"tokens": 100000, "input": 5.0, "output": 10.0}]}) for bad in ({"model": "m", "input": "free", "output": "2"}, {"model": "m", "input": "1"}, {"model": "", "input": "1", "output": "2"}): r = self.client.post("/settings/prices/set", data=bad, headers=headers); self.addCleanup(r.close) self.assertEqual((r.status_code, r.json["ok"]), (400, False), bad) diff --git a/app/web/settings.py b/app/web/settings.py index 2eb6d71d..cbb41e45 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -389,12 +389,14 @@ def settings_prices_update(): @app.route("/settings/prices/set", methods=["POST"]) def settings_prices_set(): - """A price of the user's own for one model, over the list.""" + """A price of the user's own for one model, over the list. Its row's rates past a prompt size stay: the form has no field for them.""" _sandbox_guard("Prices are set") f = request.form try: - prices.set_own(f.get("model", ""), prices.row(f.get("input") or None, f.get("output") or None, f.get("cached") or None, - f.get("cache_write") or None, cache_write_1h=f.get("cache_write_1h") or None)) + r = prices.row(f.get("input") or None, f.get("output") or None, f.get("cached") or None, + f.get("cache_write") or None, cache_write_1h=f.get("cache_write_1h") or None) + sizes = prices.load()["own"].get(str(f.get("model", "")).strip(), {}).get("above") + prices.set_own(f.get("model", ""), {**r, "above": sizes} if sizes else r) except (ValueError, TypeError) as e: return jsonify(ok=False, error=str(e)), 400 return jsonify(ok=True, **prices.state()) diff --git a/docs/cli/run.md b/docs/cli/run.md index af192968..d010bf36 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -5,7 +5,7 @@ One benchmark and one agent, capability, control or setup, into a job. ```bash title="Run" nullius standard run [@version] [--model M] [--dataset D] [--units FILE | --set NAME] [--limit N] [-j N] \ [--unsandboxed | --backend container|boat] [--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] \ + [--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...]]... [--reasoning [MODEL=]LEVEL]... [--exchanges whole|text|off] [--exchanges-max-mb N] \ [--attempts K] [--retries N] [--remove-images] [--judge-model M] [--simulator-model M] [--name NAME] [--jobs DIR] [--provider P] @@ -34,7 +34,7 @@ nullius standard run locomo model --model gpt-4o-mini | `--boat-size` | Boat's VM size: `small` (default), `default`, `large`, `xlarge` | | `--option NAME=VALUE` | An agent's or capability's option (repeatable) | | `--bench-option NAME=VALUE` | A benchmark's option (repeatable) | -| `--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]` | This run's price for a model in USD per million tokens (repeatable), over your [price list](../settings/model-prices.md) | +| `--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...]` | This run's price for a model in USD per million tokens (repeatable), over your [price list](../settings/model-prices.md) | | `--max-usd USD`, `--max-usd-per-unit USD` | A spending cap for the run, for each unit: [below](#a-spending-cap) | | `--timeout PHASE=SECONDS`, `--max-turns N` | A unit's time limit for a phase, a conversation's most turns, forced: [below](#time-limits) | | `--max-calls N` | The most model calls a unit's agent may make: [below](#a-cap-on-model-calls) | diff --git a/docs/settings/model-prices.md b/docs/settings/model-prices.md index b5322fec..268c04f9 100644 --- a/docs/settings/model-prices.md +++ b/docs/settings/model-prices.md @@ -9,12 +9,13 @@ its list is filled once. | Rule | | | --- | --- | -| The list | LiteLLM's public `model_prices_and_context_window.json` | +| The list | LiteLLM's public `model_prices_and_context_window.json`, with its `_above_k_tokens` rates | | Fetched | Only when **Update** or `nullius prices update` asks; a run reads the saved list and never the network | | Your prices | Win over the list. Kept in a file of their own that an update never opens. A row that cannot price is kept and named until it is set again | -| One run | `--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]` on [`nullius standard run`](../cli/run.md) prices that run only, over both | +| One run | `--price MODEL=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H][/TOKENS=INPUT,OUTPUT...]` on [`nullius standard run`](../cli/run.md) prices that run only, over both | | A call's cost | The provider's own figure when its reply carries one (OpenRouter's does); else the price of exactly that model name; else none, shown as — | | Exact names | `gpt-4.1-nano` is not priced as `gpt-4.1` | +| Past a prompt size | A prompt over a row's size, cached tokens in, prices the whole call at its rates | | Recorded | A job's `config.json` keeps the prices of the models it calls, each with its source (`list`, `own`, or `run` for `--price`) | | Docker and hosts | A run on a host uses this machine's list | | An estimate | List prices, not a bill: [Metrics](../field-guide.md) | @@ -33,7 +34,8 @@ nullius prices remove my-model Optional `--price` fields may be omitted or left empty. One-hour writes use `cache_write_1h` when present, otherwise `cache_write`, then the input rate. -A reply without write-duration usage uses `cache_write`. `nullius prices set` also accepts `--cache-write` and -`--cache-write-1h`. +A reply without write-duration usage uses `cache_write`. `nullius prices set` also accepts `--cache-write`, +`--cache-write-1h` and `--above TOKENS=INPUT,OUTPUT[,CACHED,WRITE,WRITE_1H]`, which `--price` takes after a `/`. +A rate a size leaves out stays as below that size. `NULLIUS_PRICES` names another price list file; your own prices sit beside it.