import '../../../core/api_gateway.dart'; /// Reported token and cost usage of a run or one stage. No widgets here. /// /// Every figure is what the server recorded from the harness: nothing is /// estimated. A run total is partial when some stages that recorded usage /// reported no token count, and it is then labelled as a lower bound (`≥`). class TokenUsage { const TokenUsage({ required this.total, required this.partial, this.input, this.output, this.cacheRead, this.cost, this.costPartial = false, this.stages, this.tokenStages, }); /// The summed reported total. final int total; /// Some stages that recorded usage reported no token count. final bool partial; /// The input/output split, only when every counted stage reported it. final int? input; final int? output; /// The cache-read share of [total], only when every counted stage reported /// its cache components. Older rows never recorded them, so they have none. final int? cacheRead; /// The tokens that were not cache reads, when [cacheRead] is known. int? get fresh => cacheRead == null ? null : total - cacheRead!; /// The reported cost in USD, only when a positive cost was reported. Some /// providers (subscription models) report a cost of zero or none at all; /// that is "not reported", never a known zero. final double? cost; /// Some stages reported no cost, so [cost] is a lower bound. final bool costPartial; /// Run totals only: the stages that recorded usage, and those of them that /// reported tokens. final int? stages; final int? tokenStages; } /// The run's reported token usage from its `usage` total, or null when the /// server sent none (an older server's list, or a run with no model usage) or /// no stage reported a token count. TokenUsage? runTokenUsage(JsonMap run) { final raw = run['usage']; if (raw is! Map) return null; final stages = _int(raw['stages']); final tokenStages = _int(raw['tokens_known_stages']) ?? 0; final total = _int(raw['tokens_total']); if (tokenStages <= 0 || total == null) return null; final costStages = _int(raw['cost_known_stages']) ?? 0; final split = raw['split_known'] == true; final cost = costStages > 0 ? _positive(raw['cost_usd']) : null; return TokenUsage( total: total, partial: stages != null && tokenStages < stages, // The server omits a zero in/out, so a known split makes absence zero. input: split ? _int(raw['tokens_in']) ?? 0 : null, output: split ? _int(raw['tokens_out']) ?? 0 : null, cacheRead: _cacheRead(raw, total), cost: cost, costPartial: cost != null && stages != null && costStages < stages, stages: stages, tokenStages: tokenStages, ); } /// One stage's reported token usage from its step `usage`, or null when the /// stage reported no token count. TokenUsage? stageTokenUsage(JsonMap step) { final raw = step['usage']; if (raw is! Map || raw['tokens_known'] != true) return null; final total = _int(raw['tokens_total']); if (total == null) return null; final split = raw['split_known'] == true; return TokenUsage( total: total, partial: false, input: split ? _int(raw['tokens_in']) ?? 0 : null, output: split ? _int(raw['tokens_out']) ?? 0 : null, cacheRead: _cacheRead(raw, total), cost: raw['cost_known'] == true ? _positive(raw['cost_usd']) : null, ); } /// A compact token count: `950`, `1.2K`, `340K`, `22.4M`, `1.3B`. /// /// Decimal multiples, one decimal below a hundred units, whole units above. String formatTokenCount(int tokens) { if (tokens < 1000) return '$tokens'; const units = ['K', 'M', 'B', 'T']; var value = tokens / 1000; var unit = 0; while (value >= 1000 && unit < units.length - 1) { value /= 1000; unit++; } // Rounding 999.6K up would print "1000K"; promote it instead. if (value >= 999.5 && unit < units.length - 1) { value /= 1000; unit++; } final text = value < 99.95 ? value.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '') : value.round().toString(); return '$text${units[unit]}'; } /// The list row's compact label: `22.4M tokens`, or `≥22.4M tokens` when some /// stages did not report a count. String tokenUsageLabel(TokenUsage usage) => '${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)} tokens'; /// A stage row's compact label: the total, the cached share when the stage /// recorded its cache split, and the cost when a positive one was reported. /// `20.1M tokens · 95% cached · $0.42`. A missing figure is omitted, never /// shown as zero. String stageTokenRowLabel(TokenUsage usage) { final cacheRead = usage.cacheRead; final cost = usage.cost; return [ tokenUsageLabel(usage), if (cacheRead != null && usage.total > 0) '${(cacheRead * 100 / usage.total).round()}% cached', if (cost != null) cost < 0.005 ? '<\$0.01' : '\$${cost.toStringAsFixed(2)}', ].join(' · '); } /// The detail's token value: the compact total, then fresh versus cached /// when every stage reported its cache components, the in/out split when /// reported, and how many stages reported when the total is partial. /// `22.4M · 1.1M fresh, 21.3M cached · 900K in, 150K out`, /// `≥9 · 1 of 2 stages reported`. String tokenUsageDetail(TokenUsage usage) => [ '${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)}', if (usage.fresh != null) '${formatTokenCount(usage.fresh!)} fresh, ' '${formatTokenCount(usage.cacheRead!)} cached', if (usage.input != null && usage.output != null) '${formatTokenCount(usage.input!)} in, ' '${formatTokenCount(usage.output!)} out', if (usage.partial && usage.stages != null) '${usage.tokenStages} of ${usage.stages} stages reported', ].join(' · '); /// The wording for a cost no stage reported as a positive amount. const costNotReported = 'Not reported'; /// The reported cost: `$1.75`, `$0.10`, `$0.0042` (four places below a cent), /// `≥$0.10` when some stages reported no cost, and [costNotReported] when no /// positive cost was reported. String tokenUsageCost(TokenUsage usage) { final cost = usage.cost; if (cost == null) return costNotReported; final text = cost >= 0.01 ? cost.toStringAsFixed(2) : cost.toStringAsFixed(4); return '${usage.costPartial ? '≥' : ''}\$$text'; } int? _int(dynamic value) => value is num && value.isFinite && value >= 0 ? value.round() : null; double? _positive(dynamic value) => value is num && value.isFinite && value > 0 ? value.toDouble() : null; /// The cache reads, only when the server marked the cache split complete and /// the count fits inside the total. int? _cacheRead(Map raw, int total) { if (raw['cache_known'] != true) return null; final read = _int(raw['cache_read']) ?? 0; return read <= total ? read : null; }