Repository navigation
Expand file tree
/
Copy pathtracker.py
More file actions
1065 lines (929 loc) · 46.9 KB
/
Copy pathtracker.py
File metadata and controls
1065 lines (929 loc) · 46.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
tracker.py – Per-conversation token, timing, cost & tool-call metrics.
Storage layout (mirrors ChatHistoryManager):
/app/data/chats/<thread_id>/usage_stats.json ← one file per conversation
/app/data/projects/<name>/logs/usage_log.json ← auto-created on workspace setup
The metrics panel always shows the CURRENT conversation only.
On thread switch the GUI calls:
tracker.switch_thread(thread_id)
which saves the current conversation, resets UsageMetrics, and pre-loads
the new conversation's saved totals — so the panel updates instantly.
"""
from __future__ import annotations
import json
import os
import re
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Union
import requests
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.outputs import LLMResult
from PySide6.QtCore import QObject, Signal
import logging
log = logging.getLogger("imagentj")
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
CHATS_DIR = Path(os.environ.get("CHAT_DATA_PATH", "/app/data/chats"))
PRICE_TABLE: dict[str, tuple[float, float, float]] = {
# model-name-substring input output cache_factor
# cache_factor = fraction of p_in charged for cached tokens (None = no caching)
#
# Keys match as substrings, LONGEST KEY FIRST (see _price_for_model), so
# "gpt-5.4-mini" wins over "gpt-5.4" no matter what order they appear in here.
# Prefer UNPREFIXED keys: the tracker sees the provider prefix stripped on
# OpenAI-direct installs ("gpt-5.4") but intact via OpenRouter
# ("openai/gpt-5.4"), and a bare key matches both spellings.
#
# ── models this deployment configures (imagentj_config.yaml) ──────────────
# Rates verified 2026-07-29 against developers.openai.com/api/docs/pricing
# and openrouter.ai. Cached input is 10% of input on all of them -> 0.10.
"gpt-5.4-mini": (0.75, 4.50, 0.10), # curator / Librarian
"gpt-5.4-nano": (0.20, 1.25, 0.10), # nano fast-path
"gpt-5.4": (2.50, 15.00, 0.10), # supervisor
"gpt-5.3-codex": (1.75, 14.00, 0.10), # worker + analyst
"gemini-3.5-flash": (1.50, 9.00, 0.10), # vision judge
"gpt-4o-mini": (0.15, 0.60, 0.50),
"gpt-4o": (2.50, 10.00, 0.50),
"gpt-4.1-nano": (0.10, 0.40, 0.25),
"gpt-4.1-mini": (0.40, 1.60, 0.25),
"gpt-4.1": (2.00, 8.00, 0.25),
"o4-mini": (1.10, 4.40, 0.50),
"o4": (10.00, 40.00, 0.50),
# Bare keys, not "openai/…": a prefixed key is LONGER than the bare key for a
# more specific model, so "openai/gpt-5" used to shadow "gpt-5.4" under
# longest-first matching. Bare keys match both spellings and sort correctly.
"gpt-5-nano": (0.05, 0.40, 0.50),
"gpt-5.2": (1.75, 14.00, 0.50),
# Verified live against openrouter.ai/api/v1/models on 2026-08-10: prompt
# $0.10/Mtok, completion $0.60/Mtok, cache read $0.01/Mtok. The previous
# (1.00, 6.00) was 10x high on both, so every estimated cost for this model
# was inflated by an order of magnitude.
"gpt-5.6-luna": (0.10, 0.60, 0.10),
"gpt-5": (1.25, 10.00, 0.10), # 5.x fallback (unknown 5.x)
"default": (1.00, 3.00, None), # fallback, no cache discount
"gemini-3-flash-preview": (0.50, 3.00, None),
"kimi-k2.5": (0.45, 2.25, None),
"claude-opus-4.6": (10.00, 37.50, None),
"deepseek-v3.2": (0.25, 0.40, None),
"anthropic/claude-haiku-4.5":(1.00, 5.00, None),
"qwen/qwen3-235b-a22b-2507": (0.071, 0.10, None),
"moonshotai/kimi-k2.5": (0.45, 2.25, None),
"z-ai/glm-5": (0.95, 2.55, None),
"mistralai/mistral-small-3.2-24b-instruct": (0.075, 0.2, None),
"google/gemini-2.5-pro": (1.25, 10.00, None),
"google/gemini-3.1-flash-lite-preview": (0.25, 1.50, None),
"anthropic/claude-opus-4.6": (5.00, 25.00, None),
"anthropic/claude-sonnet-4.6":(3.00, 15.00, None),
"google/gemini-3-pro-preview":(2.00, 12.00, None),
"google/gemini-3.1-pro-preview-customtools": (2.00, 12.00, None),
}
# Longest-first so the most specific key wins: "gpt-5.4-mini" must beat "gpt-5.4",
# and "openai/gpt-5.3-codex" must beat "openai/gpt-5". The old first-match-on-dict-
# order rule made correctness depend on how the table happened to be written, which
# is how every gpt-5.x model silently fell through to "default" ($1/$3, no cache
# discount) and produced cost figures unrelated to real pricing.
_PRICE_KEYS_BY_SPECIFICITY = sorted(
(k for k in PRICE_TABLE if k != "default"), key=len, reverse=True
)
def _price_for_model(model_name: str) -> tuple[float, float, float | None]:
lower = model_name.lower()
for key in _PRICE_KEYS_BY_SPECIFICITY:
if key in lower:
return PRICE_TABLE[key]
return PRICE_TABLE["default"]
# ---------------------------------------------------------------------------
# OpenRouter actual-cost fetcher (optional — only active when key is set)
# ---------------------------------------------------------------------------
class _OpenRouterCostFetcher:
"""
Session-level actual cost tracking via OpenRouter's /auth/key ``usage``
field (per-key, not account-wide — see OpenRouter docs).
Usage counter updates on OR's side with a delay after a request completes,
so we record a baseline at conversation start and poll after a configurable
delay at query end to let the counter settle.
"""
_URL = "https://openrouter.ai/api/v1/auth/key"
def __init__(self, api_key: str):
self._api_key = api_key
self._baseline: float | None = None
self._baseline_lock = threading.Lock()
def _fetch_usage(self) -> float | None:
try:
r = requests.get(
self._URL,
headers={"Authorization": f"Bearer {self._api_key}"},
timeout=6,
)
if r.status_code == 200:
return r.json().get("data", {}).get("usage")
except Exception:
pass
return None
def init_baseline(self):
"""
Snapshot the current OR usage as the baseline for this conversation.
Runs in a background thread so it never blocks the GUI.
"""
def _run():
usage = self._fetch_usage()
with self._baseline_lock:
self._baseline = usage
if usage is not None:
log.debug(f"OpenRouter baseline usage: ${usage:.4f}")
else:
log.warning("OpenRouter: baseline fetch failed")
threading.Thread(target=_run, daemon=True).start()
def get_session_delta(self) -> float | None:
"""
Return ``current_usage − baseline`` in USD without any sleep.
Returns None if either value is unavailable.
"""
current = self._fetch_usage()
with self._baseline_lock:
baseline = self._baseline
if current is None or baseline is None:
return None
return max(0.0, current - baseline)
# ---------------------------------------------------------------------------
# Soft-error detection (execution tools only)
# ---------------------------------------------------------------------------
_SOFT_ERROR_RE = re.compile(
r"\b(error|exception|warning|failed|failure|"
r"missingmethodexception|missingmethod|no such method|"
r"groovyruntimeexception|scriptexception|"
r"could not|unable to|traceback|illegalargument|"
r"nullpointerexception|indexoutofbounds)\b",
re.IGNORECASE,
)
_EXECUTION_TOOLS = {"execute_script", "run_script_safe", "run_python_code"}
# ---------------------------------------------------------------------------
# Per-query record
# ---------------------------------------------------------------------------
@dataclass
class QueryRecord:
timestamp: str = ""
thread_id: str = ""
prompt_preview: str = ""
model: str = ""
thinking_seconds: float = 0.0
input_tokens: int = 0
output_tokens: int = 0
total_tokens: int = 0
cost_usd: float = 0.0
tool_calls: int = 0
failed_tool_calls: int = 0
soft_error_tool_calls: int = 0
# ── new ──────────────────────────────────────────────────────────────
model_breakdown: dict = field(default_factory=dict)
# e.g. {"google/gemini-3-pro-preview": {"input": 70000, "output": 2000, "cost": 0.148},
# "anthropic/claude-haiku-4.5": {"input": 4598, "output": 366, "cost": 0.007}}
tool_call_log: list = field(default_factory=list)
# e.g. [{"tool": "imagej_coder", "status": "ok"},
# {"tool": "execute_script", "status": "soft_error"}]
def to_dict(self) -> dict:
return {
"timestamp": self.timestamp,
"thread_id": self.thread_id,
"prompt_preview": self.prompt_preview,
"model": self.model,
"thinking_seconds": round(self.thinking_seconds, 2),
"input_tokens": self.input_tokens,
"output_tokens": self.output_tokens,
"total_tokens": self.total_tokens,
"cost_usd": round(self.cost_usd, 6),
"tool_calls": self.tool_calls,
"failed_tool_calls": self.failed_tool_calls,
"soft_error_tool_calls": self.soft_error_tool_calls,
"model_breakdown": self.model_breakdown, # ← new
"tool_call_log": self.tool_call_log, # ← new
}
# ---------------------------------------------------------------------------
# Cumulative metrics — always reflects the CURRENT conversation
# ---------------------------------------------------------------------------
@dataclass
class UsageMetrics:
input_tokens: int = 0
output_tokens: int = 0
thinking_seconds: float = 0.0
cost_usd: float = 0.0
tool_calls: int = 0
failed_tool_calls: int = 0
soft_error_tool_calls: int = 0
_thinking_start: float = field(default=0.0, repr=False, compare=False)
_is_thinking: bool = field(default=False, repr=False, compare=False)
_lock: threading.RLock = field(
default_factory=threading.RLock, repr=False, compare=False
)
def start_thinking(self):
with self._lock:
self._thinking_start = time.monotonic()
self._is_thinking = True
def stop_thinking(self) -> float:
with self._lock:
if not self._is_thinking:
return 0.0
elapsed = time.monotonic() - self._thinking_start
self.thinking_seconds += elapsed
self._is_thinking = False
return elapsed
def live_thinking_seconds(self) -> float:
extra = (time.monotonic() - self._thinking_start) if self._is_thinking else 0.0
return self.thinking_seconds + extra
@property
def total_tokens(self) -> int:
return self.input_tokens + self.output_tokens
def snapshot(self) -> dict:
with self._lock:
return {
"input_tokens": self.input_tokens,
"output_tokens": self.output_tokens,
"total_tokens": self.total_tokens,
"thinking_seconds": round(self.live_thinking_seconds(), 1),
"cost_usd": round(self.cost_usd, 6),
"tool_calls": self.tool_calls,
"failed_tool_calls": self.failed_tool_calls,
"soft_error_tool_calls": self.soft_error_tool_calls,
}
def reset(self):
with self._lock:
self.input_tokens = 0
self.output_tokens = 0
self.thinking_seconds = 0.0
self._thinking_start = 0.0
self._is_thinking = False
self.cost_usd = 0.0
self.tool_calls = 0
self.failed_tool_calls = 0
self.soft_error_tool_calls = 0
def load_from_totals(self, totals: dict):
"""Pre-populate from a saved totals dict on thread switch."""
with self._lock:
self.input_tokens = totals.get("input_tokens", 0)
self.output_tokens = totals.get("output_tokens", 0)
self.thinking_seconds = totals.get("thinking_seconds", 0.0)
self.cost_usd = totals.get("cost_usd", 0.0)
self.tool_calls = totals.get("tool_calls", 0)
self.failed_tool_calls = totals.get("failed_tool_calls", 0)
self.soft_error_tool_calls = totals.get("soft_error_tool_calls", 0)
# ---------------------------------------------------------------------------
# Qt signal bridge
# ---------------------------------------------------------------------------
class MetricsSignalBridge(QObject):
updated = Signal(dict) # full snapshot → MetricsPanelWidget.update_metrics
# ---------------------------------------------------------------------------
# JSON helpers
# ---------------------------------------------------------------------------
def _read_json(path: Path) -> dict:
if path.exists():
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError):
pass
return {}
def _write_json(path: Path, data: dict):
try:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
except Exception as e:
pass # never let I/O crash the agent
# ---------------------------------------------------------------------------
# Conversation-scoped logger
# ---------------------------------------------------------------------------
class ConversationLogger:
"""
Writes /app/data/chats/<thread_id>/usage_stats.json
and (once a project workspace exists)
/app/data/projects/<name>/logs/usage_log.json
"""
def __init__(self, chats_dir: Path = CHATS_DIR):
self._chats_dir = chats_dir
self._thread_id: str = ""
self._project_log: Path | None = None
self._project_name: str = ""
# ── per-conversation file ─────────────────────────────────────────────
def _conv_path(self, thread_id: str | None = None) -> Path:
tid = thread_id or self._thread_id
return self._chats_dir / tid / "usage_stats.json"
def set_thread(self, thread_id: str):
# Always reset — prevents bleed between conversations
self._project_log = None
self._project_name = ""
self._thread_id = thread_id
path = self._conv_path()
if not path.exists():
self._write_conv({
"thread_id": thread_id,
"created": time.strftime("%Y-%m-%dT%H:%M:%S"),
"queries": [],
"totals": {},
})
else:
conv_data = _read_json(path)
saved_root = conv_data.get("project_root")
if saved_root:
root_path = Path(saved_root)
if root_path.exists():
self._project_log = root_path / "logs" / "usage_log.json"
self._project_name = root_path.name
log.debug(f"Restored project log: {self._project_log}")
self._sync_project() # immediate sync on restore
else:
conv_data.pop("project_root", None)
self._write_conv(conv_data)
def load_totals(self, thread_id: str) -> dict:
"""Return saved cumulative totals for a thread (empty dict if none)."""
data = _read_json(self._conv_path(thread_id))
return data.get("totals", {})
def append_query(self, record: QueryRecord, snapshot: dict):
if not self._thread_id:
return
data = _read_json(self._conv_path())
data.setdefault("queries", []).append(record.to_dict())
qs = data["queries"]
data["totals"] = {
"query_count": len(qs),
"input_tokens": sum(q["input_tokens"] for q in qs),
"output_tokens": sum(q["output_tokens"] for q in qs),
"total_tokens": sum(q["total_tokens"] for q in qs),
"thinking_seconds": round(sum(q["thinking_seconds"] for q in qs), 2),
"cost_usd": round(sum(q["cost_usd"] for q in qs), 6),
"tool_calls": sum(q["tool_calls"] for q in qs),
"failed_tool_calls": sum(q["failed_tool_calls"] for q in qs),
"soft_error_tool_calls": sum(q["soft_error_tool_calls"] for q in qs),
}
self._write_conv(data)
# ── project log ───────────────────────────────────────────────────────
def set_project_path(self, project_root: Path, project_name: str):
if self._project_log is not None:
return
self._project_log = project_root / "logs" / "usage_log.json"
self._project_name = project_name
# Persist so it survives restarts
conv_data = _read_json(self._conv_path())
conv_data["project_root"] = str(project_root)
self._write_conv(conv_data) # also triggers _sync_project
log.debug(f"Project log initialised at: {self._project_log}")
def _append_to_project(self, record: QueryRecord):
if not self._project_log:
return
# Just mirror the full conversation file — always in sync, no separate logic
conv_data = _read_json(self._conv_path())
_write_json(self._project_log, conv_data)
def update_query_cost(self, timestamp: str, actual_cost: float):
"""Patch cost_usd for the query matching *timestamp* and recompute totals."""
if not self._thread_id:
return
data = _read_json(self._conv_path())
queries = data.get("queries", [])
for q in reversed(queries):
if q.get("timestamp") == timestamp:
q["cost_usd"] = round(actual_cost, 6)
break
else:
return
data["totals"]["cost_usd"] = round(sum(q["cost_usd"] for q in queries), 6)
self._write_conv(data)
# ── export ────────────────────────────────────────────────────────────
def build_report(self, thread_id: str | None = None) -> dict:
conv = _read_json(self._conv_path(thread_id or self._thread_id))
project = _read_json(self._project_log) if self._project_log else {}
return {
"exported_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
"conversation": conv,
"current_project": project,
}
def _write_conv(self, data: dict):
"""Write conversation file and immediately mirror to project log if active."""
_write_json(self._conv_path(), data)
self._sync_project()
def _sync_project(self):
"""Copy current conversation file into project folder."""
if not self._project_log:
return
conv_data = _read_json(self._conv_path())
_write_json(self._project_log, conv_data)
# ---------------------------------------------------------------------------
# LangChain callback handler
# ---------------------------------------------------------------------------
class UsageTrackerCallback(BaseCallbackHandler):
"""
Attached directly to each ChatOpenAI(callbacks=[...]) so it fires for
every model including subagents, regardless of LangGraph config propagation.
"""
raise_error = False
def __init__(self, metrics, bridge, logger=None):
super().__init__()
self._m = metrics
self._bridge = bridge
self._logger = logger or ConversationLogger()
self._thread_id = ""
self._prompt = ""
self._q_start = {}
self._model_seen = ""
self._run_models: dict[str, str] = {} # run_id → model name
# ── new: per-query accumulators ───────────────────────────────────
self._q_model_breakdown: dict[str, dict] = {}
# Session-cumulative per-model usage. Deliberately independent of the
# per-query records: those live in the conversation FILE and are dropped
# whenever ConversationLogger._thread_id is unset (append_query returns
# early), which is why exported reports can show real `total_tokens`
# beside `"queries": []`. This dict is in-memory and always populated,
# so the breakdown survives that path.
self._session_model_totals: dict[str, dict] = {}
# {"model_name": {"input": int, "output": int, "cost": float}}
self._q_tool_log: list[dict] = []
# [{"tool": str, "status": "ok"|"error"|"soft_error", "detail": str|None, "code_preview": str|None}]
self._user_feedback: str = ""
# ── OpenRouter session-level cost tracking (only when key is set) ──
or_key = os.environ.get("OPEN_ROUTER_API_KEY", "")
self._or_fetcher: _OpenRouterCostFetcher | None = (
_OpenRouterCostFetcher(or_key) if or_key else None
)
# Running OR-confirmed cost for the current conversation (USD).
# Protected by _or_lock; updated once per query after the poll delay.
self._or_conv_cost: float = 0.0
self._or_lock = threading.Lock()
# ── OpenRouter session-level cost tracking (only when key is set) ──
or_key = os.environ.get("OPEN_ROUTER_API_KEY", "")
self._or_fetcher: _OpenRouterCostFetcher | None = (
_OpenRouterCostFetcher(or_key) if or_key else None
)
# Running OR-confirmed cost for the current conversation (USD).
# Protected by _or_lock; updated once per query after the poll delay.
self._or_conv_cost: float = 0.0
self._or_lock = threading.Lock()
self._or_eager_poll_pending: bool = False
def notify_workspace_created(self, output_str: str):
"""Called by the GUI from handle_event when setup_analysis_workspace completes."""
for line in output_str.splitlines():
if line.strip().startswith("Location:"):
root_path = Path(line.split("Location:", 1)[1].strip())
self._logger.set_project_path(root_path, root_path.name)
log.debug(f"Project log path set to: {root_path}")
break
# ── GUI control ───────────────────────────────────────────────────────
def switch_thread(self, thread_id: str):
"""
Called by the GUI on every thread switch (including app startup).
Saves nothing — the last finish_query() already wrote the file.
Resets metrics and pre-loads the new thread's saved totals.
"""
self._thread_id = thread_id
self._logger.set_thread(thread_id)
totals = self._logger.load_totals(thread_id)
self._m.reset()
if totals:
self._m.load_from_totals(totals)
if self._or_fetcher:
# Fresh OR baseline for this conversation so that new queries
# accumulate correctly on top of any already-saved cost.
self._or_fetcher.init_baseline()
with self._or_lock:
self._or_conv_cost = 0.0
self._bridge.updated.emit(self._m.snapshot())
self._user_feedback = ""
def start_query(self, prompt: str, thread_id: str):
self._thread_id = thread_id
self._prompt = prompt
self._q_start = {
"input": self._m.input_tokens,
"output": self._m.output_tokens,
"tools": self._m.tool_calls,
"failed": self._m.failed_tool_calls,
"soft": self._m.soft_error_tool_calls,
"cost": self._m.cost_usd,
}
# reset per-query accumulators
self._q_model_breakdown = {}
self._q_tool_log = []
self._m.start_thinking()
def finish_query(self):
elapsed = self._m.stop_thinking()
snap = self._m.snapshot()
s = self._q_start
timestamp = time.strftime("%Y-%m-%dT%H:%M:%S")
base = dict(
timestamp = timestamp,
thread_id = self._thread_id,
prompt_preview = (self._prompt[:120] + "…")
if len(self._prompt) > 120 else self._prompt,
model = self._model_seen,
thinking_seconds = round(elapsed, 2),
input_tokens = snap["input_tokens"] - s["input"],
output_tokens = snap["output_tokens"] - s["output"],
total_tokens = (snap["input_tokens"] - s["input"])
+ (snap["output_tokens"] - s["output"]),
tool_calls = snap["tool_calls"] - s["tools"],
failed_tool_calls = snap["failed_tool_calls"] - s["failed"],
soft_error_tool_calls = snap["soft_error_tool_calls"] - s["soft"],
model_breakdown = self._q_model_breakdown,
tool_call_log = self._q_tool_log,
)
if not self._or_fetcher:
# Estimated-cost path: write record immediately.
record = QueryRecord(**base, cost_usd=round(snap["cost_usd"] - s["cost"], 6))
self._logger.append_query(record, snap)
return
# OR path: poll with retries until OR's billing counter moves past the
# previous conversation total, then attribute the increment to this query.
fetcher = self._or_fetcher
def _finalize(
initial_delay: float = 2.0, # wait before first poll
poll_interval: float = 3.0, # seconds between polls
idle_timeout: float = 30.0, # stop after this many seconds with no new charge
abs_timeout: float = 120.0, # hard stop regardless
):
time.sleep(initial_delay)
abs_deadline = time.monotonic() + abs_timeout
last_increase_t = time.monotonic()
total_query_cost = 0.0
record_written = False
while True:
now = time.monotonic()
if now >= abs_deadline:
break
# Once we have at least one reading, stop when cost has been
# stable long enough — all delayed charges should have arrived.
if record_written and (now - last_increase_t) >= idle_timeout:
break
session_cost = fetcher.get_session_delta()
if session_cost is not None:
with self._or_lock:
if session_cost > self._or_conv_cost:
increment = session_cost - self._or_conv_cost
self._or_conv_cost = session_cost
else:
increment = 0.0
if increment > 0:
with self._m._lock:
self._m.cost_usd += increment
total_query_cost += increment
last_increase_t = time.monotonic()
if not record_written:
record = QueryRecord(
**base, cost_usd=round(total_query_cost, 6)
)
self._logger.append_query(record, self._m.snapshot())
record_written = True
else:
self._logger.update_query_cost(
timestamp, total_query_cost
)
log.debug(
f"OpenRouter: +${increment:.6f} "
f"query total=${total_query_cost:.6f} "
f"session=${session_cost:.6f}"
)
self._emit()
time.sleep(poll_interval)
if not record_written:
log.warning("OpenRouter: no cost registered within "
f"{abs_timeout:.0f}s — query cost not recorded")
threading.Thread(target=_finalize, daemon=True).start()
def _schedule_eager_or_poll(self, delay: float = 1.5) -> None:
"""One-shot cost poll triggered by on_llm_end for mid-query UI updates."""
with self._or_lock:
if self._or_eager_poll_pending:
return
self._or_eager_poll_pending = True
fetcher = self._or_fetcher
def _poll():
time.sleep(delay)
with self._or_lock:
self._or_eager_poll_pending = False
session_cost = fetcher.get_session_delta()
if session_cost is None:
return
with self._or_lock:
if session_cost > self._or_conv_cost:
increment = session_cost - self._or_conv_cost
self._or_conv_cost = session_cost
else:
increment = 0.0
if increment > 0:
with self._m._lock:
self._m.cost_usd += increment
self._emit()
threading.Thread(target=_poll, daemon=True).start()
def session_totals(self) -> dict:
"""Session-wide usage, broken down per model and per configured role.
Answers the benchmark team's §4.1 request: input / output / cached per
model role, without per-query granularity. Built from the in-memory
cumulative store rather than the conversation file, so it is populated
even when per-query records were dropped (see _session_model_totals).
`by_role` maps each configured role to the model serving it, so several
roles sharing one model id (worker and analyst both on gpt-5.3-codex,
say) stay distinguishable instead of being silently merged. Where roles
share a model the SAME per-model figures appear under each: the tracker
observes model ids on the wire, not which role issued the call, so the
split between them is not measurable here and is not guessed at.
"""
with self._m._lock:
by_model = {m: dict(v) for m, v in self._session_model_totals.items()}
totals = {
"input_tokens": sum(v["input_tokens"] for v in by_model.values()),
"output_tokens": sum(v["output_tokens"] for v in by_model.values()),
"cached_input_tokens": sum(v["cached_input_tokens"] for v in by_model.values()),
}
totals["total_tokens"] = totals["input_tokens"] + totals["output_tokens"]
by_role: dict[str, dict] = {}
try:
from . import config as _config
for role in ("supervisor", "worker", "analyst", "nano", "curator", "vlm"):
model_id = _config.model_for(role, "")
if not model_id:
continue
short = model_id.split("/")[-1]
stats = by_model.get(model_id) or by_model.get(short)
by_role[role] = {
"model": model_id,
**(dict(stats) if stats else {
"input_tokens": 0, "output_tokens": 0,
"cached_input_tokens": 0, "cost_usd": 0.0}),
"shares_model_with": [],
}
for role, info in by_role.items():
info["shares_model_with"] = sorted(
r for r, o in by_role.items()
if r != role and o["model"] == info["model"]
)
except Exception:
pass
return {
"totals": totals,
"by_model": by_model,
"by_role": by_role,
"cost_source": "openrouter_session" if self._or_fetcher else "estimated_per_model",
}
def get_report(self) -> dict:
report = self._logger.build_report()
# Always attach the live session totals. build_report() reads the
# conversation FILE, which is empty whenever per-query records were
# dropped; this key is derived from memory and is therefore never empty
# for a run that actually called a model.
report["session_totals"] = self.session_totals()
return report
def set_user_feedback(self, text: str):
"""Store user-provided feedback text for inclusion in error reports."""
self._user_feedback = text.strip()
def get_error_report(self, include_usage_stats: bool = True) -> dict:
"""Build a structured error/feedback report for export to the dev team."""
import platform, sys as _sys
base_report = self._logger.build_report()
queries = base_report.get("conversation", {}).get("queries", [])
error_events: list[dict] = []
for q in queries:
for entry in q.get("tool_call_log", []):
if entry.get("status") in ("soft_error", "error"):
error_events.append({
"query_timestamp": q.get("timestamp"),
"prompt_preview": q.get("prompt_preview"),
"tool": entry.get("tool"),
"status": entry.get("status"),
"detail": entry.get("detail"),
"code_preview": entry.get("code_preview"),
})
report: dict = {
"report_type": "error_feedback",
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
"thread_id": self._thread_id,
"user_feedback": self._user_feedback,
"error_summary": {
"total_errors": sum(1 for e in error_events if e["status"] == "error"),
"total_soft_errors": sum(1 for e in error_events if e["status"] == "soft_error"),
"affected_queries": len({e["query_timestamp"] for e in error_events}),
},
"error_events": error_events,
"system_info": {
"platform": platform.platform(),
"python_version": _sys.version,
"os": platform.system(),
"os_version": platform.version(),
"machine": platform.machine(),
},
}
if include_usage_stats:
report["usage_stats"] = base_report
return report
def get_error_report_for_thread(
self, thread_id: str, include_usage_stats: bool = True
) -> dict:
"""Same as get_error_report() but for any stored thread, not just the active one."""
import platform, sys as _sys
base_report = self._logger.build_report(thread_id)
queries = base_report.get("conversation", {}).get("queries", [])
error_events: list[dict] = []
for q in queries:
for entry in q.get("tool_call_log", []):
if entry.get("status") in ("soft_error", "error"):
error_events.append({
"query_timestamp": q.get("timestamp"),
"prompt_preview": q.get("prompt_preview"),
"tool": entry.get("tool"),
"status": entry.get("status"),
"detail": entry.get("detail"),
"code_preview": entry.get("code_preview"),
})
report: dict = {
"report_type": "error_feedback",
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
"thread_id": thread_id,
"user_feedback": self._user_feedback if thread_id == self._thread_id else "",
"error_summary": {
"total_errors": sum(1 for e in error_events if e["status"] == "error"),
"total_soft_errors": sum(1 for e in error_events if e["status"] == "soft_error"),
"affected_queries": len({e["query_timestamp"] for e in error_events}),
},
"error_events": error_events,
"system_info": {
"platform": platform.platform(),
"python_version": _sys.version,
"os": platform.system(),
"os_version": platform.version(),
"machine": platform.machine(),
},
}
if include_usage_stats:
report["usage_stats"] = base_report
return report
# ── LLM callbacks ─────────────────────────────────────────────────────
def on_llm_start(self, serialized: dict, prompts: list, **kwargs):
run_id = str(kwargs.get("run_id", ""))
kw = serialized.get("kwargs") or {}
model = (kw.get("model_name") or kw.get("model") or
serialized.get("name") or "")
if model:
self._model_seen = model
if run_id:
self._run_models[run_id] = model
def on_llm_end(self, response: LLMResult, **kwargs):
run_id = str(kwargs.get("run_id", ""))
model = self._run_models.pop(run_id, self._model_seen)
added_in = added_out = 0
usage = (response.llm_output or {}).get("token_usage") or \
(response.llm_output or {}).get("usage")
if isinstance(usage, dict):
added_in = usage.get("prompt_tokens", 0)
added_out = usage.get("completion_tokens", 0)
if not (added_in or added_out):
for gen_list in response.generations:
for gen in gen_list:
meta = getattr(getattr(gen, "message", None), "usage_metadata", None)
if meta:
added_in += meta.get("input_tokens", 0)
added_out += meta.get("output_tokens", 0)
if not (added_in or added_out):
for gen_list in response.generations:
for gen in gen_list:
meta = getattr(getattr(gen, "message", None), "response_metadata", {}) or {}
tok = meta.get("token_usage") or meta.get("usage") or {}
added_in += tok.get("prompt_tokens", tok.get("input_tokens", 0))
added_out += tok.get("completion_tokens", tok.get("output_tokens", 0))
# Extract cached input tokens for prompt-cache discount (OpenAI direct only)
cached_in = 0
if isinstance(usage, dict):
cached_in = (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)
if not cached_in:
# Streaming responses often carry no llm_output["token_usage"] at all —
# the counts only arrive on the message's normalized usage_metadata,
# where the cached figure is input_token_details["cache_read"]. Without
# this the discount silently never applied on the streaming path, even
# though real cache hit rates run ~70%.
for gen_list in response.generations:
for gen in gen_list:
meta = getattr(getattr(gen, "message", None), "usage_metadata", None)
if meta:
details = meta.get("input_token_details") or {}
cached_in = max(cached_in, details.get("cache_read", 0))
if not cached_in:
for gen_list in response.generations:
for gen in gen_list:
meta = getattr(getattr(gen, "message", None), "response_metadata", {}) or {}
tok = meta.get("token_usage") or meta.get("usage") or {}
cached_in = max(cached_in, (tok.get("prompt_tokens_details") or {}).get("cached_tokens", 0))
if added_in or added_out:
with self._m._lock:
self._m.input_tokens += added_in
self._m.output_tokens += added_out
if not self._or_fetcher:
# Estimated cost — only applied when OR key is not set
p_in, p_out, cache_factor = _price_for_model(model)
non_cached = added_in - cached_in
if cache_factor is not None and cached_in:
cost = (non_cached * p_in + cached_in * p_in * cache_factor + added_out * p_out) / 1_000_000
else:
cost = (added_in * p_in + added_out * p_out) / 1_000_000
self._m.cost_usd += cost
# ── per-query model breakdown (tokens always; cost only estimated path)
entry = self._q_model_breakdown.setdefault(
model, {"input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0}
)
entry["input_tokens"] += added_in
entry["output_tokens"] += added_out
cume = self._session_model_totals.setdefault(
model,
{"input_tokens": 0, "output_tokens": 0,
"cached_input_tokens": 0, "cost_usd": 0.0},
)
cume["input_tokens"] += added_in
cume["output_tokens"] += added_out
cume["cached_input_tokens"] += cached_in
if not self._or_fetcher:
entry["cost_usd"] = round(entry["cost_usd"] + cost, 6)
cume["cost_usd"] = round(cume["cost_usd"] + cost, 6)
# On the OpenRouter path per-model cost stays 0.0: OR bills per
# SESSION, so there is no per-model figure to attribute and inventing
# one by summing local estimates would disagree with the invoice.
# `cost_source` says which regime produced these numbers, so a
# consumer never has to guess why the per-model costs sum to zero.
self._emit()
if self._or_fetcher:
self._schedule_eager_or_poll()
# ── Tool callbacks ─────────────────────────────────────────────────────
def on_tool_start(self, serialized: dict, input_str: str, **kwargs):
tool_name = (serialized or {}).get("name", "unknown")
with self._m._lock:
self._m.tool_calls += 1
# For execution tools, extract the full script code so it appears in error reports
code_preview = None
if tool_name in _EXECUTION_TOOLS:
try:
# LangChain may pass input_str as valid JSON or as Python dict repr
# (single-quoted keys). Try JSON first, then ast.literal_eval as fallback.
if isinstance(input_str, dict):
args = input_str
elif isinstance(input_str, str):
try:
args = json.loads(input_str)
except (json.JSONDecodeError, ValueError):
import ast as _ast
parsed = _ast.literal_eval(input_str)
args = parsed if isinstance(parsed, dict) else {}
else:
args = {}
if "code" in args:
# run_script_safe / run_python_code — code is inline
code_preview = args["code"]
elif "directory" in args and "filename" in args:
# execute_script — code is on disk