Repository navigation
Expand file tree
/
Copy path_session_stats.py
More file actions
1574 lines (1342 loc) · 60.8 KB
/
Copy path_session_stats.py
File metadata and controls
1574 lines (1342 loc) · 60.8 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
"""Lightweight session statistics, token formatting, and usage-table rendering.
Holds `SessionStats`/`ModelStats`, the `format_token_count` formatter,
`print_usage_table` (which imports `rich.table` lazily), and
`usage_table_enabled`, which decides whether that table is rendered at all.
The module is intentionally kept free of heavy top-level dependencies (no
pydantic, no config, no widget imports) so that `app.py` can import
`SessionStats` and `format_token_count` at module level without pulling in the
full `textual_adapter` dependency tree — hence the deferred `config_manifest`
import inside `usage_table_enabled` rather than at the top.
"""
from __future__ import annotations
import logging
import math
import re
import sys
from collections.abc import Hashable, Mapping
from dataclasses import dataclass, field, replace
from decimal import ROUND_CEILING, Decimal
from typing import TYPE_CHECKING, Any, Literal, cast
from deepagents_code.formatting import format_duration
if TYPE_CHECKING:
from rich.console import Console
logger = logging.getLogger(__name__)
_warned_usage_stats_rejections: set[str] = set()
"""Rejection reasons already reported by `_warn_rejected_usage_stats_value`."""
SpinnerStatus = str | None
"""Spinner display text, or `None` to hide.
Deliberately unconstrained rather than the closed `Literal` set it replaced:
retry status text is generated per attempt by `model_retry.format_retry_status`.
Narrowing this back to a `Literal` union would break the retry spinner.
"""
UsageKind = Literal["assistant", "subagent", "offload", "auto"]
"""Billing/display class for a model request."""
USAGE_KIND_ORDER: tuple[UsageKind, ...] = (
"assistant",
"subagent",
"offload",
"auto",
)
"""Stable display order for per-type cost breakdowns."""
USAGE_KIND_LABELS: dict[UsageKind, str] = {
"assistant": "Assistant",
"subagent": "Subagents",
"offload": "Offload",
"auto": "Auto mode",
}
"""User-facing labels for `UsageKind` values."""
def classify_usage_kind(
*,
is_main_agent: bool,
metadata: Mapping[str, Any] | None = None,
) -> UsageKind:
"""Classify a streamed model request for cost and usage breakdowns.
Args:
is_main_agent: Whether the stream namespace is the top-level agent.
metadata: LangChain callback/stream metadata for the chunk.
Returns:
The usage kind used in `/cost` and session stats.
"""
if not is_main_agent:
return "subagent"
source = metadata.get("lc_source") if metadata is not None else None
if source == "summarization":
return "offload"
if source == "auto_mode_classifier":
return "auto"
return "assistant"
@dataclass
class ModelStats:
"""Token stats for a single model within a session."""
request_count: int = 0
"""Number of LLM API requests made to this model."""
invocation_count: int = 0
"""Human-submitted turns started with this model."""
input_tokens: int = 0
"""Cumulative input tokens sent to this model."""
output_tokens: int = 0
"""Cumulative output tokens received from this model."""
cost_usd: float = 0.0
"""Cumulative estimated USD cost for priceable requests to this model."""
priced_request_count: int = 0
"""Requests with a cost estimate, including estimates of literal zero."""
provider: str = ""
"""Provider that served this model (e.g. `openai`), or `""` when unknown."""
model_name: str = ""
"""Model name displayed in usage output."""
@dataclass
class KindStats:
"""Token and cost stats for one `UsageKind` bucket."""
request_count: int = 0
"""Number of LLM API requests in this bucket."""
input_tokens: int = 0
"""Cumulative input tokens in this bucket."""
output_tokens: int = 0
"""Cumulative output tokens in this bucket."""
cost_usd: float = 0.0
"""Cumulative estimated USD cost for priceable requests in this bucket."""
priced_request_count: int = 0
"""Requests with a cost estimate, including estimates of literal zero."""
@dataclass(frozen=True, slots=True)
class RecordedUsage:
"""Usage returned after recording one streamed model message."""
input_tokens: int
"""Input-token delta contributed by this message."""
output_tokens: int
"""Output-token delta contributed by this message."""
cost_usd: float | None
"""Cost contributed by this message, or `None` when pricing was unavailable.
Negative when the message re-prices its request downward -- a corrected
prompt count, or a model that turned out to cost less than the fallback the
earlier chunks were priced against.
"""
request_tokens: int
"""Running token total for the request after applying this message."""
request_id: str | None = None
"""Opaque key naming the request this delta belongs to, when known.
Keys each correction to the request it applies to. A late revision then
cannot subtract spend that belongs to other requests. `None` when the
message carried no usable ID, which is also when the ledger refuses to key
the request at all.
Built by `_provisional_bucket_key`, so it separates retry attempts exactly
as the ledger does. Treat it as a bucket key, not as a provider message ID.
"""
is_correction: bool = False
"""Whether this delta only revises spend already reported for the request.
A correction re-states what an earlier delta already contributed: a
completion replacing its chunks, or a request re-priced under the model it
finally named. New spend is not a correction, even when it arrives on a
request that already has a record, because the tokens themselves are new.
Lets the consumer drop a correction whose subject is gone -- a backend
total has already absorbed that request -- whatever the correction's sign.
A stale *positive* correction would otherwise re-inflate a display the
total had just settled.
"""
@dataclass(frozen=True, slots=True)
class ModelInvocationKey:
"""Stable identity of one model invocation in the usage ledger."""
invocation_id: str
@dataclass(frozen=True, slots=True)
class MessageUsageKey:
"""Message identity, optionally scoped to one model attempt."""
message_id: str
attempt_scope: Hashable | None = None
UsageLedgerKey = ModelInvocationKey | MessageUsageKey
"""Model run identities and message aliases for recorded requests."""
ModelStatsKey = tuple[str, str]
"""Per-model dict key: the `(provider, model_name)` pair.
Pairing the provider with the model name keeps the same model served by
different providers (e.g. `gpt-5.5` via `openai` vs `azure`) in separate rows
instead of collapsing them. The key is always built from the same values stored
on the corresponding `ModelStats`, so key and fields never diverge.
"""
@dataclass
class SessionStats:
"""Stats accumulated over a single agent turn (or full session)."""
request_count: int = 0
"""Total LLM API requests made.
One completed API request counts once, however many stream chunks carried
its usage: `record_message_usage` revises a request in place rather than
recording each chunk separately.
"""
invocation_count: int = 0
"""Human-submitted agent turns, attributed to their starting model."""
input_tokens: int = 0
"""Cumulative input tokens across all LLM requests."""
output_tokens: int = 0
"""Cumulative output tokens across all LLM requests."""
cache_read_tokens: int = 0
"""Cumulative prompt tokens served from provider caches."""
cache_write_tokens: int = 0
"""Cumulative prompt tokens written to provider caches."""
total_cost_usd: float = 0.0
"""Cumulative estimated USD cost across priceable LLM requests."""
priced_request_count: int = 0
"""Requests with a cost estimate, including estimates of literal zero."""
wall_time_seconds: float = 0.0
"""Wall-clock duration from stream start to end."""
per_model: dict[ModelStatsKey, ModelStats] = field(default_factory=dict)
"""Per-model breakdown keyed by `(provider, model_name)`.
Populated only when `record_request` receives a non-empty `model_name`. Empty
dict means no named-model requests were recorded; `print_usage_table` omits
the model table in that case and shows only the wall-time line (if applicable).
"""
per_kind: dict[UsageKind, KindStats] = field(default_factory=dict)
"""Per-type breakdown for assistant, nested, and hidden model spend."""
def record_invocation(self, model_name: str, provider: str = "") -> None:
"""Count one human turn against its configured starting model."""
self.invocation_count += 1
model_name = model_name or "Unknown"
entry = self.per_model.setdefault(
(provider, model_name),
ModelStats(provider=provider, model_name=model_name),
)
entry.invocation_count += 1
def record_request(
self,
model_name: str,
input_toks: int,
output_toks: int,
provider: str = "",
*,
cost_usd: float | None = None,
kind: UsageKind = "assistant",
cache_read_tokens: int = 0,
cache_write_tokens: int = 0,
) -> None:
"""Accumulate usage for one completed LLM request.
Updates session totals plus the per-model and per-type breakdowns.
Args:
model_name: The model that served this request.
Combined with `provider` to form the per-model key. Pass
an empty string to skip the per-model breakdown for this request.
input_toks: Input tokens for this request.
output_toks: Output tokens for this request.
provider: Provider that served the model (e.g. `openai`).
Combined with `model_name` to form the per-model key, so
the same model served by different providers is
tracked separately.
cost_usd: Estimated request cost, or `None` when no estimate exists.
Missing estimates leave monetary totals unchanged.
kind: Request class used for `/cost` type breakdowns.
cache_read_tokens: Input tokens served from provider caches.
cache_write_tokens: Input tokens written to provider caches.
"""
self.request_count += 1
self.input_tokens += input_toks
self.output_tokens += output_toks
self.cache_read_tokens += cache_read_tokens
self.cache_write_tokens += cache_write_tokens
if cost_usd is not None:
self.total_cost_usd += cost_usd
self.priced_request_count += 1
kind_entry = self.per_kind.setdefault(kind, KindStats())
kind_entry.request_count += 1
kind_entry.input_tokens += input_toks
kind_entry.output_tokens += output_toks
if cost_usd is not None:
kind_entry.cost_usd += cost_usd
kind_entry.priced_request_count += 1
if model_name:
key = (provider, model_name)
entry = self.per_model.setdefault(
key,
ModelStats(provider=provider, model_name=model_name),
)
entry.request_count += 1
entry.input_tokens += input_toks
entry.output_tokens += output_toks
if cost_usd is not None:
entry.cost_usd += cost_usd
entry.priced_request_count += 1
def retract_request(self, recorded: RecordedRequest) -> None:
"""Reverse the `record_request` call that produced *recorded*.
A request whose usage arrives across several stream chunks is recorded
as soon as the first chunk lands, so the display can react, and then
re-recorded with its running totals as later chunks arrive. Retracting
the previous version first keeps that one API call counted once, with
one per-model row, instead of once per chunk.
Takes the ledger entry rather than loose values so the retraction cannot
drift from what was recorded: a mismatch would desync the session totals
from the per-kind and per-model breakdowns silently.
Args:
recorded: Ledger entry describing the contribution to reverse.
"""
model_name = recorded.model_name
provider = recorded.provider
input_toks = recorded.input_tokens
output_toks = recorded.output_tokens
cost_usd = recorded.cost_usd
kind = recorded.kind
self.request_count -= 1
self.input_tokens -= input_toks
self.output_tokens -= output_toks
self.cache_read_tokens -= recorded.cache_read_tokens
self.cache_write_tokens -= recorded.cache_write_tokens
if cost_usd is not None:
self.total_cost_usd -= cost_usd
self.priced_request_count -= 1
kind_entry = self.per_kind.get(kind)
if kind_entry is not None:
kind_entry.request_count -= 1
kind_entry.input_tokens -= input_toks
kind_entry.output_tokens -= output_toks
if cost_usd is not None:
kind_entry.cost_usd -= cost_usd
kind_entry.priced_request_count -= 1
if kind_entry.request_count <= 0:
# Mirrors the per-model eviction below: a kind whose only
# request moved elsewhere would otherwise leave an all-zero row
# in the `/cost` type breakdown.
del self.per_kind[kind]
if model_name:
entry = self.per_model.get((provider, model_name))
if entry is not None:
entry.request_count -= 1
entry.input_tokens -= input_toks
entry.output_tokens -= output_toks
if cost_usd is not None:
entry.cost_usd -= cost_usd
entry.priced_request_count -= 1
if entry.request_count <= 0 and entry.invocation_count == 0:
# The chunk-revision path can move a request to a different
# model once the final chunk names one; drop the row it
# vacated so the breakdown does not show an empty entry.
del self.per_model[provider, model_name]
def merge(self, other: SessionStats) -> None:
"""Merge another `SessionStats` into this one (mutates *self*).
Used to accumulate per-turn stats into a session-level total.
Args:
other: The stats to fold in.
"""
self.request_count += other.request_count
self.invocation_count += other.invocation_count
self.input_tokens += other.input_tokens
self.output_tokens += other.output_tokens
self.cache_read_tokens += other.cache_read_tokens
self.cache_write_tokens += other.cache_write_tokens
self.total_cost_usd += other.total_cost_usd
self.priced_request_count += other.priced_request_count
self.wall_time_seconds += other.wall_time_seconds
for key, ms in other.per_model.items():
entry = self.per_model.setdefault(
key,
ModelStats(provider=ms.provider, model_name=ms.model_name),
)
entry.request_count += ms.request_count
entry.invocation_count += ms.invocation_count
entry.input_tokens += ms.input_tokens
entry.output_tokens += ms.output_tokens
entry.cost_usd += ms.cost_usd
entry.priced_request_count += ms.priced_request_count
for kind, kind_stats in other.per_kind.items():
entry = self.per_kind.setdefault(kind, KindStats())
entry.request_count += kind_stats.request_count
entry.input_tokens += kind_stats.input_tokens
entry.output_tokens += kind_stats.output_tokens
entry.cost_usd += kind_stats.cost_usd
entry.priced_request_count += kind_stats.priced_request_count
@dataclass(frozen=True, slots=True)
class RecordedRequest:
"""What a stream consumer last recorded for one request.
Held so a later chunk of the same request can retract that exact
contribution and re-record the running totals, keeping one API call to one
request and one per-model row.
"""
model_name: str
"""Model the contribution was recorded under."""
provider: str
"""Provider the contribution was recorded under."""
kind: UsageKind
"""Type bucket the contribution was recorded under."""
input_tokens: int
"""Running input tokens recorded so far for the request."""
output_tokens: int
"""Running output tokens recorded so far for the request."""
cache_read_tokens: int
"""Running cache-read tokens recorded so far for the request."""
cache_write_tokens: int
"""Running cache-write tokens recorded so far for the request."""
cost_usd: float | None
"""Estimate for the whole request so far, or `None` when unpriceable."""
usage_metadata: Mapping[str, Any]
"""Merged usage for the request so far.
Kept so the request can be re-priced as a whole once a later chunk reveals
the model. Summing per-chunk estimates would freeze the rates that applied
when the model was still unknown.
"""
finalized: bool
"""Whether the request's usage is complete and can no longer be added to.
Set either by a completed (non-chunk) message, which carries the request's
whole usage, or by `finalize_recorded_requests` at the end of a stream
round. A later chunk for a finalized request is a replay, not a revision.
"""
message_ids: frozenset[str] = frozenset()
"""Provider and framework message IDs observed for this invocation."""
ledger_key: UsageLedgerKey | None = None
"""Canonical ledger entry, promoted when a model run identity is learned."""
request_bucket: str | None = None
"""Stable provisional bucket even when a legacy record gains a run identity."""
invocation_id: str | None = None
"""Strong run identity, when supplied by either delivery path."""
aliases: frozenset[UsageLedgerKey] = frozenset()
"""Scoped identities pointing to this canonical record."""
def finalize_recorded_requests(
recorded_requests: dict[UsageLedgerKey, RecordedRequest],
) -> None:
"""Finalize canonical records and expose message aliases for unscoped replay."""
for request_id, recorded in list(recorded_requests.items()):
if request_id != recorded.ledger_key:
continue
closed = replace(recorded, finalized=True)
for alias in closed.aliases:
if recorded_requests.get(alias) is recorded:
recorded_requests[alias] = closed
for message_id in closed.message_ids:
recorded_requests[MessageUsageKey(message_id)] = closed
def _provisional_bucket_key(request_id: UsageLedgerKey | None) -> str | None:
"""Return the initial provisional bucket, retained when run identity improves."""
if request_id is None:
return None
if isinstance(request_id, ModelInvocationKey):
return repr(request_id.invocation_id)
if request_id.attempt_scope is not None:
return repr((request_id.attempt_scope, request_id.message_id))
return request_id.message_id
def _usage_ledger_key(
recorded_requests: dict[UsageLedgerKey, RecordedRequest],
message_id: str | None,
attempt_scope: Hashable | None,
invocation_id: str | None,
) -> tuple[UsageLedgerKey | None, frozenset[UsageLedgerKey]]:
"""Return a canonical key and compatible scoped aliases, never across runs."""
message_key = MessageUsageKey(message_id, attempt_scope) if message_id else None
run_key = ModelInvocationKey(invocation_id) if invocation_id else None
aliases = frozenset(key for key in (run_key, message_key) if key is not None)
for key in (run_key, message_key):
previous = recorded_requests.get(key) if key is not None else None
if previous is not None and (
not invocation_id
or not previous.invocation_id
or previous.invocation_id == invocation_id
):
return previous.ledger_key, aliases
return run_key or message_key, aliases
def _names_a_model(message: object) -> bool:
"""Report whether a message's own metadata names the model that served it.
Google attaches `model_name` only to the chunk carrying `finish_reason`, so
a chunk that does not name one must keep the model already recorded rather
than reverting the request to the caller's fallback.
Args:
message: Streamed model message or chunk.
Returns:
`True` when response metadata names a model.
"""
metadata = getattr(message, "response_metadata", None)
if not isinstance(metadata, Mapping):
return False
return bool(metadata.get("model_name") or metadata.get("model"))
def _positive_int(value: object) -> int:
"""Return a token count as a non-negative int, or `0` when unusable."""
return (
value
if isinstance(value, int) and not isinstance(value, bool) and value > 0
else 0
)
def _carries_token_counts(usage: Mapping[str, Any]) -> bool:
"""Report whether usage states any token count, including a negative one.
Google's final chunk can report a *negative* `input_tokens` to correct an
over-counted prompt, which normalizes to zero but is still a real revision
of the request.
Args:
usage: A message's `usage_metadata`.
Returns:
`True` when any top-level token field holds a non-zero integer.
"""
return any(
isinstance(value, int) and not isinstance(value, bool) and value != 0
for value in (
usage.get("input_tokens"),
usage.get("output_tokens"),
usage.get("total_tokens"),
)
)
def _display_token_counts(usage: Mapping[str, Any]) -> tuple[int, int]:
"""Return the `(input, output)` token counts to display for some usage.
Args:
usage: A message's `usage_metadata`, or a request's merged usage.
Returns:
Non-negative input and output counts. When neither is reported but a
total is, the total is attributed to input so the request is not
shown as having used nothing.
"""
input_count = _positive_int(usage.get("input_tokens"))
output_count = _positive_int(usage.get("output_tokens"))
if not input_count and not output_count:
return _positive_int(usage.get("total_tokens")), 0
return input_count, output_count
def _merge_usage(
left: Mapping[str, Any],
right: Mapping[str, Any],
) -> Mapping[str, Any]:
"""Combine two usage metadata mappings for the same request.
Uses LangChain's own recursive adder so nested token details (cache reads,
cache writes, reasoning tokens) are summed rather than dropped -- those
buckets carry their own rates, so losing them would misprice the request.
Summing assumes each chunk reports an *incremental* usage delta. That is
LangChain's contract, not just ours: `AIMessageChunk.__add__` adds the usage
of chunks sharing an ID, so a provider that repeated cumulative totals per
chunk would already double-count in the framework's own aggregation.
Args:
left: Usage accumulated for the request so far.
right: Usage reported by the message being folded in.
Returns:
The combined usage, or `left` unchanged if the two cannot be added.
"""
try:
# Imported inside the guard: a langchain-core release that renames or
# moves `add_usage` would otherwise raise straight into the stream loop,
# which does not wrap this call.
from langchain_core.messages.ai import add_usage
return dict(add_usage(cast("Any", dict(left)), cast("Any", dict(right))))
except Exception:
# Malformed provider usage must not break accounting for the request.
# `left` is returned unchanged, so this chunk's usage is dropped rather
# than mis-merged -- log it, because the resulting total is short.
logger.warning(
"Could not merge streamed usage metadata; this chunk's tokens and "
"cost are missing from the request.",
exc_info=True,
)
return left
def _cost_delta(
previous_cost_usd: float | None,
cost_usd: float | None,
*,
model_name: str,
previous_model_name: str,
) -> float | None:
"""Return the provisional-display delta between two estimates of a request.
Re-pricing can move a request from priceable to unpriceable, when the model
it finally names has no published rates but the caller's fallback did. The
accumulator drops the old estimate, so reporting `None` would leave the
caller's provisional display holding a cost nothing backs any more. Report
the retraction as a negative delta instead.
Args:
previous_cost_usd: Estimate last recorded for the request.
cost_usd: Estimate now recorded for it.
model_name: Model the request is now priced under, for the log.
previous_model_name: Model it was priced under before, for the log.
Returns:
The signed change to apply, or `None` when the request has never had a
priceable estimate and so contributes nothing to the display.
"""
if cost_usd is None:
if previous_cost_usd is None:
return None
logger.warning(
"Re-filing a request under the model it named made it unpriceable; "
"dropping %.6f USD from the session total. from=%r to=%r",
previous_cost_usd,
previous_model_name,
model_name,
)
return -previous_cost_usd
return cost_usd - (previous_cost_usd or 0.0)
def _resolve_usage_model(
message: object,
*,
fallback_model: str,
fallback_provider: str,
request_metadata: Mapping[str, Any] | None,
kind: UsageKind,
) -> tuple[str, str]:
"""Resolve the `(model, provider)` a streamed message should be priced as.
Args:
message: Streamed model message or chunk.
fallback_model: Model to use when response metadata does not name one.
fallback_provider: Provider to use when response metadata omits it.
request_metadata: Stream metadata for this specific request, if any.
kind: Request class used by the type breakdown.
Returns:
The `(model_name, provider)` pair to record and price under.
"""
from deepagents_code.cost_tracking import (
_CONFIGURED_MODEL_METADATA_KEY,
_CONFIGURED_PROVIDER_METADATA_KEY,
resolve_message_model,
)
request_metadata = request_metadata or {}
configured_provider = request_metadata.get(_CONFIGURED_PROVIDER_METADATA_KEY)
has_request_provider = isinstance(configured_provider, str) and bool(
configured_provider
)
configured_model = request_metadata.get(_CONFIGURED_MODEL_METADATA_KEY)
has_request_model = isinstance(configured_model, str) and bool(configured_model)
return resolve_message_model(
message,
# The request's own configured model describes this very call, so unlike
# the caller's fallback it is valid for nested calls too; it only
# replaces the parent-fallback step, ahead of the existing chain.
fallback_model=configured_model if has_request_model else fallback_model,
fallback_provider=(
configured_provider if has_request_provider else fallback_provider
),
# Request-specific metadata safely corrects generic provider responses.
# Without it, only the main request may use the parent fallback; hidden
# calls can be cross-provider and must keep their explicit response value.
prefer_fallback_provider=has_request_provider or kind == "assistant",
)
def _move_request_to_named_model(
stats: SessionStats,
message: object,
previous: RecordedRequest,
*,
recorded_requests: dict[UsageLedgerKey, RecordedRequest],
request_id: UsageLedgerKey,
fallback_model: str,
fallback_provider: str,
request_metadata: Mapping[str, Any] | None,
kind: UsageKind,
) -> float | None:
"""Re-file an already-recorded request under the model it finally named.
Called for a message that names a model but carries no usable tokens of its
own, which is how Google can close a stream. Token totals are unchanged, but
the request is re-priced under the newly named model: the estimate it
carried was computed against the caller's fallback model.
Args:
stats: Accumulator holding the request.
message: The model-naming message.
previous: What was last recorded for this request.
recorded_requests: Ledger to update in place.
request_id: Message ID keying the ledger entry.
fallback_model: Model to use when response metadata does not name one.
fallback_provider: Provider to use when response metadata omits it.
request_metadata: Stream metadata for this specific request, if any.
kind: Request class used by the type breakdown.
Returns:
The signed cost change the re-pricing applied, for the caller's
provisional display, or `None` when it did not change.
"""
model_name, provider = _resolve_usage_model(
message,
fallback_model=fallback_model,
fallback_provider=fallback_provider,
request_metadata=request_metadata,
kind=kind,
)
if (model_name, provider) == (previous.model_name, previous.provider):
return None
from deepagents_code.cost_tracking import estimate_cost
cost_usd = estimate_cost(previous.usage_metadata, model_name, provider)
stats.retract_request(previous)
stats.record_request(
model_name,
previous.input_tokens,
previous.output_tokens,
provider,
cost_usd=cost_usd,
kind=previous.kind,
cache_read_tokens=previous.cache_read_tokens,
cache_write_tokens=previous.cache_write_tokens,
)
recorded_requests[request_id] = RecordedRequest(
model_name=model_name,
provider=provider,
kind=previous.kind,
input_tokens=previous.input_tokens,
output_tokens=previous.output_tokens,
cache_read_tokens=previous.cache_read_tokens,
cache_write_tokens=previous.cache_write_tokens,
cost_usd=cost_usd,
usage_metadata=previous.usage_metadata,
finalized=previous.finalized,
message_ids=previous.message_ids,
)
return _cost_delta(
previous.cost_usd,
cost_usd,
model_name=model_name,
previous_model_name=previous.model_name,
)
def _finalize_from_completed(
stats: SessionStats,
message: object,
previous: RecordedRequest,
*,
usage: Mapping[str, Any],
recorded_requests: dict[UsageLedgerKey, RecordedRequest],
request_id: UsageLedgerKey,
fallback_model: str,
fallback_provider: str,
request_metadata: Mapping[str, Any] | None,
kind: UsageKind,
) -> RecordedUsage | None:
"""Replace a chunk-built request record with a completed message's usage.
Chunks report incremental deltas, so a request recorded mid-stream holds
partial tokens priced under whatever model was known then. The completed
message carries the whole usage; it must replace the partial record rather
than join it, or corrected token counts, cache details, and model
attribution never reach the stats.
Args:
stats: Accumulator holding the partial request.
message: The completed message with the request's whole usage.
previous: The partial ledger entry to supersede.
usage: The completed message's whole usage metadata.
recorded_requests: Ledger to update in place.
request_id: Message ID keying the ledger entry.
fallback_model: Model to use when response metadata does not name one.
fallback_provider: Provider to use when response metadata omits it.
request_metadata: Stream metadata for this specific request, if any.
kind: Request class used by the type breakdown.
Returns:
The signed cost change the replacement applied, for the caller's
provisional display, or `None` when nothing changed.
"""
from deepagents_code.cost_tracking import cache_token_counts, estimate_cost
model_name, provider = _resolve_usage_model(
message,
fallback_model=fallback_model,
fallback_provider=fallback_provider,
request_metadata=request_metadata,
kind=kind,
)
if not _names_a_model(message):
# An earlier chunk may already have upgraded the record off the
# caller's fallback. A completion that names no model of its own must
# not undo that, or the request goes back to the parent's pricing --
# the very mis-attribution the chunk path guards against.
model_name, provider = previous.model_name, previous.provider
input_count, output_count = _display_token_counts(usage)
cost_usd = estimate_cost(usage, model_name, provider)
cache_reads, cache_writes = cache_token_counts(usage)
if (
not input_count
and not output_count
and _carries_token_counts(previous.usage_metadata)
):
# A completion that corrects its chunks downward is ordinary -- the
# provider revises an over-counted prompt. Reporting *no* token field
# at all is not: it normalizes to zero and wipes a request the chunks
# had counted. Replace the record regardless, since the completion is
# authoritative, but say so rather than losing the tokens quietly.
logger.warning(
"A completed message states no token counts, so it replaces its "
"chunks with zero. request_id=%r dropped=%d/%d",
request_id,
previous.input_tokens,
previous.output_tokens,
)
stats.retract_request(previous)
stats.record_request(
model_name,
input_count,
output_count,
provider,
cost_usd=cost_usd,
kind=kind,
cache_read_tokens=cache_reads,
cache_write_tokens=sum(cache_writes),
)
recorded_requests[request_id] = RecordedRequest(
model_name=model_name,
provider=provider,
kind=kind,
input_tokens=input_count,
output_tokens=output_count,
cache_read_tokens=cache_reads,
cache_write_tokens=sum(cache_writes),
cost_usd=cost_usd,
usage_metadata=usage,
finalized=True,
message_ids=previous.message_ids
| (
frozenset({message_id})
if (message_id := getattr(message, "id", None))
else frozenset()
),
)
return RecordedUsage(
input_tokens=input_count - previous.input_tokens,
output_tokens=output_count - previous.output_tokens,
cost_usd=_cost_delta(
previous.cost_usd,
cost_usd,
model_name=model_name,
previous_model_name=previous.model_name,
),
request_tokens=input_count + output_count,
request_id=_provisional_bucket_key(request_id),
is_correction=True,
)
def record_message_usage(
stats: SessionStats,
message: object,
*,
fallback_model: str = "",
fallback_provider: str = "",
request_metadata: Mapping[str, Any] | None = None,
kind: UsageKind = "assistant",
recorded_requests: dict[UsageLedgerKey, RecordedRequest] | None = None,
attempt_scope: Hashable | None = None,
invocation_id: str | None = None,
) -> RecordedUsage | None:
"""Record usage attached to one streamed model message.
A request is entered in `recorded_requests` only once usable token metadata
has been recorded for it. Callers retain that ledger across stream rounds so
one API call stays one row, however its usage arrives.
A streamed chunk and a completed message report usage differently, so they
are handled differently. A completed `AIMessage` carries the request's
*whole* usage and is idempotent: replaying it must not count twice. A chunk
carries whatever the provider chose to emit at that point in the stream --
Anthropic and OpenAI attach the full usage to one chunk, while Google emits
an incremental delta on every chunk, which the consumer is expected to sum.
Skipping a chunk whose ID was already seen would drop every Google chunk
after the first, losing most of the request's output tokens and cost.
Summing them as separate requests would be wrong in the other direction, so
a later chunk instead *revises* the request already recorded: its earlier
contribution is retracted and re-recorded with the running totals. One API
call therefore counts once, with one per-model row, no matter how many
chunks carried its usage. Google also names the model only on its final
chunk, so the model is upgraded when a message supplies one and otherwise
left alone -- without that, one call would straddle a fallback-model row and
a real-model row.
Args:
stats: Accumulator that receives the request.
message: Streamed model message or chunk.
fallback_model: Model to use when response metadata does not name one.
fallback_provider: Provider to use when response metadata omits it.
request_metadata: Stream metadata identifying the provider configured for
this specific request, when available.
kind: Request class used by the type breakdown.
recorded_requests: Ledger of requests this stream consumer has already
recorded, keyed by stable invocation identity when available and by
message ID otherwise. Mutated in place.
attempt_scope: Lifecycle identity of the attempt that produced this
message. Keeps retries distinct when no model run ID is available.
invocation_id: LangChain model run ID shared by streaming and callback
deliveries for this invocation. Preferred over provider message IDs.
Returns:
The tokens and cost *this message* contributed, or `None` when it has no
usable usage metadata or was already recorded in full. A message
that only re-files an already-recorded request under a newly named
model reports zero tokens and the signed cost change, because
`stats` moved even though no new tokens arrived.
"""
usage = getattr(message, "usage_metadata", None)
if not isinstance(usage, Mapping) or not usage:
return None
from deepagents_code.cost_tracking import _MODEL_INVOCATION_METADATA_KEY
if recorded_requests is None:
recorded_requests = {}