Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_unit_prices.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_unit_prices.py · 6.1 KB · 162 lines
1"""Media pricing: what one image or one second of video costs.
2
3`ai_prices` prices a token: input_per_million / output_per_million, and
4object_ai.compute_cost_cents multiplies. Media cannot be expressed in
5that shape at all, and pretending otherwise is how a $6.00 run gets
6quoted at zero.
7
8 images (model, quality, size) -> cents per image
9 video (model, size) -> cents per second
10
11Two things follow from those tuples, and both are the point of this
12module existing separately rather than as another column on ai_prices:
13
14**A price is a LOOKUP, not a rate.** There is no arithmetic that turns
15gpt-image-2 at 1024x1024 into gpt-image-2 at 1536x1024; they are
16different products with different prices, published as a table. So this
17module looks up a row and refuses when there is no row, rather than
18interpolating, defaulting, or falling back to a cheaper neighbour --
19every one of which would quote a price the provider will not honour.
20
21**The quote must exist BEFORE the call.** A media run is held against the
22wallet at queue time, so the price has to be knowable from the request
23alone: model, quality, size, and (for video) duration. That is why
24`quote` takes a spec dict rather than a provider response. A run whose
25price cannot be computed in advance is a run that cannot be held, and it
26must be refused at submission rather than discovered afterwards -- the
27whole reason holds exist.
28
29Integer minor units throughout (doctrine #10). Video is the interesting
30case: per-second pricing times a fractional duration must not lose
31money to truncation, so seconds are carried as Decimal and the product
32is rounded HALF UP to the cent at the end, once.
33"""
34
35from __future__ import annotations
36
37from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
38from typing import Any, Iterable
39
40UNIT_PRICES_COLLECTION = "unit_prices"
41
42#: What each kind is priced per. `image` is a flat per-item price;
43#: `video` multiplies by duration_seconds.
44PER_ITEM_KINDS = ("image",)
45PER_SECOND_KINDS = ("video", "audio")
46
47#: The dimensions that identify a price row, per kind. Order matters
48#: only for the message a refusal prints.
49KIND_DIMENSIONS = {
50 "image": ("model", "quality", "size"),
51 "video": ("model", "size"),
52 "audio": ("model",),
53}
54
55
56def _text(value: Any) -> str:
57 return str(value if value is not None else "").strip()
58
59
60def _decimal(value: Any) -> Decimal | None:
61 text = _text(value)
62 if not text:
63 return None
64 try:
65 return Decimal(text)
66 except InvalidOperation:
67 return None
68
69
70def find_price(rows: Iterable[dict], spec: dict) -> dict | None:
71 """The price row matching a spec's dimensions, or None.
72
73 Matching is exact on every dimension the kind declares. A row whose
74 dimension is BLANK is a wildcard for that dimension -- which is how a
75 provider that charges one price for every size is expressed without
76 enumerating sizes -- but an exact match always wins over a wildcard,
77 so adding a specific row later overrides the catch-all without
78 having to delete it.
79 """
80 kind = _text(spec.get("kind"))
81 dimensions = KIND_DIMENSIONS.get(kind)
82 if dimensions is None:
83 return None
84
85 exact, wildcard = None, None
86 for row in rows or ():
87 if _text(row.get("kind")) != kind:
88 continue
89 specificity = 0
90 matched = True
91 for name in dimensions:
92 wanted = _text(spec.get(name))
93 have = _text(row.get(name))
94 if not have:
95 continue # wildcard on this dimension
96 if have != wanted:
97 matched = False
98 break
99 specificity += 1
100 if not matched:
101 continue
102 if specificity == len(dimensions):
103 exact = row
104 break
105 if wildcard is None or specificity > wildcard[0]:
106 wildcard = (specificity, row)
107 if exact is not None:
108 return exact
109 return wildcard[1] if wildcard else None
110
111
112def quote(rows: Iterable[dict], spec: dict) -> dict:
113 """Price one media request in advance.
114
115 Returns {"price_cents": int, "price_row_id": str, "detail": str} or
116 {"error": str} -- and the error is deliberately a value rather than
117 an exception, because "we cannot price this" is a normal answer that
118 a submission path must turn into a 409 naming what to configure, not
119 an exceptional one.
120 """
121 kind = _text(spec.get("kind"))
122 if kind not in KIND_DIMENSIONS:
123 return {"error": (f"No pricing for media kind {kind!r}. Known kinds: "
124 f"{', '.join(sorted(KIND_DIMENSIONS))}.")}
125
126 quantity = _decimal(spec.get("quantity"))
127 if quantity is None:
128 quantity = Decimal("1")
129 if quantity <= 0:
130 return {"error": "quantity must be positive"}
131
132 row = find_price(rows, spec)
133 if row is None:
134 named = ", ".join(f"{name}={_text(spec.get(name)) or '?'}"
135 for name in KIND_DIMENSIONS[kind])
136 return {"error": (f"No unit price for {kind} ({named}). Add a "
137 f"{UNIT_PRICES_COLLECTION} row before running this "
138 f"-- a media run is held against the wallet at "
139 f"submission, so an unpriced model cannot be run "
140 f"rather than being billed after the fact.")}
141
142 unit = _decimal(row.get("unit_price_cents"))
143 if unit is None or unit < 0:
144 return {"error": (f"Unit price row {row.get('id')!r} has no usable "
145 f"unit_price_cents.")}
146
147 if kind in PER_SECOND_KINDS:
148 seconds = _decimal(spec.get("duration_seconds"))
149 if seconds is None or seconds <= 0:
150 return {"error": (f"{kind} is priced per second, so "
151 f"duration_seconds is required to quote it in "
152 f"advance.")}
153 total = unit * seconds * quantity
154 detail = (f"{seconds}s x {quantity} @ {unit}c/s")
155 else:
156 total = unit * quantity
157 detail = f"{quantity} x {unit}c"
158
159 cents = int(total.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
160 return {"price_cents": cents,
161 "price_row_id": _text(row.get("id")),
162 "detail": detail}