trioditis 0.6.0__py3-none-any.whl

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.
trioditis/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Trioditis: a small, security-first LLM router with an OpenAI-compatible API."""
2
+
3
+ __version__ = "0.6.0"
trioditis/__main__.py ADDED
@@ -0,0 +1,514 @@
1
+ """Command line entry point: python -m trioditis [init|serve|check|explain|eval-routes|hardware|usage|plan|prices|refit]."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import json
8
+ import os
9
+ import re
10
+ import stat
11
+ import sys
12
+ import textwrap
13
+ import time
14
+ from pathlib import Path
15
+
16
+ from . import __version__
17
+ from .config import ConfigError, load_config
18
+ from .envvars import env
19
+ from .security import assert_safe_bind
20
+
21
+ _ENV_LINE = re.compile(r"^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$")
22
+
23
+
24
+ def load_dotenv(path: str | Path = ".env") -> list[str]:
25
+ """Minimal, dependency-free .env loader (same behaviour on Linux and Windows).
26
+
27
+ Only KEY=VALUE lines; never overrides variables already set in the
28
+ environment; values are not executed or expanded.
29
+ """
30
+ p = Path(path)
31
+ if not p.is_file():
32
+ return []
33
+ if os.name == "posix" and p.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
34
+ print(f"warning: {p} is readable by other users; run: chmod 600 {p}", file=sys.stderr)
35
+ loaded = []
36
+ for line in p.read_text(encoding="utf-8-sig").splitlines():
37
+ if not line.strip() or line.lstrip().startswith("#"):
38
+ continue
39
+ m = _ENV_LINE.match(line)
40
+ if not m:
41
+ continue
42
+ key, value = m.group(1), m.group(2)
43
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
44
+ value = value[1:-1]
45
+ if value and key not in os.environ:
46
+ os.environ[key] = value
47
+ loaded.append(key)
48
+ return loaded
49
+
50
+
51
+ def main(argv: list[str] | None = None) -> None:
52
+ load_dotenv(env("ENV_FILE", ".env"))
53
+ ap = argparse.ArgumentParser(prog="trioditis")
54
+ ap.add_argument("--config", default=env("CONFIG", "config.yaml"))
55
+ ap.add_argument("--version", action="version", version=f"trioditis {__version__}")
56
+ sub = ap.add_subparsers(dest="cmd")
57
+
58
+ i = sub.add_parser("init", help="write config.yaml and .env from the templates (never overwrites)")
59
+ i.add_argument("--dir", default=".", help="folder to set up (default: the current one)")
60
+
61
+ s = sub.add_parser("serve", help="run the router (default)")
62
+ s.add_argument("--host", default=env("HOST", "127.0.0.1"))
63
+ s.add_argument("--port", type=int, default=int(env("PORT", "8787")))
64
+
65
+ sub.add_parser("check", help="validate the config, ask local servers which models they have, show which cloud keys are set")
66
+
67
+ e = sub.add_parser("explain", help="show which model a prompt would go to (no model call)")
68
+ e.add_argument("prompt")
69
+
70
+ ev = sub.add_parser("eval-routes", help="how often the router picks the right route, against a labelled CSV "
71
+ "(no chat model is called)",
72
+ description="Grade the router's route choice on a labelled CSV: columns prompt and expected_route "
73
+ "(UTF-8, header in row 1; other columns are ignored). Prints accuracy with a 95% interval, "
74
+ "accuracy per route and a confusion table, for keywords alone and, when the config has "
75
+ "embeddings and the local provider answers, keywords plus embeddings. With 20 or more rows it "
76
+ "then picks embeddings.threshold on half the rows, scores it against yours on the other "
77
+ "half (exact sign test) and records a proposal in the notebook only when the gain is "
78
+ "unlikely to be chance. Changes nothing in the config. The only network call is to the "
79
+ "configured local embeddings provider.")
80
+ ev.add_argument("--labels", required=True, metavar="FILE", help="the labelled prompts (CSV with prompt, expected_route)")
81
+ ev.add_argument("--config", default=argparse.SUPPRESS, metavar="FILE",
82
+ help="the config to grade (default: TRIODITIS_CONFIG or config.yaml; same as the option before the command)")
83
+ ev.add_argument("--notebook", default=None, metavar="FILE", help="where a threshold proposal goes (default ~/.hlidskjalv/trioditis-notebook.jsonl)")
84
+ ev.add_argument("--dry-run", action="store_true", help="show the proposal that would be recorded, write nothing")
85
+ ev.add_argument("--compare-threshold", type=float, default=None, metavar="VALUE",
86
+ help="instead of the sweep, score this embeddings.threshold against the config's on every row "
87
+ "(for a value chosen on other labels; nothing is proposed or written)")
88
+
89
+ h = sub.add_parser("hardware", help="detect hardware and suggest local models (no config change)")
90
+ h.add_argument("--json", action="store_true", help="machine-readable output")
91
+
92
+ u = sub.add_parser("usage", help="calls, tokens and spend from the metrics database (no config needed)")
93
+ u.add_argument("--since", default="24h", help="30m, 24h, 7d, today, month or YYYY-MM-DD (default 24h)")
94
+ u.add_argument("--until", default=None, help="same forms as --since; default now")
95
+ u.add_argument("--by", default=None, help="model, route, provider, client, session or day (default model); "
96
+ "with --plan: model-effort (default), model, effort, day, source, "
97
+ "person or agent")
98
+ u.add_argument("--session", default=None, help="only this X-Session-Id (matched by its hash)")
99
+ u.add_argument("--db", default=None, help="metrics database (default ~/.hlidskjalv/metrics.db)")
100
+ u.add_argument("--outcomes", action="store_true",
101
+ help="rates with 95%% intervals instead of spend: errors, answers cut off at the length "
102
+ "limit, answers asked again within 2 minutes, prompt tokens served from cache")
103
+ u.add_argument("--plan", action="store_true",
104
+ help="plan usage instead of API calls: messages and tokens per model and effort, and how far "
105
+ "each plan meter rose (fill it with `trioditis plan import`)")
106
+ u.add_argument("--json", action="store_true", help="machine-readable output (always includes the rates)")
107
+
108
+ pl = sub.add_parser("plan", help="plan usage: what a subscription's chats and agents used (no config needed)")
109
+ pl_sub = pl.add_subparsers(dest="plan_cmd", required=True)
110
+ pi = pl_sub.add_parser("import", help="import token counts and meter readings; with no arguments, what the "
111
+ "config's plan: section names (the daily timer runs it that way)")
112
+ pi.add_argument("file", nargs="?", help="a plan-usage.v1 events file (Euboulia exports one)")
113
+ pi.add_argument("--claude-code", action="store_true",
114
+ help="token counts from Claude Code's transcripts (~/.claude, or $CLAUDE_CONFIG_DIR); no text is kept")
115
+ pi.add_argument("--claude-home", default=None, help=argparse.SUPPRESS)
116
+ pi.add_argument("--meter", nargs="?", const="", default=None, metavar="FILE",
117
+ help="plan meter readings (plan-meter.v1 or snapshots); without FILE, plan.meter_file")
118
+ pi.add_argument("--db", default=None, help="metrics database (default ~/.hlidskjalv/metrics.db)")
119
+ pi.add_argument("--dry-run", action="store_true", help="show what would be imported, write nothing")
120
+
121
+ pr = sub.add_parser("prices", help="manage ~/.hlidskjalv/prices.json")
122
+ pr_sub = pr.add_subparsers(dest="prices_cmd", required=True)
123
+ imp = pr_sub.add_parser("import", help="take cloud model prices from a provider-facts file, with their sources")
124
+ imp.add_argument("facts", help="a provider-facts.v1 JSON file (for example Euboulia's src/catalog/provider-facts.json)")
125
+ imp.add_argument("--prices", default=None, help="prices file to update (default ~/.hlidskjalv/prices.json)")
126
+ imp.add_argument("--dry-run", action="store_true", help="show the changes, write nothing")
127
+
128
+ rf = sub.add_parser("refit", help="refit rates, latency and drift charts from the call record, and check the "
129
+ "model facts (changes nothing the router uses)")
130
+ rf.add_argument("--days", type=int, default=28, help="window to fit, in days (default 28)")
131
+ rf.add_argument("--db", default=None, help="metrics database (default ~/.hlidskjalv/metrics.db)")
132
+ rf.add_argument("--out", default=None, help="fitted file (default ~/.hlidskjalv/trioditis-fitted.json)")
133
+ rf.add_argument("--notebook", default=None, help="findings log (default ~/.hlidskjalv/trioditis-notebook.jsonl)")
134
+ rf.add_argument("--prices", default=None, help="prices file to compare (default ~/.hlidskjalv/prices.json)")
135
+ rf.add_argument("--json", action="store_true", help="print the fitted document")
136
+ rf.add_argument("--dry-run", action="store_true", help="show the result, write nothing")
137
+
138
+ args = ap.parse_args(argv)
139
+ if args.cmd == "usage": # reads the metrics database only: works without a config
140
+ sys.exit(plan_report(args) if args.plan else usage_report(args))
141
+ if args.cmd == "plan": # reads only the config's plan: section, and only when it needs it
142
+ from .config import load_plan_settings
143
+ from .plan import run as plan_run
144
+ try:
145
+ settings = load_plan_settings(args.config)
146
+ except (OSError, ConfigError, ValueError) as err:
147
+ sys.exit(f"config error in {args.config}: {err}")
148
+ sys.exit(plan_run(args, settings))
149
+ if args.cmd == "init": # creates the config: obviously works without one
150
+ sys.exit(init_folder(Path(args.dir)))
151
+ try:
152
+ cfg = load_config(args.config)
153
+ except (OSError, ConfigError) as err:
154
+ sys.exit(f"config error: {err}")
155
+
156
+ if args.cmd == "check":
157
+ print(f"config OK: {len(cfg.models)} models, {len(cfg.routes)} routes")
158
+ from .localcheck import local_states
159
+ # Local servers are asked once each (a model listing); cloud providers are never contacted.
160
+ # Exit code: 0 whatever the states, as for a missing key: `check` reports, `serve` decides.
161
+ states, notes = local_states(cfg)
162
+ confirmed = 0
163
+ for name, m in cfg.models.items():
164
+ p = cfg.providers[m.provider]
165
+ if not p.available():
166
+ state = f"missing ${p.api_key_env}"
167
+ elif p.local:
168
+ state = states[name]
169
+ else:
170
+ state = "key set (not tested)"
171
+ confirmed += state == "ready"
172
+ where = "local" if p.local else "cloud"
173
+ print(f" {name:<24} {where:<6} {state}")
174
+ for note in notes:
175
+ print(textwrap.fill(note, width=98, initial_indent=" ", subsequent_indent=" ",
176
+ break_long_words=False, break_on_hyphens=False))
177
+ print(f"{confirmed} of {len(cfg.models)} models confirmed ready; cloud providers are never contacted")
178
+ for line in _facts_lines(cfg):
179
+ print(line)
180
+ return
181
+
182
+ if args.cmd == "refit":
183
+ from .refit import run
184
+ sys.exit(run(cfg, args))
185
+
186
+ if args.cmd == "prices":
187
+ sys.exit(prices_import(cfg, args))
188
+
189
+ if args.cmd == "explain":
190
+ from trioditis_metrics.prices import Prices
191
+
192
+ from .router import Signals, decide
193
+ body = {"model": "auto", "messages": [{"role": "user", "content": args.prompt}]}
194
+ # Keyword/rule signals only here, so the CLI never calls any network service; prices and past
195
+ # latency (read-only) let it show a route's cost or speed order.
196
+ d = asyncio.run(decide(cfg, body, signals=Signals(prices=Prices(), latency=_readonly_latency())))
197
+ print(json.dumps(d.as_dict(), indent=2))
198
+ return
199
+
200
+ if args.cmd == "eval-routes":
201
+ from .evalroutes import run as eval_routes
202
+ sys.exit(eval_routes(cfg, args))
203
+
204
+ if args.cmd == "hardware":
205
+ import httpx
206
+
207
+ from .hardware import build_report, detect, format_report, installed_models, load_prices
208
+
209
+ async def listed():
210
+ # Only local providers are queried (GET /api/tags); no proxy, no redirects.
211
+ async with httpx.AsyncClient(follow_redirects=False, trust_env=False) as c:
212
+ return await installed_models(cfg, c)
213
+
214
+ inst, errs = asyncio.run(listed())
215
+ rep = build_report(cfg, detect(), inst, errs, load_prices())
216
+ print(json.dumps(rep, indent=2) if args.json else format_report(rep))
217
+ return
218
+
219
+ host = getattr(args, "host", "127.0.0.1")
220
+ port = getattr(args, "port", 8787)
221
+ assert_safe_bind(host)
222
+
223
+ if sys.stderr is None or sys.stdout is None:
224
+ # Started without a console (pythonw.exe on Windows, some launchers):
225
+ # send server output to a private log file instead of nowhere.
226
+ Path("logs").mkdir(exist_ok=True)
227
+ fd = os.open("logs/server.log", os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
228
+ stream = os.fdopen(fd, "a", encoding="utf-8", buffering=1)
229
+ sys.stdout = sys.stderr = stream
230
+
231
+ for line in _facts_lines(cfg):
232
+ print(f"warning: {line}", file=sys.stderr)
233
+
234
+ import uvicorn
235
+
236
+ from .app import create_app
237
+
238
+ uvicorn.run(
239
+ create_app(cfg),
240
+ host=host,
241
+ port=port,
242
+ server_header=False,
243
+ date_header=False,
244
+ proxy_headers=False,
245
+ log_level="info",
246
+ )
247
+
248
+
249
+ def _facts_lines(cfg) -> list[str]:
250
+ """What the model facts say about the configured cloud models; nothing when `facts:` is unset."""
251
+ if not cfg.facts:
252
+ return []
253
+ from .pricefacts import check_lines
254
+ cloud = {name: m.upstream_id for name, m in cfg.models.items() if not cfg.providers[m.provider].local}
255
+ return check_lines(cfg.facts, cloud)
256
+
257
+
258
+ _AGO = re.compile(r"^(\d+)([mhdw])$")
259
+ _UNIT_S = {"m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}
260
+
261
+
262
+ def init_folder(folder: Path) -> int:
263
+ """config.yaml and .env from the packaged templates; files that exist are left alone."""
264
+ from importlib import resources
265
+ folder = folder.expanduser()
266
+ folder.mkdir(parents=True, exist_ok=True)
267
+ tpl = resources.files("trioditis") / "templates"
268
+ wrote = []
269
+ # Both files are private: .env holds keys, and config.yaml names your providers and local addresses.
270
+ for name, target in (("config.example.yaml", "config.yaml"), ("env.example", ".env")):
271
+ dest = folder / target
272
+ if dest.exists():
273
+ print(f"kept {dest} (already there)")
274
+ continue
275
+ data = tpl.joinpath(name).read_text(encoding="utf-8")
276
+ fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
277
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
278
+ f.write(data)
279
+ wrote.append(target)
280
+ print(f"wrote {dest}")
281
+ where = "" if folder.resolve() == Path.cwd().resolve() else f"cd {folder} && "
282
+ print("next: " + (f"add cloud keys to {folder / '.env'} if you want them, then " if ".env" in wrote else "")
283
+ + f"{where}trioditis check && trioditis serve (config.yaml, .env and logs/ are read from that folder)")
284
+ return 0
285
+
286
+
287
+ def _readonly_latency():
288
+ import sqlite3
289
+
290
+ from trioditis_metrics.db import DEFAULT_PATH, latency_p50, open_readonly
291
+
292
+ def p50(model: str) -> int | None:
293
+ try:
294
+ conn = open_readonly(DEFAULT_PATH)
295
+ try:
296
+ return latency_p50(conn, model, time.time() - 7 * 86400)
297
+ finally:
298
+ conn.close()
299
+ except sqlite3.Error:
300
+ return None
301
+ return p50
302
+
303
+
304
+ def parse_when(text: str, now: float | None = None) -> float:
305
+ """'30m', '24h', '7d', '2w' ago; 'today' or 'month' (local midnight); 'YYYY-MM-DD' (local midnight)."""
306
+ now = time.time() if now is None else now
307
+ text = text.strip().lower()
308
+ if m := _AGO.match(text):
309
+ return now - int(m.group(1)) * _UNIT_S[m.group(2)]
310
+ t = time.localtime(now)
311
+ if text == "today":
312
+ return time.mktime((t.tm_year, t.tm_mon, t.tm_mday, 0, 0, 0, 0, 0, -1))
313
+ if text == "month":
314
+ return time.mktime((t.tm_year, t.tm_mon, 1, 0, 0, 0, 0, 0, -1))
315
+ try:
316
+ d = time.strptime(text, "%Y-%m-%d")
317
+ except ValueError:
318
+ raise ValueError(f"cannot read {text!r}: use 30m, 24h, 7d, today, month or YYYY-MM-DD") from None
319
+ return time.mktime((d.tm_year, d.tm_mon, d.tm_mday, 0, 0, 0, 0, 0, -1))
320
+
321
+
322
+ def prices_import(cfg, args) -> int:
323
+ from trioditis_metrics.prices import DEFAULT_PRICES_PATH
324
+
325
+ from .pricefacts import FactsError, plan_import, stale_warning, write_prices
326
+
327
+ try:
328
+ facts = json.loads(Path(args.facts).expanduser().read_text(encoding="utf-8"))
329
+ except (OSError, ValueError) as err:
330
+ print(f"prices import: cannot read {args.facts}: {err}", file=sys.stderr)
331
+ return 2
332
+ path = Path(args.prices).expanduser() if args.prices else DEFAULT_PRICES_PATH
333
+ try:
334
+ current = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
335
+ except ValueError:
336
+ print(f"prices import: {path} is not valid JSON; fix or move it first", file=sys.stderr)
337
+ return 2
338
+ cloud = {name: m.upstream_id for name, m in cfg.models.items() if not cfg.providers[m.provider].local}
339
+ try:
340
+ table, changes, unmatched = plan_import(facts, cloud, current if isinstance(current, dict) else {})
341
+ except FactsError as err:
342
+ print(f"prices import: {err}", file=sys.stderr)
343
+ return 2
344
+ if warning := stale_warning(facts):
345
+ print(f"warning: {warning}")
346
+ for line in changes:
347
+ print(" " + line)
348
+ for name in unmatched:
349
+ print(f" {name} ({cloud[name]}): not in the facts file, left as it is")
350
+ if not changes:
351
+ print("nothing to import: no configured cloud model is in the facts file")
352
+ return 1
353
+ if args.dry_run:
354
+ print(f"dry run: {path} not changed")
355
+ return 0
356
+ write_prices(path, table)
357
+ print(f"wrote {path}")
358
+ return 0
359
+
360
+
361
+ def usage_report(args) -> int:
362
+ import sqlite3
363
+
364
+ from trioditis_metrics.db import DEFAULT_PATH, GROUPS, open_readonly, outcome_rates, usage
365
+
366
+ from .security import fingerprint
367
+
368
+ try:
369
+ since = parse_when(args.since)
370
+ until = parse_when(args.until) if args.until else None
371
+ except ValueError as err:
372
+ print(f"usage: {err}", file=sys.stderr)
373
+ return 2
374
+ args.by = args.by or "model"
375
+ if args.by not in GROUPS:
376
+ print(f"usage: cannot group calls by {args.by!r}; choose from {', '.join(GROUPS)}", file=sys.stderr)
377
+ return 2
378
+ path = Path(args.db).expanduser() if args.db else DEFAULT_PATH
379
+ sfp = fingerprint(args.session) if args.session else None
380
+ try:
381
+ conn = open_readonly(path)
382
+ try:
383
+ rows = usage(conn, since, until, args.by, sfp)
384
+ finally:
385
+ conn.close()
386
+ except sqlite3.Error:
387
+ rows = None # no database yet (Trioditis has not served a call), or not one of ours
388
+ total = {k: sum((r[k] or 0) for r in rows or []) for k in
389
+ ("calls", "errors", "tokens_in", "tokens_out", "cost", "unpriced", "fallbacks", "local_calls",
390
+ "finished", "truncated", "fingerprinted", "retried", "cached_tokens", "cache_base_tokens")}
391
+ total["cost"] = round(total["cost"], 6)
392
+ for r in [*(rows or []), total]:
393
+ r["rates"] = outcome_rates(r)
394
+ stamp = lambda ts: time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(ts)) if ts else None # noqa: E731
395
+ if args.json:
396
+ for r in rows or []:
397
+ r["first"], r["last"] = stamp(r.pop("first_ts")), stamp(r.pop("last_ts"))
398
+ print(json.dumps({"since": stamp(since), "until": stamp(until), "by": args.by, "session": sfp,
399
+ "database": str(path), "rows": rows or [], "total": total}, indent=2))
400
+ return 0
401
+ if rows is None:
402
+ print(f"no calls recorded yet (no metrics database at {path})")
403
+ return 0
404
+ span = f"since {stamp(since)}" + (f" until {stamp(until)}" if until else "")
405
+ print(f"usage by {args.by} {span}" + (f", session {args.session!r}" if args.session else ""))
406
+ if not rows:
407
+ print("no calls in this window")
408
+ return 0
409
+ if args.outcomes:
410
+ return _print_outcomes(args.by, rows, total)
411
+ head = (args.by, "calls", "errors", "tokens in", "tokens out", "cost USD", "unpriced")
412
+ table = [head] + [(str(r["key"]) if r["key"] is not None else "-", r["calls"], r["errors"], r["tokens_in"],
413
+ r["tokens_out"], f"{r['cost']:.4f}", r["unpriced"]) for r in rows]
414
+ table.append(("total", total["calls"], total["errors"], total["tokens_in"], total["tokens_out"],
415
+ f"{total['cost']:.4f}", total["unpriced"]))
416
+ _print_table(table)
417
+ if total["unpriced"]:
418
+ print(f"{total['unpriced']} cloud call(s) had no price: add them to ~/.hlidskjalv/prices.json")
419
+ return 0
420
+
421
+
422
+ def plan_report(args) -> int:
423
+ import sqlite3
424
+
425
+ from trioditis_metrics.db import DEFAULT_PATH, open_readonly
426
+ from trioditis_metrics.plan import GROUPS, meter_rise, plan_usage
427
+
428
+ by = args.by or "model-effort"
429
+ if by not in GROUPS:
430
+ print(f"usage --plan: cannot group by {by!r}; choose from {', '.join(GROUPS)}", file=sys.stderr)
431
+ return 2
432
+ try:
433
+ since = parse_when(args.since)
434
+ until = parse_when(args.until) if args.until else None
435
+ except ValueError as err:
436
+ print(f"usage: {err}", file=sys.stderr)
437
+ return 2
438
+ path = Path(args.db).expanduser() if args.db else DEFAULT_PATH
439
+ try:
440
+ conn = open_readonly(path)
441
+ try:
442
+ rows, meters = plan_usage(conn, since, until, by), meter_rise(conn, since, until)
443
+ finally:
444
+ conn.close()
445
+ except sqlite3.Error:
446
+ rows, meters = [], []
447
+ keys = ("messages", "tokens_in", "cache_read", "cache_write", "tokens_out", "measured")
448
+ total = {k: sum(r[k] or 0 for r in rows) for k in keys}
449
+ stamp = lambda ts: time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(ts)) if ts else None # noqa: E731
450
+ if args.json:
451
+ for r in rows:
452
+ r["first"], r["last"] = stamp(r.pop("first_ts")), stamp(r.pop("last_ts"))
453
+ print(json.dumps({"since": stamp(since), "until": stamp(until), "by": by, "database": str(path),
454
+ "rows": rows, "total": total, "meters": meters}, indent=2))
455
+ return 0
456
+ span = f"since {stamp(since)}" + (f" until {stamp(until)}" if until else "")
457
+ print(f"plan usage by {by} {span}")
458
+ if not rows:
459
+ print("no plan usage in this window (import it with: trioditis plan import --claude-code)")
460
+ else:
461
+ head = (by, "messages", "in", "cache read", "cache write", "out", "measured")
462
+ table = [head] + [(str(r["key"]), r["messages"], r["tokens_in"], r["cache_read"], r["cache_write"],
463
+ r["tokens_out"], f"{(r['measured'] or 0) / r['messages']:.0%}") for r in rows]
464
+ table.append(("total", total["messages"], total["tokens_in"], total["cache_read"], total["cache_write"],
465
+ total["tokens_out"], f"{total['measured'] / total['messages']:.0%}"))
466
+ _print_table(table)
467
+ print("'in' is uncached prompt tokens; 'measured' is the share with real counts, the rest are estimates.")
468
+ if meters:
469
+ print("meters (whole percents; a reset counts the new window from zero):")
470
+ for m in meters:
471
+ name = m["meter"] + (f" ({m['model']})" if m["model"] else "")
472
+ resets = f", {m['resets']} reset(s)" if m["resets"] else ""
473
+ print(f" {name:<28} +{m['rise']:g} points over {m['readings']:,} readings "
474
+ f"({m['first']:g}% -> {m['last']:g}%{resets})")
475
+ else:
476
+ print("no meter readings in this window (import them with: trioditis plan import --meter FILE)")
477
+ return 0
478
+
479
+
480
+ def _pct(rate: dict) -> str:
481
+ if rate["value"] is None:
482
+ return "-"
483
+ if "lo" not in rate:
484
+ return f"{rate['value']:.0%}"
485
+ return f"{rate['value']:.0%} ({rate['lo']:.0%}-{rate['hi']:.0%})"
486
+
487
+
488
+ def _print_outcomes(by: str, rows: list[dict], total: dict) -> int:
489
+ head = (by, "calls", "errors", "cut off", "asked again", "cache hit")
490
+ table = [head]
491
+ for r in [*rows, {**total, "key": "total"}]:
492
+ x = r["rates"]
493
+ table.append((str(r["key"]) if r["key"] is not None else "-", r["calls"], _pct(x["error"]),
494
+ _pct(x["truncated"]), _pct(x["retried"]), _pct(x["cache_hit"])))
495
+ _print_table(table)
496
+ print("rates with 95% intervals; '-' means no data. 'cut off': of the answers whose provider said why they "
497
+ "ended.\n'cache hit': of the prompt tokens whose provider reports cache use (Anthropic's "
498
+ "OpenAI-compatible endpoint has no prompt caching).")
499
+ return 0
500
+
501
+
502
+ def _print_table(table: list[tuple]) -> None:
503
+ head = table[0]
504
+ widths = [max(len(f"{row[i]:,}" if isinstance(row[i], int) else str(row[i])) for row in table)
505
+ for i in range(len(head))]
506
+ for n, row in enumerate(table):
507
+ cells = [f"{v:,}" if isinstance(v, int) else str(v) for v in row]
508
+ print(" ".join(c.ljust(widths[i]) if i == 0 else c.rjust(widths[i]) for i, c in enumerate(cells)))
509
+ if n == 0 or n == len(table) - 2:
510
+ print(" ".join("-" * w for w in widths))
511
+
512
+
513
+ if __name__ == "__main__":
514
+ main()