@alexgreensh/token-optimizer 5.13.73 → 5.13.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -8
- package/hooks/sessionstart_runner.py +25 -0
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +20 -7
- package/skills/token-optimizer/assets/savings_story.js +10 -6
- package/skills/token-optimizer/references/cli-reference.md +9 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -2
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +3 -1
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +2 -79
- package/skills/token-optimizer/scripts/_measure/cli.py +24 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +77 -15
- package/skills/token-optimizer/scripts/_measure/install_baseline.py +157 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +16 -3
- package/skills/token-optimizer/scripts/_measure/mod_action_diagnostics.py +24 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_selftest.py +33 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +4 -4
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +2 -2
- package/skills/token-optimizer/scripts/_measure/nudge_followthrough.py +334 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +3 -0
- package/skills/token-optimizer/scripts/_measure/pilot_report.py +349 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +15 -414
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +5 -10
- package/skills/token-optimizer/scripts/_measure/routing_credit.py +60 -0
- package/skills/token-optimizer/scripts/_measure/routing_default.py +374 -0
- package/skills/token-optimizer/scripts/_measure/routing_savings.py +368 -0
- package/skills/token-optimizer/scripts/_measure/runway_all_in.py +42 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +33 -247
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_activity.py +128 -0
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +59 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -4
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -10
- package/skills/token-optimizer/scripts/hermes_doctor.py +1 -10
- package/skills/token-optimizer/scripts/hermes_install.py +1 -10
- package/skills/token-optimizer/scripts/injection.py +5 -2
- package/skills/token-optimizer/scripts/measure.py +4 -4
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""Model-routing savings realized/potential calculation.
|
|
2
|
+
|
|
3
|
+
Split out of the pricing provider: the frozen facade symbol
|
|
4
|
+
_compute_model_routing_savings delegates through routing_credit.compute,
|
|
5
|
+
which resolves this module to avoid a facade-binding recursion.
|
|
6
|
+
"""
|
|
7
|
+
from . import _compat
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def unrestricted(days=None, since=None, *, until=None):
|
|
11
|
+
"""Model-routing savings: realized (mix shift vs baseline) + potential (remaining Opus).
|
|
12
|
+
|
|
13
|
+
REALIZED: compare current model mix against the install-era baseline (snapshot
|
|
14
|
+
model_mix, else the earliest model_daily window). If the user moved tokens off
|
|
15
|
+
expensive models, the counterfactual cost (current volume spread over the
|
|
16
|
+
baseline mix) minus the current cost, both on one standardized price
|
|
17
|
+
schedule, is the estimated saving. This is the pillar that can show a
|
|
18
|
+
realized win (e.g. Opus 94% -> 67%).
|
|
19
|
+
Models priced above the baseline's costliest model (a premium model the user
|
|
20
|
+
chose) are left out of the comparison and the rest renormalized, so they do not
|
|
21
|
+
cancel a real shift toward lighter models; `premium_share` and
|
|
22
|
+
`premium_cost_usd` report them separately.
|
|
23
|
+
|
|
24
|
+
POTENTIAL: an assumption, not a measurement. A fixed share
|
|
25
|
+
(`routable_fraction`) of Opus fresh input and output is priced at the
|
|
26
|
+
Opus-to-Sonnet API rate delta. Opus usage without a class split is left out
|
|
27
|
+
and counted in `potential_unsplit_excluded_tokens`. Cache reads and
|
|
28
|
+
writes represent main-session history: switching models rebuilds that cache,
|
|
29
|
+
while routine subagent work carries its own smaller context. The result is
|
|
30
|
+
shown separately from concrete opportunities.
|
|
31
|
+
|
|
32
|
+
Realized routing prices fresh input, cache creation, cache reads and output
|
|
33
|
+
by class. Usage without a class split stays outside both comparisons and
|
|
34
|
+
their coverage, and is reported as `unsplit_tokens`. Potential uses the model's
|
|
35
|
+
own generation card for fresh input and output, and the newest Sonnet card
|
|
36
|
+
for its target.
|
|
37
|
+
The class split comes from per-day, per-model session usage.
|
|
38
|
+
|
|
39
|
+
Realized routing is a standardized family comparison: the remaining work's
|
|
40
|
+
class volumes per current family, and the same class volumes spread over the
|
|
41
|
+
baseline family shares, are valued on one fixed schedule (the newest card of
|
|
42
|
+
each family's tier) chosen independently of the window's volumes. A
|
|
43
|
+
generation change inside a family therefore cannot create routing credit.
|
|
44
|
+
The exact-card cost of the same work and its gap to the standardized value
|
|
45
|
+
are reported separately (`actual_cost_usd`, `generation_price_delta_usd`).
|
|
46
|
+
The schedule is assumed because the frozen baseline records no generations,
|
|
47
|
+
so the result is labelled "estimated".
|
|
48
|
+
|
|
49
|
+
Models with no exact rate card are unpriced, not free (an unknown Claude
|
|
50
|
+
generation does not borrow its family's price): they are left out of the
|
|
51
|
+
comparison and reported as `unpriced_models`, `unpriced_tokens` and
|
|
52
|
+
`unpriced_share`. Explicitly free tiers (":free") are left out the same way
|
|
53
|
+
and reported as `free_models`.
|
|
54
|
+
Labelled estimated (realized) and opportunity (potential). Never raises.
|
|
55
|
+
"""
|
|
56
|
+
# `zero` is returned only on no-data / error paths (no current mix, no
|
|
57
|
+
# baseline, or an exception). Label it "unavailable" so a $0 here reads as
|
|
58
|
+
# "couldn't compute" rather than a measured zero -- the success return below
|
|
59
|
+
# sets its own evidence="estimated" when comparable work remains.
|
|
60
|
+
_measure_facade = _compat.facade()
|
|
61
|
+
zero = {
|
|
62
|
+
"realized_cost_usd": 0.0, "potential_cost_usd": 0.0,
|
|
63
|
+
"potential_tokens": 0, "potential_tokens_monthly": 0,
|
|
64
|
+
"potential_billable_tokens": 0, "potential_by_class": {}, "unsplit_tokens": 0,
|
|
65
|
+
"potential_unsplit_excluded_tokens": 0,
|
|
66
|
+
"premium_models": [], "premium_share": 0.0, "premium_cost_usd": 0.0,
|
|
67
|
+
"unpriced_models": [], "unpriced_tokens": 0, "unpriced_share": 0.0,
|
|
68
|
+
"free_models": [], "free_tokens": 0,
|
|
69
|
+
"compared_share": 0.0,
|
|
70
|
+
"baseline_rate_basis": {}, "baseline_reference_priced": [],
|
|
71
|
+
"standardized_baseline_cost_usd": 0.0, "standardized_actual_cost_usd": 0.0,
|
|
72
|
+
"actual_cost_usd": 0.0, "generation_price_delta_usd": 0.0,
|
|
73
|
+
"baseline_opus_share": 0.0, "current_opus_share": 0.0,
|
|
74
|
+
"measured_baseline_opus_share": None,
|
|
75
|
+
"measured_baseline_realized_cost_usd": None,
|
|
76
|
+
"measured_baseline_source": None,
|
|
77
|
+
"measured_baseline_first_date": None,
|
|
78
|
+
"baseline_source": None, "evidence": "unavailable",
|
|
79
|
+
}
|
|
80
|
+
try:
|
|
81
|
+
window_end = {"until": until} if until else {}
|
|
82
|
+
current = _measure_facade._model_mix_shares(days=days, since=since, **window_end)
|
|
83
|
+
zero["activity_coverage"] = current.get("activity_coverage", {"complete": True, "undated_sessions": 0})
|
|
84
|
+
cur_shares = current.get("shares", {})
|
|
85
|
+
cur_total = int(current.get("total_tokens", 0) or 0)
|
|
86
|
+
if not cur_shares or cur_total <= 0:
|
|
87
|
+
return zero
|
|
88
|
+
|
|
89
|
+
from . import routing_credit
|
|
90
|
+
baseline_shares, baseline_source, baseline_stated, early_mix = routing_credit.baseline(_measure_facade)
|
|
91
|
+
if not baseline_shares:
|
|
92
|
+
return zero
|
|
93
|
+
|
|
94
|
+
# While collect is still re-reading window sessions (an older usage
|
|
95
|
+
# parser, or per-day usage not yet rebuilt), their per-class usage is
|
|
96
|
+
# incomplete and the figure would move pass to pass. Report the count
|
|
97
|
+
# instead of a number.
|
|
98
|
+
pending = _measure_facade._routing_pending_sessions(days=days, since=since, **window_end)
|
|
99
|
+
if pending:
|
|
100
|
+
return {**zero, "evidence": "pending", "pending_sessions": pending,
|
|
101
|
+
"baseline_source": baseline_source}
|
|
102
|
+
|
|
103
|
+
# Rows of per-model, per-class usage. When the DB holds none (adapters
|
|
104
|
+
# that only record model totals), the model-daily mix stands in as
|
|
105
|
+
# unsplit tokens, reported outside comparison coverage.
|
|
106
|
+
usage = _measure_facade._routing_usage_by_model(days=days, since=since, **window_end)
|
|
107
|
+
from_rows = bool(usage)
|
|
108
|
+
if not from_rows:
|
|
109
|
+
usage = {m: {"unsplit": share * cur_total} for m, share in cur_shares.items()}
|
|
110
|
+
|
|
111
|
+
# Mix keys from the model-daily fallback are already family buckets.
|
|
112
|
+
fam_of = {m: (_measure_facade._normalize_model_name(m) if from_rows else m) for m in usage}
|
|
113
|
+
rates_cache = {}
|
|
114
|
+
|
|
115
|
+
def _rates(model):
|
|
116
|
+
_measure_facade = _compat.facade()
|
|
117
|
+
if model not in rates_cache:
|
|
118
|
+
rates_cache[model] = _measure_facade._routing_class_rates(model)
|
|
119
|
+
return rates_cache[model]
|
|
120
|
+
|
|
121
|
+
# Only a model with an exact rate card is compared. A model with no card
|
|
122
|
+
# is unpriced (not free) and an explicitly free tier is not credited as a
|
|
123
|
+
# saving: both keep their token counts, are reported, and stay out of
|
|
124
|
+
# every mix and cost below.
|
|
125
|
+
priced_usage = {}
|
|
126
|
+
unpriced_by_model = {}
|
|
127
|
+
free_by_model = {}
|
|
128
|
+
unsplit_tokens = 0.0
|
|
129
|
+
potential_unsplit_excluded = 0.0
|
|
130
|
+
for m, classes in usage.items():
|
|
131
|
+
if not fam_of[m]:
|
|
132
|
+
continue
|
|
133
|
+
if _rates(m) is not None:
|
|
134
|
+
unsplit_tokens += classes.get("unsplit", 0)
|
|
135
|
+
if fam_of[m] == "opus":
|
|
136
|
+
potential_unsplit_excluded += classes.get("unsplit", 0)
|
|
137
|
+
split = {k: v for k, v in classes.items() if k != "unsplit"}
|
|
138
|
+
if sum(split.values()) > 0:
|
|
139
|
+
priced_usage[m] = split
|
|
140
|
+
continue
|
|
141
|
+
tokens = sum(classes.get(k, 0) for k in _measure_facade._ROUTING_CLASSES)
|
|
142
|
+
bucket = free_by_model if _measure_facade._routing_model_status(m) == "free" else unpriced_by_model
|
|
143
|
+
bucket[m] = bucket.get(m, 0) + tokens
|
|
144
|
+
|
|
145
|
+
fam_models = {}
|
|
146
|
+
for m in priced_usage:
|
|
147
|
+
fam_models.setdefault(fam_of[m], []).append(m)
|
|
148
|
+
fam_classes = {}
|
|
149
|
+
class_totals = {k: 0.0 for k in _measure_facade._ROUTING_CLASSES}
|
|
150
|
+
for fam, ms in fam_models.items():
|
|
151
|
+
dst = fam_classes[fam] = {k: 0.0 for k in _measure_facade._ROUTING_CLASSES}
|
|
152
|
+
for m in ms:
|
|
153
|
+
for k in _measure_facade._ROUTING_CLASSES:
|
|
154
|
+
dst[k] += priced_usage[m].get(k, 0)
|
|
155
|
+
class_totals[k] += priced_usage[m].get(k, 0)
|
|
156
|
+
pooled = sum(class_totals.values())
|
|
157
|
+
|
|
158
|
+
def _unpriced_report():
|
|
159
|
+
_measure_facade = _compat.facade()
|
|
160
|
+
return [mid for mid, _t in sorted(unpriced_by_model.items(), key=lambda kv: -kv[1])]
|
|
161
|
+
|
|
162
|
+
def _free_report():
|
|
163
|
+
_measure_facade = _compat.facade()
|
|
164
|
+
return [mid for mid, _t in sorted(free_by_model.items(), key=lambda kv: -kv[1])]
|
|
165
|
+
|
|
166
|
+
unpriced_tokens = int(sum(unpriced_by_model.values()))
|
|
167
|
+
free_tokens = int(sum(free_by_model.values()))
|
|
168
|
+
|
|
169
|
+
def _coverage_fields():
|
|
170
|
+
_measure_facade = _compat.facade()
|
|
171
|
+
total = unpriced_tokens + free_tokens + pooled + unsplit_tokens
|
|
172
|
+
return {
|
|
173
|
+
"unpriced_models": _unpriced_report(), "unpriced_tokens": unpriced_tokens,
|
|
174
|
+
"unpriced_share": round(unpriced_tokens / total, 4) if total > 0 else 0.0,
|
|
175
|
+
"free_models": _free_report(), "free_tokens": free_tokens,
|
|
176
|
+
"unsplit_tokens": int(round(unsplit_tokens)),
|
|
177
|
+
"potential_unsplit_excluded_tokens": int(round(potential_unsplit_excluded)),
|
|
178
|
+
"baseline_source": baseline_source,
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if pooled <= 0:
|
|
182
|
+
return {**zero, **_coverage_fields()}
|
|
183
|
+
|
|
184
|
+
# STANDARDIZED ROUTING VALUATION. Realized routing measures a shift of work
|
|
185
|
+
# between model families, so both arms are valued on one fixed price
|
|
186
|
+
# schedule: one rate per family and token class, chosen without looking at
|
|
187
|
+
# how much of that family ran in the window. The frozen baseline records
|
|
188
|
+
# shares by family only (no generation), so the schedule is a documented
|
|
189
|
+
# reference-card scenario: each family at the newest generation card of
|
|
190
|
+
# its tier (legacy Sonnet counts as Sonnet; a provider model stands for
|
|
191
|
+
# itself). It is the same for present and absent families, so one token of
|
|
192
|
+
# any generation changes the result only by that token's own contribution,
|
|
193
|
+
# and a generation change within a family cannot become routing credit.
|
|
194
|
+
# What the work actually cost at the exact cards used is reported
|
|
195
|
+
# separately (`actual_cost_usd`, `generation_price_delta_usd`). Because the
|
|
196
|
+
# scenario is assumed, the result is labelled estimated. A baseline that
|
|
197
|
+
# recorded generations would replace the reference card in
|
|
198
|
+
# `_fixed_family_rates` for the families it covers.
|
|
199
|
+
fam_rate_cache = {}
|
|
200
|
+
fam_rate_basis = {}
|
|
201
|
+
|
|
202
|
+
def _fixed_family_rates(fam):
|
|
203
|
+
_measure_facade = _compat.facade()
|
|
204
|
+
if fam in fam_rate_cache:
|
|
205
|
+
return fam_rate_cache[fam]
|
|
206
|
+
ref_model = _measure_facade._routing_reference_model(fam)
|
|
207
|
+
out = _rates(ref_model)
|
|
208
|
+
if out is None and fam_models.get(fam):
|
|
209
|
+
# No reference card for a family that did run: its lowest-sorted
|
|
210
|
+
# model id stands in, so the choice never depends on input order.
|
|
211
|
+
ref_model = sorted(fam_models[fam])[0]
|
|
212
|
+
out = _rates(ref_model)
|
|
213
|
+
if out is not None:
|
|
214
|
+
fam_rate_basis[fam] = f"reference:{ref_model}"
|
|
215
|
+
fam_rate_cache[fam] = out
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
def _renormalized(shares):
|
|
219
|
+
_measure_facade = _compat.facade()
|
|
220
|
+
kept = {f: s for f, s in shares.items() if s and s > 0 and _fixed_family_rates(f) is not None}
|
|
221
|
+
total = sum(kept.values())
|
|
222
|
+
return {f: s / total for f, s in kept.items()} if total > 0 else {}
|
|
223
|
+
|
|
224
|
+
base_priced = _renormalized(baseline_shares)
|
|
225
|
+
|
|
226
|
+
# Effective $/MTok of a family under the window's own class mix.
|
|
227
|
+
def _family_price(f):
|
|
228
|
+
_measure_facade = _compat.facade()
|
|
229
|
+
if pooled <= 0:
|
|
230
|
+
return 0.0
|
|
231
|
+
r = _fixed_family_rates(f)
|
|
232
|
+
return sum(class_totals[k] * r[k] for k in _measure_facade._ROUTING_CLASSES) / pooled
|
|
233
|
+
|
|
234
|
+
# Models priced above the most expensive model of the baseline are the
|
|
235
|
+
# user's own choice, not routing: they are taken out of the comparison
|
|
236
|
+
# so it measures the shift toward lighter models. Their share and cost
|
|
237
|
+
# are reported separately. A model must be dearer than the baseline's
|
|
238
|
+
# costliest family on the window's pooled mix AND on the output card:
|
|
239
|
+
# cache-read rates alone do not rank tiers across generations (Sonnet 4.6
|
|
240
|
+
# reads cache at $0.30, Opus 5.5 at $0.20), so a lighter older model is
|
|
241
|
+
# never mistaken for a premium one.
|
|
242
|
+
ceiling_fam = max(base_priced, key=_family_price, default=None)
|
|
243
|
+
baseline_ceiling = _family_price(ceiling_fam) if ceiling_fam else 0.0
|
|
244
|
+
ceiling_output = _fixed_family_rates(ceiling_fam)["output"] if ceiling_fam else 0.0
|
|
245
|
+
premium = sorted(
|
|
246
|
+
f for f in fam_classes
|
|
247
|
+
if _family_price(f) > baseline_ceiling > 0 and _fixed_family_rates(f)["output"] > ceiling_output
|
|
248
|
+
)
|
|
249
|
+
premium_share = sum(cur_shares.get(f, 0.0) for f in premium)
|
|
250
|
+
premium_cost = sum(
|
|
251
|
+
classes.get(k, 0) * _rates(m)[k]
|
|
252
|
+
for m, classes in priced_usage.items() if fam_of[m] in premium
|
|
253
|
+
for k in _measure_facade._ROUTING_CLASSES
|
|
254
|
+
) / 1_000_000
|
|
255
|
+
|
|
256
|
+
# REALIZED: the remaining work's class volumes, per current family, valued
|
|
257
|
+
# on the standardized schedule, against the same total class volumes spread
|
|
258
|
+
# over the baseline family shares on that same schedule. Only the shift
|
|
259
|
+
# between families moves the number. Never negative. Premium and unpriced
|
|
260
|
+
# models are outside both arms.
|
|
261
|
+
kept_models = [m for m in priced_usage if fam_of[m] not in premium]
|
|
262
|
+
kept_totals = {k: sum(priced_usage[m].get(k, 0) for m in kept_models) for k in _measure_facade._ROUTING_CLASSES}
|
|
263
|
+
standardized_actual = sum(
|
|
264
|
+
priced_usage[m].get(k, 0) * _fixed_family_rates(fam_of[m])[k]
|
|
265
|
+
for m in kept_models for k in _measure_facade._ROUTING_CLASSES
|
|
266
|
+
) / 1_000_000
|
|
267
|
+
standardized_baseline = sum(
|
|
268
|
+
kept_totals[k] * sum(s * _fixed_family_rates(f)[k] for f, s in base_priced.items())
|
|
269
|
+
for k in _measure_facade._ROUTING_CLASSES
|
|
270
|
+
) / 1_000_000 if base_priced else 0.0
|
|
271
|
+
# Exact-card API-equivalent cost of the same work (each model's own card).
|
|
272
|
+
actual_cost = sum(
|
|
273
|
+
priced_usage[m].get(k, 0) * _rates(m)[k] for m in kept_models for k in _measure_facade._ROUTING_CLASSES
|
|
274
|
+
) / 1_000_000
|
|
275
|
+
realized_cost = max(0.0, standardized_baseline - standardized_actual) if base_priced and kept_models else 0.0
|
|
276
|
+
|
|
277
|
+
def _realized_for_baseline(shares):
|
|
278
|
+
base = _renormalized(shares or {})
|
|
279
|
+
if not base or not kept_models:
|
|
280
|
+
return 0.0
|
|
281
|
+
baseline_cost = sum(
|
|
282
|
+
kept_totals[k] * sum(s * _fixed_family_rates(f)[k] for f, s in base.items())
|
|
283
|
+
for k in _measure_facade._ROUTING_CLASSES
|
|
284
|
+
) / 1_000_000
|
|
285
|
+
return max(0.0, baseline_cost - standardized_actual)
|
|
286
|
+
|
|
287
|
+
measured_baseline = {}
|
|
288
|
+
compared_tokens = sum(kept_totals.values())
|
|
289
|
+
window_tokens = unpriced_tokens + free_tokens + pooled + unsplit_tokens
|
|
290
|
+
|
|
291
|
+
# POTENTIAL: a fixed share of remaining Opus fresh input and output, priced
|
|
292
|
+
# at each Opus model's own card minus the current Sonnet card. It is
|
|
293
|
+
# computed apart from the realized figure: with no target card the
|
|
294
|
+
# potential is zero and the realized routing above is unaffected. Usage
|
|
295
|
+
# without a class split cannot be told apart as input or output, so it is
|
|
296
|
+
# left out and its count is reported.
|
|
297
|
+
target = _measure_facade._routing_target_model()
|
|
298
|
+
target_rates = _rates(target)
|
|
299
|
+
by_class = {k: {"tokens": 0, "usd": 0.0} for k in _measure_facade._ROUTING_CLASSES}
|
|
300
|
+
for m, classes in priced_usage.items():
|
|
301
|
+
if fam_of[m] != "opus":
|
|
302
|
+
continue
|
|
303
|
+
if target_rates is None:
|
|
304
|
+
continue
|
|
305
|
+
m_rates = _rates(m)
|
|
306
|
+
for k in ("fresh_input", "output"):
|
|
307
|
+
tok = classes.get(k, 0)
|
|
308
|
+
if tok:
|
|
309
|
+
by_class[k]["tokens"] += tok * _measure_facade._ROUTABLE_OPUS_FRACTION
|
|
310
|
+
by_class[k]["usd"] += tok * _measure_facade._ROUTABLE_OPUS_FRACTION * (m_rates[k] - target_rates[k]) / 1_000_000
|
|
311
|
+
potential_cost = max(0.0, sum(v["usd"] for v in by_class.values()))
|
|
312
|
+
potential_tokens = int(round(sum(v["tokens"] for v in by_class.values())))
|
|
313
|
+
potential_tokens_monthly = int(round(potential_tokens / max(days, 1) * 30))
|
|
314
|
+
potential_billable_tokens = int(round(sum(by_class[k]["tokens"] for k in _measure_facade._ROUTING_BILLABLE_CLASSES)))
|
|
315
|
+
opus_share = cur_shares.get("opus", 0.0)
|
|
316
|
+
|
|
317
|
+
return {
|
|
318
|
+
"activity_coverage": zero["activity_coverage"],
|
|
319
|
+
"realized_cost_usd": round(realized_cost, 4),
|
|
320
|
+
"potential_cost_usd": round(potential_cost, 4),
|
|
321
|
+
# Routable tokens cover observed fresh input and output only.
|
|
322
|
+
"potential_tokens": potential_tokens,
|
|
323
|
+
"potential_tokens_monthly": potential_tokens_monthly,
|
|
324
|
+
"potential_billable_tokens": potential_billable_tokens,
|
|
325
|
+
"potential_token_classes": [k for k in _measure_facade._ROUTING_CLASSES if by_class[k]["tokens"]],
|
|
326
|
+
"potential_by_class": {
|
|
327
|
+
k: {"tokens": int(round(v["tokens"])), "usd": round(v["usd"], 4)}
|
|
328
|
+
for k, v in by_class.items() if v["tokens"] or v["usd"]
|
|
329
|
+
},
|
|
330
|
+
"potential_basis": "api_rate_equivalent",
|
|
331
|
+
"target_model": target,
|
|
332
|
+
"pricing_basis": "per_token_class_generation_card",
|
|
333
|
+
# Premium models (priced above the baseline's costliest model) are the
|
|
334
|
+
# user's own choice: excluded from realized routing, shown here.
|
|
335
|
+
"premium_models": premium,
|
|
336
|
+
"premium_share": round(premium_share, 4),
|
|
337
|
+
"premium_cost_usd": round(premium_cost, 4),
|
|
338
|
+
# Models with no exact rate card (unpriced) and explicitly free tiers are
|
|
339
|
+
# left out of the comparison, never priced at zero or at a stand-in rate.
|
|
340
|
+
**_coverage_fields(),
|
|
341
|
+
"baseline_opus_share": round(baseline_shares.get("opus", 0.0), 4),
|
|
342
|
+
"current_opus_share": round(opus_share, 4),
|
|
343
|
+
"measured_baseline_opus_share": measured_baseline.get("opus_share"),
|
|
344
|
+
"measured_baseline_realized_cost_usd": measured_baseline.get("realized_cost_usd"),
|
|
345
|
+
"measured_baseline_source": measured_baseline.get("source"),
|
|
346
|
+
"measured_baseline_first_date": measured_baseline.get("first_date"),
|
|
347
|
+
"baseline_source": baseline_source, "baseline_stated": baseline_stated,
|
|
348
|
+
"routable_fraction": _measure_facade._ROUTABLE_OPUS_FRACTION,
|
|
349
|
+
# Realized routing is a standardized comparison on a fixed price
|
|
350
|
+
# schedule (newest card per family) in both arms, because the baseline
|
|
351
|
+
# records no generations. That schedule is an assumption, so the
|
|
352
|
+
# result is an estimate. The exact-card cost of the same work and its
|
|
353
|
+
# gap to the standardized valuation are reported apart: the gap is
|
|
354
|
+
# price/generation, never routing.
|
|
355
|
+
"realized_basis": "standardized_reference_card",
|
|
356
|
+
"baseline_rate_basis": {f: fam_rate_basis[f] for f in sorted(set(base_priced) | set(fam_classes)) if f in fam_rate_basis},
|
|
357
|
+
"baseline_reference_priced": sorted(base_priced),
|
|
358
|
+
"standardized_baseline_cost_usd": round(standardized_baseline, 4),
|
|
359
|
+
"standardized_actual_cost_usd": round(standardized_actual, 4),
|
|
360
|
+
"actual_cost_usd": round(actual_cost, 4),
|
|
361
|
+
"generation_price_delta_usd": round(actual_cost - standardized_actual, 4),
|
|
362
|
+
# Share of the window's class tokens inside both arms (premium,
|
|
363
|
+
# unpriced and free models, and unsplit tokens are outside).
|
|
364
|
+
"compared_share": round(compared_tokens / window_tokens, 4) if window_tokens > 0 else 0.0,
|
|
365
|
+
"evidence": "estimated" if compared_tokens > 0 and base_priced else "unavailable",
|
|
366
|
+
}
|
|
367
|
+
except Exception:
|
|
368
|
+
return zero
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Calculate capacity from the same savings components as the savings story."""
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def extra_work(facade, conn, days, summary, estimated_only=False):
|
|
6
|
+
cutoff = (facade.datetime.now() - facade.timedelta(days=days)).date().isoformat()
|
|
7
|
+
today = facade.datetime.now().date().isoformat()
|
|
8
|
+
columns = {row[1] for row in conn.execute('PRAGMA table_info(session_log)')}
|
|
9
|
+
parent = 'parent_daily_usage_json' if 'parent_daily_usage_json' in columns else 'daily_usage_json'
|
|
10
|
+
side = 'COALESCE(is_sidechain,0)=0' if 'is_sidechain' in columns else '1=1'
|
|
11
|
+
actual = 0.0
|
|
12
|
+
for (raw,) in conn.execute(f'SELECT {parent} FROM session_log WHERE {side}'):
|
|
13
|
+
try:
|
|
14
|
+
daily = json.loads(raw or '{}')
|
|
15
|
+
for day, models in daily.items():
|
|
16
|
+
if not cutoff <= day <= today:
|
|
17
|
+
continue
|
|
18
|
+
for model, usage in models.items():
|
|
19
|
+
if facade._is_priced_model(model):
|
|
20
|
+
actual += facade._get_model_cost(model, int(usage.get('fresh_input') or 0), int(usage.get('output') or 0), int(usage.get('cache_read') or 0), int(usage.get('cache_create') or 0))
|
|
21
|
+
except (TypeError, ValueError, AttributeError):
|
|
22
|
+
continue
|
|
23
|
+
if actual <= 0:
|
|
24
|
+
return None
|
|
25
|
+
counted = facade._counted_cumulative_summary(days=days)
|
|
26
|
+
facade._apply_counted_oneshot_pricing(summary, counted)
|
|
27
|
+
components = facade._action_savings_components(summary, counted)
|
|
28
|
+
# These two pools already contribute tokens to the context multiplier.
|
|
29
|
+
if estimated_only:
|
|
30
|
+
estimates = components.get('estimates_usd') or {}
|
|
31
|
+
saved = sum(float(value or 0) for key, value in estimates.items()
|
|
32
|
+
if key not in ('hint_followed', 'resume_lean_verified'))
|
|
33
|
+
else:
|
|
34
|
+
saved = components['total_usd'] + components['routing_usd']
|
|
35
|
+
return max(0.0, saved / actual * 100)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def safe_extra_work(facade, conn, days):
|
|
39
|
+
try:
|
|
40
|
+
return extra_work(facade, conn, days, facade._get_merged_savings(days=days), estimated_only=True)
|
|
41
|
+
except Exception:
|
|
42
|
+
return None
|