tanglebrain 0.16.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.
- tanglebrain/__init__.py +23 -0
- tanglebrain/adapters/__init__.py +15 -0
- tanglebrain/adapters/api.py +65 -0
- tanglebrain/adapters/base.py +46 -0
- tanglebrain/adapters/cli.py +341 -0
- tanglebrain/adapters/openai_compat.py +197 -0
- tanglebrain/classifier.py +99 -0
- tanglebrain/cli.py +251 -0
- tanglebrain/config/pricing.yaml +14 -0
- tanglebrain/config/roster.yaml +129 -0
- tanglebrain/config/settings.yaml +39 -0
- tanglebrain/delegate.py +485 -0
- tanglebrain/gui/__init__.py +10 -0
- tanglebrain/gui/server.py +162 -0
- tanglebrain/gui/static/index.html +295 -0
- tanglebrain/gui/static/logo.png +0 -0
- tanglebrain/gui/views.py +180 -0
- tanglebrain/mcp_server.py +208 -0
- tanglebrain/measurement.py +548 -0
- tanglebrain/roster.py +415 -0
- tanglebrain/roster_edit.py +201 -0
- tanglebrain/router.py +232 -0
- tanglebrain/selector.py +117 -0
- tanglebrain/settings.py +132 -0
- tanglebrain-0.16.0.dist-info/METADATA +369 -0
- tanglebrain-0.16.0.dist-info/RECORD +30 -0
- tanglebrain-0.16.0.dist-info/WHEEL +5 -0
- tanglebrain-0.16.0.dist-info/entry_points.txt +4 -0
- tanglebrain-0.16.0.dist-info/licenses/LICENSE +21 -0
- tanglebrain-0.16.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
"""Measurement / "spend avoided" rollup.
|
|
2
|
+
|
|
3
|
+
Every routed task is logged as one JSON line in an append-only usage log, and ``tanglebrain
|
|
4
|
+
--stats`` rolls those records up into a "spend avoided" figure: what the routed work *would* have
|
|
5
|
+
cost on a paid frontier API, had it not gone to the free local tier or a subscription CLI. This
|
|
6
|
+
makes the cloud-equivalent cost avoided by routing visible.
|
|
7
|
+
|
|
8
|
+
Design notes:
|
|
9
|
+
|
|
10
|
+
- **Tokens are estimated, not measured.** Authenticated CLIs expose no usable token counts, and a
|
|
11
|
+
local reasoning model's real ``usage`` is inflated by dropped reasoning tokens. So a
|
|
12
|
+
single ``chars/4`` heuristic over the visible prompt + response is applied *uniformly* across all
|
|
13
|
+
tiers — one consistent, if approximate, methodology (see :func:`estimate_tokens`).
|
|
14
|
+
- **Pricing is config-driven** (``config/pricing.yaml``): a reference frontier price the operator
|
|
15
|
+
tunes (the knob GUI edits it).
|
|
16
|
+
- **All I/O is fault-tolerant.** A logging failure must never break the user's actual answer, and a
|
|
17
|
+
corrupt log line must never break the rollup. Reads return sensible defaults; the writer swallows
|
|
18
|
+
every exception. This mirrors the router's state-file idiom (:mod:`tanglebrain.router`).
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import shutil
|
|
25
|
+
import threading
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from datetime import datetime, timezone
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
import yaml
|
|
31
|
+
|
|
32
|
+
from tanglebrain.router import DEFAULT_STATE_SUBDIR, STATE_DIR_ENV
|
|
33
|
+
|
|
34
|
+
LOG_FILENAME = "usage.jsonl"
|
|
35
|
+
|
|
36
|
+
#: Env var carrying the top-level task id from the orchestrator down to a delegated sub-call. The
|
|
37
|
+
#: CLI mints a task id per routed task and the orchestrator-CLI adapter injects it into the
|
|
38
|
+
#: orchestrator subprocess env (only when the delegate tool is injected); the orchestrator forwards
|
|
39
|
+
#: its env to the MCP delegate child it spawns, where :func:`tanglebrain.delegate.run_delegate` reads
|
|
40
|
+
#: it back and stamps each delegate record's ``parent_task_id``. This is what links a delegated
|
|
41
|
+
#: sub-call to the specific top-level task that spawned it, across the process boundary.
|
|
42
|
+
PARENT_TASK_ID_ENV = "TANGLEBRAIN_TASK_ID"
|
|
43
|
+
|
|
44
|
+
# Serializes appends to the usage log so concurrent writers in one process (delegate_many fans
|
|
45
|
+
# sub-tasks out across threads) can't interleave bytes mid-line. Per-process only; cross-process
|
|
46
|
+
# appends rely on the OS's O_APPEND atomicity for short lines, as before.
|
|
47
|
+
_LOG_LOCK = threading.Lock()
|
|
48
|
+
|
|
49
|
+
# Chars per token for the uniform estimation heuristic. ~4 chars/token is the standard rough
|
|
50
|
+
# approximation for English-ish text across modern BPE tokenizers; good enough for an *estimate*.
|
|
51
|
+
_CHARS_PER_TOKEN = 4
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Pricing:
|
|
56
|
+
"""Cloud-equivalent reference pricing for the rollup (loaded from ``config/pricing.yaml``).
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
reference_model: Human-readable label for the frontier model these rates represent.
|
|
60
|
+
input_per_mtok: US dollars per 1,000,000 input (prompt) tokens.
|
|
61
|
+
output_per_mtok: US dollars per 1,000,000 output (completion) tokens.
|
|
62
|
+
is_placeholder: ``True`` while the rates are rough/illustrative; the rollup renders a
|
|
63
|
+
PLACEHOLDER caveat so no figure is mistaken for a precise cost.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
reference_model: str
|
|
67
|
+
input_per_mtok: float
|
|
68
|
+
output_per_mtok: float
|
|
69
|
+
is_placeholder: bool
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# Fallback used when ``config/pricing.yaml`` is missing or unreadable — always flagged placeholder.
|
|
73
|
+
PLACEHOLDER_PRICING = Pricing(
|
|
74
|
+
reference_model="unconfigured (PLACEHOLDER — pricing.yaml unreadable)",
|
|
75
|
+
input_per_mtok=3.00,
|
|
76
|
+
output_per_mtok=15.00,
|
|
77
|
+
is_placeholder=True,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def default_log_path() -> Path:
|
|
82
|
+
"""Return the usage-log file path.
|
|
83
|
+
|
|
84
|
+
Honors ``TANGLEBRAIN_STATE_DIR`` (``~`` expanded); otherwise ``~/.cache/tanglebrain/``. The log
|
|
85
|
+
lives alongside the router's state file (same dir, same env override).
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
The absolute path to the append-only usage JSONL file.
|
|
89
|
+
"""
|
|
90
|
+
base = os.environ.get(STATE_DIR_ENV)
|
|
91
|
+
root = Path(base).expanduser() if base else Path.home() / DEFAULT_STATE_SUBDIR
|
|
92
|
+
return root / LOG_FILENAME
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def default_pricing_path() -> Path:
|
|
96
|
+
"""Return the path to the pricing YAML shipped with the package.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
The absolute path to ``tanglebrain/config/pricing.yaml``.
|
|
100
|
+
"""
|
|
101
|
+
return Path(__file__).resolve().parent / "config" / "pricing.yaml"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def load_pricing(path: str | os.PathLike[str] | None = None) -> Pricing:
|
|
105
|
+
"""Load cloud-equivalent reference pricing, tolerating a missing/corrupt file.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
path: Path to a pricing YAML. Defaults to the packaged ``config/pricing.yaml``.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
The parsed :class:`Pricing`, or :data:`PLACEHOLDER_PRICING` if the file is absent,
|
|
112
|
+
unreadable, or malformed — bad config must never crash the rollup.
|
|
113
|
+
"""
|
|
114
|
+
pricing_path = Path(path) if path is not None else default_pricing_path()
|
|
115
|
+
try:
|
|
116
|
+
raw = yaml.safe_load(pricing_path.read_text())
|
|
117
|
+
return Pricing(
|
|
118
|
+
reference_model=str(raw.get("reference_model", "unknown")),
|
|
119
|
+
input_per_mtok=float(raw["input_per_mtok"]),
|
|
120
|
+
output_per_mtok=float(raw["output_per_mtok"]),
|
|
121
|
+
is_placeholder=bool(raw.get("placeholder", False)),
|
|
122
|
+
)
|
|
123
|
+
except (OSError, yaml.YAMLError, ValueError, TypeError, KeyError, AttributeError):
|
|
124
|
+
return PLACEHOLDER_PRICING
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# Fallback header, used ONLY when the target file is absent (e.g. a fresh write to a new path).
|
|
128
|
+
# A normal save preserves the existing file's own leading comment block verbatim (see
|
|
129
|
+
# :func:`_leading_comment_block`), so the curated methodology note is never replaced or drifted.
|
|
130
|
+
PRICING_HEADER = """\
|
|
131
|
+
# Cloud-equivalent reference pricing for the "spend avoided" rollup.
|
|
132
|
+
#
|
|
133
|
+
# Methodology: for each routed task, estimate what it WOULD have cost on a paid frontier API, valued
|
|
134
|
+
# at a reference model's per-million-token price. The rollup multiplies estimated tokens (a chars/4
|
|
135
|
+
# heuristic over the visible prompt + response) by these rates. Values are US dollars per 1,000,000
|
|
136
|
+
# tokens.
|
|
137
|
+
#
|
|
138
|
+
# `placeholder: true` makes `tanglebrain --stats` flag every figure as PLACEHOLDER (use it if you
|
|
139
|
+
# fork these reference rates before re-checking them). Edited via `tanglebrain-gui` or by hand.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _leading_comment_block(text: str) -> str:
|
|
144
|
+
"""Return the file's leading run of comment/blank lines (its header), or ``""`` if none.
|
|
145
|
+
|
|
146
|
+
Used to preserve a pricing file's curated header verbatim across a save, so no documentation
|
|
147
|
+
is lost or replaced. Stops at the first non-comment, non-blank line (the first YAML key).
|
|
148
|
+
"""
|
|
149
|
+
out: list[str] = []
|
|
150
|
+
for line in text.splitlines():
|
|
151
|
+
if line.startswith("#") or not line.strip():
|
|
152
|
+
out.append(line)
|
|
153
|
+
else:
|
|
154
|
+
break
|
|
155
|
+
while out and not out[-1].strip(): # drop trailing blank lines before the keys
|
|
156
|
+
out.pop()
|
|
157
|
+
return "\n".join(out) + "\n" if out else ""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def validate_pricing(data: dict) -> Pricing:
|
|
161
|
+
"""Strictly validate raw pricing fields and build a :class:`Pricing`.
|
|
162
|
+
|
|
163
|
+
Unlike :func:`load_pricing` (lenient — bad reads fall back to a placeholder), this rejects
|
|
164
|
+
invalid input so the panel never persists garbage.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
data: ``{reference_model, input_per_mtok, output_per_mtok, placeholder}``.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
A validated :class:`Pricing`.
|
|
171
|
+
|
|
172
|
+
Raises:
|
|
173
|
+
ValueError: If a field is missing, the wrong type, a non-finite/negative rate, or an
|
|
174
|
+
empty ``reference_model``.
|
|
175
|
+
"""
|
|
176
|
+
if not isinstance(data, dict):
|
|
177
|
+
raise ValueError("pricing must be an object")
|
|
178
|
+
|
|
179
|
+
model = data.get("reference_model")
|
|
180
|
+
if not isinstance(model, str) or not model.strip():
|
|
181
|
+
raise ValueError("reference_model must be a non-empty string")
|
|
182
|
+
|
|
183
|
+
rates = {}
|
|
184
|
+
for key in ("input_per_mtok", "output_per_mtok"):
|
|
185
|
+
value = data.get(key)
|
|
186
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
187
|
+
raise ValueError(f"{key} must be a number")
|
|
188
|
+
value = float(value)
|
|
189
|
+
if value != value or value in (float("inf"), float("-inf")): # NaN / inf guard
|
|
190
|
+
raise ValueError(f"{key} must be finite")
|
|
191
|
+
if value < 0:
|
|
192
|
+
raise ValueError(f"{key} must be >= 0")
|
|
193
|
+
rates[key] = value
|
|
194
|
+
|
|
195
|
+
placeholder = data.get("placeholder", False)
|
|
196
|
+
if not isinstance(placeholder, bool):
|
|
197
|
+
raise ValueError("placeholder must be a boolean")
|
|
198
|
+
|
|
199
|
+
return Pricing(
|
|
200
|
+
reference_model=model.strip(),
|
|
201
|
+
input_per_mtok=rates["input_per_mtok"],
|
|
202
|
+
output_per_mtok=rates["output_per_mtok"],
|
|
203
|
+
is_placeholder=placeholder,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _backup_dir() -> Path:
|
|
208
|
+
"""Return the directory for config backups (under the state dir, never the repo config dir)."""
|
|
209
|
+
base = os.environ.get(STATE_DIR_ENV)
|
|
210
|
+
root = Path(base).expanduser() if base else Path.home() / DEFAULT_STATE_SUBDIR
|
|
211
|
+
return root / "backups"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _atomic_write(path: Path, text: str) -> None:
|
|
215
|
+
"""Write ``text`` to ``path`` atomically (temp file in the same dir, then ``os.replace``)."""
|
|
216
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
217
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
218
|
+
tmp.write_text(text, encoding="utf-8")
|
|
219
|
+
os.replace(tmp, path)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _render_pricing(pricing: Pricing, header: str) -> str:
|
|
223
|
+
"""Render a :class:`Pricing` to YAML text beneath ``header``.
|
|
224
|
+
|
|
225
|
+
``reference_model`` is emitted via ``json.dumps`` — a JSON string is valid YAML and safely
|
|
226
|
+
quotes/escapes any colons, quotes, unicode, or backslashes. Float rates use Python's ``repr``
|
|
227
|
+
(valid YAML), which round-trips exactly through :func:`load_pricing`.
|
|
228
|
+
"""
|
|
229
|
+
return (
|
|
230
|
+
header
|
|
231
|
+
+ f"placeholder: {str(pricing.is_placeholder).lower()}\n"
|
|
232
|
+
+ f"reference_model: {json.dumps(pricing.reference_model)}\n"
|
|
233
|
+
+ f"input_per_mtok: {pricing.input_per_mtok}\n"
|
|
234
|
+
+ f"output_per_mtok: {pricing.output_per_mtok}\n"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def save_pricing(pricing: Pricing, path: str | os.PathLike[str] | None = None) -> None:
|
|
239
|
+
"""Persist pricing to the config YAML — header-preserving, with a backup, written atomically.
|
|
240
|
+
|
|
241
|
+
Preserves the target's existing leading comment block verbatim (falling back to
|
|
242
|
+
:data:`PRICING_HEADER` only when the file is absent), backs up any existing file to
|
|
243
|
+
``<state_dir>/backups/pricing-<ts>.yaml``, then atomically replaces the target.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
pricing: The validated pricing to write (see :func:`validate_pricing`).
|
|
247
|
+
path: Target YAML path. Defaults to the packaged ``config/pricing.yaml``.
|
|
248
|
+
"""
|
|
249
|
+
target = Path(path) if path is not None else default_pricing_path()
|
|
250
|
+
header = PRICING_HEADER
|
|
251
|
+
if target.exists():
|
|
252
|
+
existing = target.read_text(encoding="utf-8")
|
|
253
|
+
block = _leading_comment_block(existing)
|
|
254
|
+
if block.strip():
|
|
255
|
+
header = block # keep the curated header verbatim — no drift, no doc loss
|
|
256
|
+
backup_dir = _backup_dir()
|
|
257
|
+
backup_dir.mkdir(parents=True, exist_ok=True)
|
|
258
|
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S_%fZ") # sub-second: no same-second collision
|
|
259
|
+
shutil.copy2(target, backup_dir / f"pricing-{stamp}.yaml")
|
|
260
|
+
_atomic_write(target, _render_pricing(pricing, header))
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def estimate_tokens(text: str) -> int:
|
|
264
|
+
"""Estimate the token count of ``text`` via the uniform ``chars/4`` heuristic.
|
|
265
|
+
|
|
266
|
+
This is an approximation, applied identically to every tier (CLI subs expose no real counts).
|
|
267
|
+
Empty/falsy text counts as 0; any non-empty text is at least 1 token.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
text: The prompt or response text.
|
|
271
|
+
|
|
272
|
+
Returns:
|
|
273
|
+
The estimated token count (``>= 0``).
|
|
274
|
+
"""
|
|
275
|
+
if not text:
|
|
276
|
+
return 0
|
|
277
|
+
return max(1, len(text) // _CHARS_PER_TOKEN)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def cloud_equiv_usd(in_tokens: int, out_tokens: int, pricing: Pricing) -> float:
|
|
281
|
+
"""Compute the cloud-equivalent cost of a task at the reference frontier price.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
in_tokens: Estimated input (prompt) tokens.
|
|
285
|
+
out_tokens: Estimated output (completion) tokens.
|
|
286
|
+
pricing: The reference pricing to apply.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
The estimated US-dollar cost on the reference frontier API.
|
|
290
|
+
"""
|
|
291
|
+
return (
|
|
292
|
+
in_tokens / 1_000_000 * pricing.input_per_mtok
|
|
293
|
+
+ out_tokens / 1_000_000 * pricing.output_per_mtok
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def record_task(
|
|
298
|
+
*,
|
|
299
|
+
path: str,
|
|
300
|
+
entry: object,
|
|
301
|
+
prompt: str,
|
|
302
|
+
response: str,
|
|
303
|
+
kind: str = "task",
|
|
304
|
+
task_id: str | None = None,
|
|
305
|
+
parent_task_id: str | None = None,
|
|
306
|
+
log_path: str | os.PathLike[str] | None = None,
|
|
307
|
+
pricing: Pricing | None = None,
|
|
308
|
+
) -> None:
|
|
309
|
+
"""Append one usage record for a routed task or a delegated sub-call. Never raises.
|
|
310
|
+
|
|
311
|
+
A logging failure is dropped — measurement is a side-effect that must never affect the returned
|
|
312
|
+
answer.
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
path: Which execution path served the work — ``router`` | ``local`` | ``model`` |
|
|
316
|
+
``delegate``.
|
|
317
|
+
entry: The served :class:`~tanglebrain.roster.RosterEntry` (read for ``tier``/``id``); may
|
|
318
|
+
be ``None`` (e.g. the router didn't surface one), in which case both are ``"unknown"``.
|
|
319
|
+
prompt: The prompt (for input-token estimation).
|
|
320
|
+
response: The returned response text (for output-token estimation).
|
|
321
|
+
kind: ``"task"`` for a top-level routed task (the default; what the spend-avoided headline
|
|
322
|
+
counts) or ``"delegate"`` for a delegated sub-call. Delegate records are rolled up
|
|
323
|
+
**separately** so a sub-call's saving is never double-counted against its parent task.
|
|
324
|
+
task_id: For a top-level task, the id minted for this routed task (so its delegated sub-calls
|
|
325
|
+
can be linked back to it). Omitted from the record when ``None``.
|
|
326
|
+
parent_task_id: For a delegated sub-call, the id of the top-level task that spawned it (read
|
|
327
|
+
from :data:`PARENT_TASK_ID_ENV`). Omitted from the record when ``None`` — e.g. a delegate
|
|
328
|
+
invoked outside a propagated task, which rolls up as ``unlinked``.
|
|
329
|
+
log_path: Override the usage-log path (tests inject a temp path). Defaults to
|
|
330
|
+
:func:`default_log_path`.
|
|
331
|
+
pricing: Override the pricing. Defaults to :func:`load_pricing`.
|
|
332
|
+
"""
|
|
333
|
+
try:
|
|
334
|
+
if pricing is None:
|
|
335
|
+
pricing = load_pricing()
|
|
336
|
+
tier = getattr(entry, "tier", None) or "unknown"
|
|
337
|
+
model = getattr(entry, "id", None) or "unknown"
|
|
338
|
+
in_tok = estimate_tokens(prompt)
|
|
339
|
+
out_tok = estimate_tokens(response)
|
|
340
|
+
equiv = cloud_equiv_usd(in_tok, out_tok, pricing)
|
|
341
|
+
# A paid `api` task incurs real spend, so it avoids nothing (avoided = 0); every other tier
|
|
342
|
+
# routes work off a paid frontier API, so it avoids the full cloud-equivalent.
|
|
343
|
+
avoided = 0.0 if tier == "api" else equiv
|
|
344
|
+
record = {
|
|
345
|
+
"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
346
|
+
"kind": str(kind),
|
|
347
|
+
"path": str(path),
|
|
348
|
+
"tier": str(tier),
|
|
349
|
+
"model": str(model),
|
|
350
|
+
"in_tokens_est": in_tok,
|
|
351
|
+
"out_tokens_est": out_tok,
|
|
352
|
+
"cloud_equiv_usd": round(equiv, 6),
|
|
353
|
+
"spend_avoided_usd": round(avoided, 6),
|
|
354
|
+
"pricing_ref": pricing.reference_model,
|
|
355
|
+
}
|
|
356
|
+
# Optional linkage fields — only written when present, so existing records/readers that
|
|
357
|
+
# never set them are unaffected (a missing field reads as "no linkage").
|
|
358
|
+
if task_id is not None:
|
|
359
|
+
record["task_id"] = str(task_id)
|
|
360
|
+
if parent_task_id is not None:
|
|
361
|
+
record["parent_task_id"] = str(parent_task_id)
|
|
362
|
+
target = Path(log_path) if log_path is not None else default_log_path()
|
|
363
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
364
|
+
with _LOG_LOCK:
|
|
365
|
+
with target.open("a", encoding="utf-8") as fh:
|
|
366
|
+
fh.write(json.dumps(record) + "\n")
|
|
367
|
+
except Exception:
|
|
368
|
+
# Measurement is a side-effect: a failure here must never affect the returned answer.
|
|
369
|
+
return
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _as_int(value: object) -> int:
|
|
373
|
+
"""Coerce a stored numeric field to int, defaulting to 0 on any bad value."""
|
|
374
|
+
try:
|
|
375
|
+
return int(value) # type: ignore[arg-type]
|
|
376
|
+
except (ValueError, TypeError):
|
|
377
|
+
return 0
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _as_float(value: object) -> float:
|
|
381
|
+
"""Coerce a stored numeric field to float, defaulting to 0.0 on any bad value."""
|
|
382
|
+
try:
|
|
383
|
+
return float(value) # type: ignore[arg-type]
|
|
384
|
+
except (ValueError, TypeError):
|
|
385
|
+
return 0.0
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def read_records(log_path: str | os.PathLike[str] | None = None) -> list[dict]:
|
|
389
|
+
"""Read all usage records from the log, skipping malformed lines.
|
|
390
|
+
|
|
391
|
+
Args:
|
|
392
|
+
log_path: Override the usage-log path. Defaults to :func:`default_log_path`.
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
The parsed records in file (chronological) order. An absent log yields ``[]``.
|
|
396
|
+
"""
|
|
397
|
+
target = Path(log_path) if log_path is not None else default_log_path()
|
|
398
|
+
records: list[dict] = []
|
|
399
|
+
try:
|
|
400
|
+
text = target.read_text(encoding="utf-8")
|
|
401
|
+
except OSError:
|
|
402
|
+
return records
|
|
403
|
+
for line in text.splitlines():
|
|
404
|
+
line = line.strip()
|
|
405
|
+
if not line:
|
|
406
|
+
continue
|
|
407
|
+
try:
|
|
408
|
+
obj = json.loads(line)
|
|
409
|
+
except json.JSONDecodeError:
|
|
410
|
+
continue
|
|
411
|
+
if isinstance(obj, dict):
|
|
412
|
+
records.append(obj)
|
|
413
|
+
return records
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def rollup(records: list[dict]) -> dict:
|
|
417
|
+
"""Aggregate usage records into a summary.
|
|
418
|
+
|
|
419
|
+
Args:
|
|
420
|
+
records: The records from :func:`read_records`.
|
|
421
|
+
|
|
422
|
+
Returns:
|
|
423
|
+
A dict with: ``tasks`` (int), ``by_tier`` (tier → count), ``in_tokens_est`` /
|
|
424
|
+
``out_tokens_est`` (summed estimates), and ``cloud_equiv_usd`` / ``spend_avoided_usd``
|
|
425
|
+
(summed dollars) — all over **top-level tasks only** — plus ``delegates``, a separate
|
|
426
|
+
sub-rollup of delegated sub-calls ``{count, by_backend: {model: {count, in_tokens_est,
|
|
427
|
+
out_tokens_est}}, by_parent: {parent_task_id: {count, by_backend: {model: count}}},
|
|
428
|
+
in_tokens_est, out_tokens_est, cloud_equiv_usd}``. ``by_parent`` groups each delegate under
|
|
429
|
+
the top-level task that spawned it (via ``parent_task_id``); delegates with no
|
|
430
|
+
``parent_task_id`` are grouped under the sentinel ``"unlinked"``. Delegate records are kept
|
|
431
|
+
out of the headline so a sub-call's saving is never double-counted against its parent task;
|
|
432
|
+
their cloud-equiv is informational. A record without a ``kind`` field counts as a task.
|
|
433
|
+
"""
|
|
434
|
+
summary: dict = {
|
|
435
|
+
"tasks": 0,
|
|
436
|
+
"by_tier": {},
|
|
437
|
+
"in_tokens_est": 0,
|
|
438
|
+
"out_tokens_est": 0,
|
|
439
|
+
"cloud_equiv_usd": 0.0,
|
|
440
|
+
"spend_avoided_usd": 0.0,
|
|
441
|
+
}
|
|
442
|
+
delegates: dict = {
|
|
443
|
+
"count": 0,
|
|
444
|
+
"by_backend": {},
|
|
445
|
+
"by_parent": {},
|
|
446
|
+
"in_tokens_est": 0,
|
|
447
|
+
"out_tokens_est": 0,
|
|
448
|
+
"cloud_equiv_usd": 0.0,
|
|
449
|
+
}
|
|
450
|
+
for r in records:
|
|
451
|
+
in_tok = _as_int(r.get("in_tokens_est"))
|
|
452
|
+
out_tok = _as_int(r.get("out_tokens_est"))
|
|
453
|
+
if str(r.get("kind", "task")) == "delegate":
|
|
454
|
+
delegates["count"] += 1
|
|
455
|
+
model = str(r.get("model", "unknown"))
|
|
456
|
+
backend = delegates["by_backend"].setdefault(
|
|
457
|
+
model, {"count": 0, "in_tokens_est": 0, "out_tokens_est": 0}
|
|
458
|
+
)
|
|
459
|
+
backend["count"] += 1
|
|
460
|
+
backend["in_tokens_est"] += in_tok
|
|
461
|
+
backend["out_tokens_est"] += out_tok
|
|
462
|
+
# Per-parent tree: link this sub-call to the top-level task that spawned it. A delegate
|
|
463
|
+
# with no parent_task_id (run outside a propagated task) groups under "unlinked".
|
|
464
|
+
parent_id = r.get("parent_task_id")
|
|
465
|
+
parent_key = str(parent_id) if parent_id not in (None, "") else "unlinked"
|
|
466
|
+
parent = delegates["by_parent"].setdefault(parent_key, {"count": 0, "by_backend": {}})
|
|
467
|
+
parent["count"] += 1
|
|
468
|
+
parent["by_backend"][model] = parent["by_backend"].get(model, 0) + 1
|
|
469
|
+
delegates["in_tokens_est"] += in_tok
|
|
470
|
+
delegates["out_tokens_est"] += out_tok
|
|
471
|
+
delegates["cloud_equiv_usd"] += _as_float(r.get("cloud_equiv_usd"))
|
|
472
|
+
continue
|
|
473
|
+
summary["tasks"] += 1
|
|
474
|
+
tier = str(r.get("tier", "unknown"))
|
|
475
|
+
summary["by_tier"][tier] = summary["by_tier"].get(tier, 0) + 1
|
|
476
|
+
summary["in_tokens_est"] += in_tok
|
|
477
|
+
summary["out_tokens_est"] += out_tok
|
|
478
|
+
summary["cloud_equiv_usd"] += _as_float(r.get("cloud_equiv_usd"))
|
|
479
|
+
summary["spend_avoided_usd"] += _as_float(r.get("spend_avoided_usd"))
|
|
480
|
+
summary["cloud_equiv_usd"] = round(summary["cloud_equiv_usd"], 4)
|
|
481
|
+
summary["spend_avoided_usd"] = round(summary["spend_avoided_usd"], 4)
|
|
482
|
+
delegates["cloud_equiv_usd"] = round(delegates["cloud_equiv_usd"], 4)
|
|
483
|
+
summary["delegates"] = delegates
|
|
484
|
+
return summary
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def format_rollup(summary: dict, pricing: Pricing) -> str:
|
|
488
|
+
"""Render a rollup summary as a human-readable block for the CLI.
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
summary: The aggregate from :func:`rollup`.
|
|
492
|
+
pricing: The currently-configured pricing (for the reference-model label + placeholder
|
|
493
|
+
caveat). Per-record costs were computed when each task ran; this only labels the figure.
|
|
494
|
+
|
|
495
|
+
Returns:
|
|
496
|
+
A multi-line string suitable for printing.
|
|
497
|
+
"""
|
|
498
|
+
lines = [
|
|
499
|
+
"TangleBrain — spend avoided (cloud-equivalent)",
|
|
500
|
+
f" Tasks routed: {summary.get('tasks', 0)}",
|
|
501
|
+
]
|
|
502
|
+
by_tier = summary.get("by_tier") or {}
|
|
503
|
+
if by_tier:
|
|
504
|
+
tiers = ", ".join(f"{k} {v}" for k, v in sorted(by_tier.items()))
|
|
505
|
+
lines.append(f" By tier: {tiers}")
|
|
506
|
+
lines.append(
|
|
507
|
+
f" Est. tokens: in {summary.get('in_tokens_est', 0):,} / "
|
|
508
|
+
f"out {summary.get('out_tokens_est', 0):,}"
|
|
509
|
+
)
|
|
510
|
+
lines.append(f" Spend avoided: ${summary.get('spend_avoided_usd', 0.0):,.2f}")
|
|
511
|
+
lines.append(f" Pricing ref: {pricing.reference_model}")
|
|
512
|
+
if pricing.is_placeholder:
|
|
513
|
+
lines.append(
|
|
514
|
+
" ⚠ pricing: PLACEHOLDER — figures are illustrative; set real rates in "
|
|
515
|
+
"config/pricing.yaml and flip placeholder to false."
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
delegates = summary.get("delegates") or {}
|
|
519
|
+
if delegates.get("count"):
|
|
520
|
+
lines.append("")
|
|
521
|
+
lines.append(" Delegated sub-tasks (offloaded by orchestrators)")
|
|
522
|
+
lines.append(f" Count: {delegates.get('count', 0)}")
|
|
523
|
+
by_backend = delegates.get("by_backend") or {}
|
|
524
|
+
if by_backend:
|
|
525
|
+
backends = ", ".join(
|
|
526
|
+
f"{model} {info.get('count', 0)}" for model, info in sorted(by_backend.items())
|
|
527
|
+
)
|
|
528
|
+
lines.append(f" By backend: {backends}")
|
|
529
|
+
by_parent = delegates.get("by_parent") or {}
|
|
530
|
+
if by_parent:
|
|
531
|
+
linked = [k for k in by_parent if k != "unlinked"]
|
|
532
|
+
unlinked = (by_parent.get("unlinked") or {}).get("count", 0)
|
|
533
|
+
if linked:
|
|
534
|
+
tree = f"{len(linked)} parent task(s)"
|
|
535
|
+
if unlinked:
|
|
536
|
+
tree += f", {unlinked} unlinked"
|
|
537
|
+
else:
|
|
538
|
+
tree = f"{unlinked} unlinked" # all sub-calls ran outside a propagated task
|
|
539
|
+
lines.append(f" Linked to: {tree}")
|
|
540
|
+
lines.append(
|
|
541
|
+
f" Est. tokens: in {delegates.get('in_tokens_est', 0):,} / "
|
|
542
|
+
f"out {delegates.get('out_tokens_est', 0):,}"
|
|
543
|
+
)
|
|
544
|
+
lines.append(
|
|
545
|
+
f" Cloud-equiv: ${delegates.get('cloud_equiv_usd', 0.0):,.2f} "
|
|
546
|
+
"(informational — already credited within parent tasks)"
|
|
547
|
+
)
|
|
548
|
+
return "\n".join(lines)
|