llmLiveTrailUsage function

String llmLiveTrailUsage(
  1. LlmUsage usage,
  2. DateTime at
)

The extension's ### ๐Ÿ“Š usage block for usage, recorded at at; empty when there is nothing to say.

Implementation

String llmLiveTrailUsage(LlmUsage usage, DateTime at) {
  final lines = <String>[];
  final counts = [
    if (usage.inputTokens != null) 'in ${_count(usage.inputTokens)}',
    if (usage.outputTokens != null) 'out ${_count(usage.outputTokens)}',
    if (usage.cacheReadTokens != null)
      'cache read ${_count(usage.cacheReadTokens)}',
    if (usage.cacheWriteTokens != null)
      'cache write ${_count(usage.cacheWriteTokens)}',
  ];
  if (counts.isNotEmpty) lines.add('- tokens: ${counts.join(' ยท ')}');
  final meta = [
    if (usage.costUsd case final cost? when cost.isFinite)
      '\$${cost.toStringAsFixed(4)}',
    if (usage.apiDuration case final api?)
      'api ${(api.inMilliseconds / 1000).toStringAsFixed(1)}s',
  ];
  if (meta.isNotEmpty) lines.add('- cost: ${meta.join(' ยท ')}');
  if (usage.models.isNotEmpty) {
    final stamp = llmLiveTrailTimestamp(at);
    lines
      ..add('')
      ..add(
        '| model | in | out | cache read | cache write | cost | ctx | when |',
      )
      ..add('| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |');
    for (final m in usage.models) {
      final c = m.costUsd;
      final cost = c != null && c.isFinite ? '\$${c.toStringAsFixed(4)}' : '';
      lines.add(
        '| ${m.model} | ${_count(m.inputTokens)} | '
        '${_count(m.outputTokens)} | ${_count(m.cacheReadTokens)} | '
        '${_count(m.cacheWriteTokens)} | $cost |  | $stamp |',
      );
    }
  }
  if (lines.isEmpty) return '';
  return '\n### ๐Ÿ“Š usage\n\n${lines.join('\n')}\n';
}