blib/lib/Langertha/Usage.pm

filter: Statementstmt 96.6% 199 / 206 Branchbran 93.0% 121 / 130 Conditioncond 80.0% 124 / 155 MC/DCmcdc 63.9% 55 / 86 Subroutinesub 92.5% 25 / 27 Podpod 45.4% 5 / 11 totaltotal 86.0% 529 / 615 CC 131 SCAR 37.3
CC
131
Cov
90%
from_hash
76.2
merge
17.2
from_response
15.9
CRAP 41.6
« blib/lib/Langertha/Output/Tools.pm ↑ Summary blib/lib/Langertha/Role/Tools.pm »
1 package Langertha::Usage;
2 # ABSTRACT: Immutable value object for LLM token usage with cross-provider conversion
3 185 our $VERSION = '0.503';
4 185 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 185 ▶use Scalar::Util qw( blessed looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 185 ▶use Hash::Util::FieldHash qw( fieldhash );
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 # The %{} overload (back-compat for `$response->usage->{...}`) hijacks every
9 # `$self->{attr}` deref on the object — including the ones Moose's generated
10 # accessors use internally. A naive overload therefore breaks the accessors
11 # (verified: infinite recursion / undef reads). The canonical Perl solution is
12 # to keep the attribute values in a field hash (keyed by object identity, not
13 # by the object's own hash) and route both the accessors and the overload
14 # through it. See "HASH OVERLOAD" below.
15 185 fieldhash my %DATA;
16  
17 use overload
18 3143 ▶ '%{}' => sub { $_[0]->_as_hash },
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
19 185 fallback => 1;
20  
21 185 has input_tokens => ( is => 'ro', isa => 'Int', default => 0 );
22 185 has output_tokens => ( is => 'ro', isa => 'Int', default => 0 );
23 185 has total_tokens => ( is => 'ro', isa => 'Int', lazy => 1, builder => '_build_total_tokens' );
24  
25 185 has cached_tokens => ( is => 'ro', isa => 'Maybe[Int]', default => undef );
26 185 has cache_write_tokens => ( is => 'ro', isa => 'Maybe[Int]', default => undef );
27 185 has reasoning_tokens => ( is => 'ro', isa => 'Maybe[Int]', default => undef );
28 185 has input_includes_cache => ( is => 'ro', isa => 'Maybe[Bool]', default => undef );
29 185 has cost_usd => ( is => 'ro', isa => 'Maybe[Num]', default => undef );
30  
31 185 has raw => (
32 is => 'ro',
33 isa => 'Maybe[HashRef]',
34 default => undef,
35 );
36  
37 # The generated accessors read $self->{attr}, which the %{} overload would
38 # route through _as_hash. Route them through the field hash instead.
39 211 ▶around input_tokens => sub { my ( $orig, $self ) = @_; $DATA{$self}{input_tokens} };
Subroutine __ANON__: called CC=1 SCAR=0.0
40 159 ▶around output_tokens => sub { my ( $orig, $self ) = @_; $DATA{$self}{output_tokens} };
Subroutine __ANON__: called CC=1 SCAR=0.0
41 80 ▶around total_tokens => sub {
Subroutine __ANON__: called CC=5 SCAR=16.8
42 80 my ( $orig, $self ) = @_;
43 80 ▶ my $d = $DATA{$self} || {};
Condition50%1/2
$DATA{$self} || {}
l!l
800
MC/DC0%0/1
$DATA{$self} || {}
$DATA{$self}
Truth table50%1/2
A
A= $DATA{$self}
Aresult
11
00
44 80 ▶ return $d->{total_tokens} if defined $d->{total_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if defined $d->{"total_tokens"} 55 25 80
45 25 ▶ return ( $d->{input_tokens} // 0 ) + ( $d->{output_tokens} // 0 );
Condition50%2/4
$d->{"input_tokens"} // 0
l!l
250
$d->{"output_tokens"} // 0
l!l
250
MC/DC0%0/1
$d->{"input_tokens"} // 0
$d->{"input_tokens"}
MC/DC0%0/1
$d->{"output_tokens"} // 0
$d->{"output_tokens"}
Truth table50%1/2
A
A= $d->{"input_tokens"}
Aresult
11
00
Truth table50%1/2
A
A= $d->{"output_tokens"}
Aresult
11
00
46 185 };
47 432 ▶around cached_tokens => sub { my ( $orig, $self ) = @_; $DATA{$self}{cached_tokens} };
Subroutine __ANON__: called CC=1 SCAR=0.0
48 119 ▶around cache_write_tokens => sub { my ( $orig, $self ) = @_; $DATA{$self}{cache_write_tokens} };
Subroutine __ANON__: called CC=1 SCAR=0.0
49 42 ▶around reasoning_tokens => sub { my ( $orig, $self ) = @_; $DATA{$self}{reasoning_tokens} };
Subroutine __ANON__: called CC=1 SCAR=0.0
50 92 ▶around input_includes_cache => sub { my ( $orig, $self ) = @_; $DATA{$self}{input_includes_cache} };
Subroutine __ANON__: called CC=1 SCAR=0.0
51 60 ▶around cost_usd => sub { my ( $orig, $self ) = @_; $DATA{$self}{cost_usd} };
Subroutine __ANON__: called CC=1 SCAR=0.0
52 0 ▶around raw => sub { my ( $orig, $self ) = @_; $DATA{$self}{raw} };
Subroutine __ANON__: not called CC=1 SCAR=2.6
53  
54 # The constructor's writes to $self->{attr} go through the overload and are
55 # lost, so the field hash is populated here from the raw constructor args.
56 362 ▶sub BUILD {
Subroutine BUILD: called CC=3 SCAR=11.0
Pod undocumented
57 362 my ( $self, $args ) = @_;
58 $DATA{$self} = {
59 input_tokens => $args->{input_tokens} // 0,
60 output_tokens => $args->{output_tokens} // 0,
61 total_tokens => $args->{total_tokens},
62 cached_tokens => $args->{cached_tokens},
63 cache_write_tokens => $args->{cache_write_tokens},
64 reasoning_tokens => $args->{reasoning_tokens},
65 input_includes_cache => $args->{input_includes_cache},
66 cost_usd => $args->{cost_usd},
67 raw => $args->{raw},
68 362 ▶ };
Condition100%4/4
$args->{"input_tokens"} // 0
l!l
3602
$args->{"output_tokens"} // 0
l!l
3557
MC/DC100%1/1
$args->{"input_tokens"} // 0
$args->{"input_tokens"}
MC/DC100%1/1
$args->{"output_tokens"} // 0
$args->{"output_tokens"}
Truth table100%2/2
A
A= $args->{"input_tokens"}
Aresult
11
00
Truth table100%2/2
A
A= $args->{"output_tokens"}
Aresult
11
00
69 }
70  
71 # input_tokens without the cache reads and writes that are counted in it.
72 41 ▶sub uncached_input_tokens {
Subroutine uncached_input_tokens: called CC=6 SCAR=17.9
Pod documented
73 41 my ($self) = @_;
74 41 my $input = $self->input_tokens;
75 41 my $includes = $self->input_includes_cache;
76 41 ▶ return $input if defined $includes && !$includes;
Branch: 1 branch
BranchTrueFalseTotal
if defined $includes and not $includes 13 28 41
Condition100%3/3
defined $includes and not $includes
!ll&&!rl&&r
32513
MC/DC100%2/2
defined $includes and not $includes
defined $includes not $includes
Truth table100%3/3
A and not(B)
A= defined $includesB= not $includes
ABresult
0X0
100
111
77 28 ▶ my $rest = $input - ( $self->cached_tokens // 0 ) - ( $self->cache_write_tokens // 0 );
Condition75%3/4
$self->cached_tokens // 0
l!l
280
$self->cache_write_tokens // 0
l!l
820
MC/DC0%0/1
$self->cached_tokens // 0
$self->cached_tokens
MC/DC100%1/1
$self->cache_write_tokens // 0
$self->cache_write_tokens
Truth table50%1/2
A
A= $self->cached_tokens
Aresult
11
00
Truth table100%2/2
A
A= $self->cache_write_tokens
Aresult
11
00
78 28 ▶ return $rest < 0 ? 0 : $rest;
Branch: 1 branch
BranchTrueFalseTotal
$rest < 0 ? : 1 27 28
79 }
80  
81 0 ▶sub _build_total_tokens {
Subroutine _build_total_tokens: not called CC=1 SCAR=6.9
82 0 my ($self) = @_;
83 0 return $self->input_tokens + $self->output_tokens;
84 }
85  
86 # Build a Usage from any of the wire-format hashrefs we know about.
87 323 ▶sub from_hash {
Subroutine from_hash: called CC=75 SCAR=43.3
Pod documented
88 323 my ($class, $hash) = @_;
89 323 ▶ return $class->new unless $hash && ref($hash) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $hash and ref $hash eq "HASH" 1 322 323
Condition66%2/3
$hash and ref $hash eq "HASH"
!ll&&!rl&&r
10322
MC/DC50%1/2
$hash and ref $hash eq "HASH"
$hash ref $hash eq "HASH"
Truth table66%2/3
A and B
A= $hashB= ref $hash eq "HASH"
ABresult
0X0
100
111
90  
91 322 my $input = $hash->{input_tokens};
92 322 my $output = $hash->{output_tokens};
93 322 my $total = $hash->{total_tokens};
94  
95 322 ▶ $input = $hash->{prompt_tokens} if !defined $input && defined $hash->{prompt_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $input and defined $hash->{"prompt_tokens"} 181 141 322
Condition100%3/3
not defined $input and defined $hash->{"prompt_tokens"}
!ll&&!rl&&r
8655181
MC/DC100%2/2
not defined $input and defined $hash->{"prompt_tokens"}
not defined $input defined $hash->{"prompt_tokens"}
Truth table100%3/3
not(A) and B
A= not defined $inputB= defined $hash->{"prompt_tokens"}
ABresult
0X0
100
111
96 322 ▶ $input = $hash->{prompt_eval_count} if !defined $input && defined $hash->{prompt_eval_count};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $input and defined $hash->{"prompt_eval_count"} 5 317 322
Condition100%3/3
not defined $input and defined $hash->{"prompt_eval_count"}
!ll&&!rl&&r
267505
MC/DC100%2/2
not defined $input and defined $hash->{"prompt_eval_count"}
not defined $input defined $hash->{"prompt_eval_count"}
Truth table100%3/3
not(A) and B
A= not defined $inputB= defined $hash->{"prompt_eval_count"}
ABresult
0X0
100
111
97  
98 322 ▶ $output = $hash->{completion_tokens} if !defined $output && defined $hash->{completion_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $output and defined $hash->{"completion_tokens"} 159 163 322
Condition100%3/3
not defined $output and defined $hash->{"completion_tokens"}
!ll&&!rl&&r
7687159
MC/DC100%2/2
not defined $output and defined $hash->{"completion_tokens"}
not defined $output defined $hash->{"completion_tokens"}
Truth table100%3/3
not(A) and B
A= not defined $outputB= defined $hash->{"completion_tokens"}
ABresult
0X0
100
111
99 322 ▶ $output = $hash->{eval_count} if !defined $output && defined $hash->{eval_count};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $output and defined $hash->{"eval_count"} 5 317 322
Condition100%3/3
not defined $output and defined $hash->{"eval_count"}
!ll&&!rl&&r
235825
MC/DC100%2/2
not defined $output and defined $hash->{"eval_count"}
not defined $output defined $hash->{"eval_count"}
Truth table100%3/3
not(A) and B
A= not defined $outputB= defined $hash->{"eval_count"}
ABresult
0X0
100
111
100  
101 # Gemini's usageMetadata spelling (the raw body, before the engine renames it).
102 # Gemini counts thinking and the tool-use prompt beside the prompt and the
103 # answer: totalTokenCount = promptTokenCount + toolUsePromptTokenCount +
104 # candidatesTokenCount + thoughtsTokenCount. Thinking is billed as output, so
105 # it is folded into output_tokens (what OpenAI's completion_tokens already
106 # includes), the tool-use prompt into input_tokens. proto3 JSON omits zero
107 # counts, so either half of a sum may be missing (k299).
108 322 my $gemini_thoughts = $hash->{thoughtsTokenCount};
109 322 ▶ if ( !defined $input && ( defined $hash->{promptTokenCount} || defined $hash->{toolUsePromptTokenCount} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $input and defined $hash->{"promptTokenCount"} || defined $hash->{"toolUsePromptTokenCount"}) 14 308 322
Condition83%5/6
not defined $input and defined $hash->{"promptTokenCount"} || defined $hash->{"toolUsePromptTokenCount"}
!ll&&!rl&&r
2723614
defined $hash->{"promptTokenCount"} or defined $hash->{"toolUsePromptTokenCount"}
l!l&&r!l&&!r
14036
MC/DC66%2/3
not defined $input and defined $hash->{"promptTokenCount"} || defined $hash->{"toolUsePromptTokenCount"}
not defined $input defined $hash->{"promptTokenCount"} defined $hash->{"toolUsePromptTokenCount"}
Truth table75%3/4
not(A) and B or C
A= not defined $inputB= defined $hash->{"promptTokenCount"}C= defined $hash->{"toolUsePromptTokenCount"}
ABCresult
0XX0
1000
11X1
1011
110 14 ▶ $input = ( $hash->{promptTokenCount} // 0 ) + ( $hash->{toolUsePromptTokenCount} // 0 );
Condition75%3/4
$hash->{"promptTokenCount"} // 0
l!l
140
$hash->{"toolUsePromptTokenCount"} // 0
l!l
113
MC/DC0%0/1
$hash->{"promptTokenCount"} // 0
$hash->{"promptTokenCount"}
MC/DC100%1/1
$hash->{"toolUsePromptTokenCount"} // 0
$hash->{"toolUsePromptTokenCount"}
Truth table50%1/2
A
A= $hash->{"promptTokenCount"}
Aresult
11
00
Truth table100%2/2
A
A= $hash->{"toolUsePromptTokenCount"}
Aresult
11
00
111 }
112 322 ▶ if ( !defined $output && ( defined $hash->{candidatesTokenCount} || defined $gemini_thoughts ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $output and defined $hash->{"candidatesTokenCount"} || defined $gemini_thoughts) 14 308 322
Condition100%6/6
not defined $output and defined $hash->{"candidatesTokenCount"} || defined $gemini_thoughts
!ll&&!rl&&r
2406814
defined $hash->{"candidatesTokenCount"} or defined $gemini_thoughts
l!l&&r!l&&!r
13168
MC/DC100%3/3
not defined $output and defined $hash->{"candidatesTokenCount"} || defined $gemini_thoughts
not defined $output defined $hash->{"candidatesTokenCount"} defined $gemini_thoughts
Truth table100%4/4
not(A) and B or C
A= not defined $outputB= defined $hash->{"candidatesTokenCount"}C= defined $gemini_thoughts
ABCresult
0XX0
1000
11X1
1011
113 14 ▶ $output = ( $hash->{candidatesTokenCount} // 0 ) + ( $gemini_thoughts // 0 );
Condition100%4/4
$hash->{"candidatesTokenCount"} // 0
l!l
131
$gemini_thoughts // 0
l!l
68
MC/DC100%1/1
$hash->{"candidatesTokenCount"} // 0
$hash->{"candidatesTokenCount"}
MC/DC100%1/1
$gemini_thoughts // 0
$gemini_thoughts
Truth table100%2/2
A
A= $hash->{"candidatesTokenCount"}
Aresult
11
00
Truth table100%2/2
A
A= $gemini_thoughts
Aresult
11
00
114 }
115 322 ▶ $total = $hash->{totalTokenCount} if !defined $total && defined $hash->{totalTokenCount};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $total and defined $hash->{"totalTokenCount"} 11 311 322
Condition100%3/3
not defined $total and defined $hash->{"totalTokenCount"}
!ll&&!rl&&r
18212911
MC/DC100%2/2
not defined $total and defined $hash->{"totalTokenCount"}
not defined $total defined $hash->{"totalTokenCount"}
Truth table100%3/3
not(A) and B
A= not defined $totalB= defined $hash->{"totalTokenCount"}
ABresult
0X0
100
111
116  
117 322 ▶ $input = 0 + ($input // 0);
Condition100%2/2
$input // 0
l!l
28636
MC/DC100%1/1
$input // 0
$input
Truth table100%2/2
A
A= $input
Aresult
11
00
118 322 ▶ $output = 0 + ($output // 0);
Condition100%2/2
$output // 0
l!l
25468
MC/DC100%1/1
$output // 0
$output
Truth table100%2/2
A
A= $output
Aresult
11
00
119  
120 # Prompt-cache read/write counts each carry several wire spellings. OpenAI's
121 # Chat wire nests both under prompt_tokens_details (cached_tokens /
122 # cache_write_tokens); the Open-Responses envelope (OpenAI Responses, the
123 # Perplexity Agent API) nests them under input_tokens_details, mixing the
124 # OpenAI read key (cached_tokens) with the Anthropic-named counts
125 # (cache_read_input_tokens / cache_creation_input_tokens); Anthropic reports
126 # them flat; Gemini reports the read count as usageMetadata's
127 # cachedContentTokenCount (Engine::Gemini renames it cached_content_token_count).
128 # The OpenAI Chat nesting wins, then the Responses nesting, then the Anthropic
129 # flat keys, then Gemini's, then the canonical flat cached_tokens that
130 # Engine::AKI emits (karr #125 / #130 / #159 / k197). The read count and the
131 # write count are distinct quantities — the write count is deliberately NOT
132 # folded into cached_tokens. Values are read into lexicals first so a missing
133 # key never autovivifies the caller's hash.
134 322 my $ptd = $hash->{prompt_tokens_details};
135 322 ▶ $ptd = undef unless ref($ptd) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ptd eq "HASH" 281 41 322
136 322 my $itd = $hash->{input_tokens_details};
137 322 ▶ $itd = undef unless ref($itd) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $itd eq "HASH" 270 52 322
138  
139 # Whether the cache counts are part of the input count depends on where they
140 # were found, so it is recorded next to them (input_includes_cache, k263). A
141 # count nested in a *_details block breaks the prompt/input total down
142 # (OpenAI Chat, Open-Responses: the captures in t/data/ show input_tokens 8542
143 # beside a 4394 write, 4071 beside a 4068 write); Gemini's
144 # cachedContentTokenCount is part of promptTokenCount; AKI native's
145 # num_cached_tokens is a subset of prompt_length. Anthropic's flat keys are
146 # counted beside input_tokens, not in it.
147 322 my ( $cached, $cached_in_input );
148 322 ▶ if ( $ptd && defined $ptd->{cached_tokens} ) { $cached = $ptd->{cached_tokens}; $cached_in_input = 1 }
Branch: 7 branches
BranchTrueFalseTotal
if ($ptd and defined $ptd->{'cached_tokens'}) { } 41 281 322
elsif ($itd and defined $itd->{'cached_tokens'}) { } 51 230 281
elsif ($itd and defined $itd->{'cache_read_input_tokens'}) { } 0 230 230
elsif (defined $hash->{'cache_read_input_tokens'}) { } 25 205 230
elsif (defined $hash->{'cachedContentTokenCount'}) { } 2 203 205
elsif (defined $hash->{'cached_content_token_count'}) { } 3 200 203
elsif (defined $hash->{'cached_tokens'}) { } 4 196 200
Condition66%2/3
$ptd and defined $ptd->{"cached_tokens"}
!ll&&!rl&&r
281041
MC/DC50%1/2
$ptd and defined $ptd->{"cached_tokens"}
$ptd defined $ptd->{"cached_tokens"}
Truth table66%2/3
A and B
A= $ptdB= defined $ptd->{"cached_tokens"}
ABresult
0X0
100
111
149 51 ▶ elsif ( $itd && defined $itd->{cached_tokens} ) { $cached = $itd->{cached_tokens}; $cached_in_input = 1 }
Condition100%3/3
$itd and defined $itd->{"cached_tokens"}
!ll&&!rl&&r
229151
MC/DC100%2/2
$itd and defined $itd->{"cached_tokens"}
$itd defined $itd->{"cached_tokens"}
Truth table100%3/3
A and B
A= $itdB= defined $itd->{"cached_tokens"}
ABresult
0X0
100
111
150 0 ▶ elsif ( $itd && defined $itd->{cache_read_input_tokens} ) { $cached = $itd->{cache_read_input_tokens}; $cached_in_input = 1 }
Condition66%2/3
$itd and defined $itd->{"cache_read_input_tokens"}
!ll&&!rl&&r
22910
MC/DC0%0/2
$itd and defined $itd->{"cache_read_input_tokens"}
$itd defined $itd->{"cache_read_input_tokens"}
Truth table66%2/3
A and B
A= $itdB= defined $itd->{"cache_read_input_tokens"}
ABresult
0X0
100
111
151 25 elsif ( defined $hash->{cache_read_input_tokens} ) { $cached = $hash->{cache_read_input_tokens}; $cached_in_input = 0 }
152 2 elsif ( defined $hash->{cachedContentTokenCount} ) { $cached = $hash->{cachedContentTokenCount}; $cached_in_input = 1 }
153 3 elsif ( defined $hash->{cached_content_token_count} ) { $cached = $hash->{cached_content_token_count}; $cached_in_input = 1 }
154 4 elsif ( defined $hash->{cached_tokens} ) { $cached = $hash->{cached_tokens}; $cached_in_input = 1 }
155  
156 322 my ( $cache_write, $write_in_input );
157 322 ▶ if ( $ptd && defined $ptd->{cache_write_tokens} ) { $cache_write = $ptd->{cache_write_tokens}; $write_in_input = 1 }
Branch: 5 branches
BranchTrueFalseTotal
if ($ptd and defined $ptd->{'cache_write_tokens'}) { } 5 317 322
elsif ($itd and defined $itd->{'cache_write_tokens'}) { } 14 303 317
elsif ($itd and defined $itd->{'cache_creation_input_tokens'}) { } 26 277 303
elsif (defined $hash->{'cache_creation_input_tokens'}) { } 11 266 277
elsif (ref $hash->{'cache_creation'} eq 'HASH') { } 1 265 266
Condition100%3/3
$ptd and defined $ptd->{"cache_write_tokens"}
!ll&&!rl&&r
281365
MC/DC100%2/2
$ptd and defined $ptd->{"cache_write_tokens"}
$ptd defined $ptd->{"cache_write_tokens"}
Truth table100%3/3
A and B
A= $ptdB= defined $ptd->{"cache_write_tokens"}
ABresult
0X0
100
111
158 14 ▶ elsif ( $itd && defined $itd->{cache_write_tokens} ) { $cache_write = $itd->{cache_write_tokens}; $write_in_input = 1 }
Condition100%3/3
$itd and defined $itd->{"cache_write_tokens"}
!ll&&!rl&&r
2653814
MC/DC100%2/2
$itd and defined $itd->{"cache_write_tokens"}
$itd defined $itd->{"cache_write_tokens"}
Truth table100%3/3
A and B
A= $itdB= defined $itd->{"cache_write_tokens"}
ABresult
0X0
100
111
159 26 ▶ elsif ( $itd && defined $itd->{cache_creation_input_tokens} ) { $cache_write = $itd->{cache_creation_input_tokens}; $write_in_input = 1 }
Condition100%3/3
$itd and defined $itd->{"cache_creation_input_tokens"}
!ll&&!rl&&r
2651226
MC/DC100%2/2
$itd and defined $itd->{"cache_creation_input_tokens"}
$itd defined $itd->{"cache_creation_input_tokens"}
Truth table100%3/3
A and B
A= $itdB= defined $itd->{"cache_creation_input_tokens"}
ABresult
0X0
100
111
160 11 elsif ( defined $hash->{cache_creation_input_tokens} ) { $cache_write = $hash->{cache_creation_input_tokens}; $write_in_input = 0 }
161 elsif ( ref( $hash->{cache_creation} ) eq 'HASH' ) {
162 # Anthropic's per-TTL split (ephemeral_5m / ephemeral_1h), which Moonshot's
163 # /anthropic shim also reports; only read when the flat total is missing.
164 1 my @tiers = grep { defined } map { $hash->{cache_creation}{"ephemeral_${_}_input_tokens"} } qw( 5m 1h );
165 1 ▶ if (@tiers) { $cache_write = 0; $cache_write += $_ for @tiers; $write_in_input = 0 }
Branch: 1 branch
BranchTrueFalseTotal
if (@tiers) 1 0 1
166 }
167  
168 # One flag for both counts: every wire above nests both or flattens both. If
169 # a hash ever mixes the two, "not included" wins — pricing a count on top of
170 # input_tokens can overcharge, subtracting it can go below zero.
171 322 ▶ my $includes = defined $cached_in_input ? $cached_in_input : $write_in_input;
Branch: 1 branch
BranchTrueFalseTotal
defined $cached_in_input ? : 126 196 322
172 322 ▶ $includes = 0 if defined $write_in_input && !$write_in_input;
Branch: 1 branch
BranchTrueFalseTotal
if defined $write_in_input and not $write_in_input 12 310 322
Condition100%3/3
defined $write_in_input and not $write_in_input
!ll&&!rl&&r
2654512
MC/DC100%2/2
defined $write_in_input and not $write_in_input
defined $write_in_input not $write_in_input
Truth table100%3/3
A and not(B)
A= defined $write_in_inputB= not $write_in_input
ABresult
0X0
100
111
173  
174 # A canonical input_includes_cache key in the hash beats the inference from
175 # the spelling. Role::AnthropicCompatible adds it for a shim that spells the
176 # counts the Anthropic way but counts them inside input_tokens (AKIAnthropic,
177 # ADR 0031 / k265). It only applies when a cache count was found.
178 $includes = $hash->{input_includes_cache}
179 322 ▶ if defined $includes && defined $hash->{input_includes_cache};
Branch: 1 branch
BranchTrueFalseTotal
if defined $includes and defined $hash->{"input_includes_cache"} 9 313 322
Condition100%3/3
defined $includes and defined $hash->{"input_includes_cache"}
!ll&&!rl&&r
1941199
MC/DC100%2/2
defined $includes and defined $hash->{"input_includes_cache"}
defined $includes defined $hash->{"input_includes_cache"}
Truth table100%3/3
A and B
A= defined $includesB= defined $hash->{"input_includes_cache"}
ABresult
0X0
100
111
180  
181 # The reasoning share of output_tokens (already counted in it on every wire):
182 # OpenAI Chat nests it under completion_tokens_details, Open-Responses under
183 # output_tokens_details, Gemini reports thoughtsTokenCount (k299).
184 322 my $ctd = $hash->{completion_tokens_details};
185 322 my $otd = $hash->{output_tokens_details};
186 322 my $reasoning;
187 322 ▶ if ( ref($ctd) eq 'HASH' && defined $ctd->{reasoning_tokens} ) { $reasoning = $ctd->{reasoning_tokens} }
Branch: 3 branches
BranchTrueFalseTotal
if (ref $ctd eq 'HASH' and defined $ctd->{'reasoning_tokens'}) { } 45 277 322
elsif (ref $otd eq 'HASH' and defined $otd->{'reasoning_tokens'}) { } 18 259 277
elsif (defined $gemini_thoughts) { } 6 253 259
Condition66%2/3
ref $ctd eq "HASH" and defined $ctd->{"reasoning_tokens"}
!ll&&!rl&&r
277045
MC/DC50%1/2
ref $ctd eq "HASH" and defined $ctd->{"reasoning_tokens"}
ref $ctd eq "HASH" defined $ctd->{"reasoning_tokens"}
Truth table66%2/3
A and B
A= ref $ctd eq "HASH"B= defined $ctd->{"reasoning_tokens"}
ABresult
0X0
100
111
188 18 ▶ elsif ( ref($otd) eq 'HASH' && defined $otd->{reasoning_tokens} ) { $reasoning = $otd->{reasoning_tokens} }
Condition66%2/3
ref $otd eq "HASH" and defined $otd->{"reasoning_tokens"}
!ll&&!rl&&r
259018
MC/DC50%1/2
ref $otd eq "HASH" and defined $otd->{"reasoning_tokens"}
ref $otd eq "HASH" defined $otd->{"reasoning_tokens"}
Truth table66%2/3
A and B
A= ref $otd eq "HASH"B= defined $otd->{"reasoning_tokens"}
ABresult
0X0
100
111
189 6 elsif ( defined $gemini_thoughts ) { $reasoning = $gemini_thoughts }
190  
191 # What the provider says the request was billed, normalized to USD. xAI
192 # reports it in the usage block as cost_in_usd_ticks (1 USD = 10^10 ticks;
193 # chat/completions, Responses, images, video) and, on Responses, also as
194 # cost_in_nano_usd (1 USD = 10^9); both may be null there. The finer ticks
195 # win. The integers stay verbatim in raw (k354).
196 # The Perplexity Agent API sends usage.cost as an object that names its unit
197 # ({ currency => 'USD', total_cost => ..., input_cost => ... }, the captures
198 # in t/data/perplexity_agent_*); it is read only when the currency is USD and
199 # a total is there. A bare number under the generic name cost (OpenRouter's
200 # credits) carries no unit, so it is not read here: the engine that knows the
201 # unit copies it to the canonical cost_usd key, which is read first (k363).
202 322 my $cost_usd;
203 322 my $cost = $hash->{cost};
204 322 ▶ if ( defined $hash->{cost_usd} && !ref $hash->{cost_usd} && looks_like_number( $hash->{cost_usd} ) ) {
Branch: 4 branches
BranchTrueFalseTotal
if (defined $hash->{'cost_usd'} and not ref $hash->{'cost_usd'} and &looks_like_number($hash->{'cost_usd'})) { } 3 319 322
elsif (defined $hash->{'cost_in_usd_ticks'}) { } 7 312 319
elsif (defined $hash->{'cost_in_nano_usd'}) { } 2 310 312
elsif (ref $cost eq 'HASH' and uc($cost->{'currency'} // '') eq 'USD' and defined $cost->{'total_cost'} and not ref $cost->{'total_cost'} and &looks_like_number($cost->{'total_cost'})) { } 28 564 592
Condition66%4/6
defined $hash->{"cost_usd"} and not ref $hash->{"cost_usd"} and &looks_like_number($hash->{"cost_usd"})
!ll&&!rl&&r
31903
defined $hash->{"cost_usd"} and not ref $hash->{"cost_usd"}
!ll&&!rl&&r
31903
MC/DC33%1/3
defined $hash->{"cost_usd"} and not ref $hash->{"cost_usd"} and &looks_like_number($hash->{"cost_usd"})
defined $hash->{"cost_usd"} not ref $hash->{"cost_usd"} &looks_like_number($hash->{"cost_usd"})
Truth table50%2/4
A and not(B) and C
A= defined $hash->{"cost_usd"}B= not ref $hash->{"cost_usd"}C= &looks_like_number($hash->{"cost_usd"})
ABCresult
0XX0
10X0
1100
1111
205 3 $cost_usd = 0 + $hash->{cost_usd};
206 }
207 7 elsif ( defined $hash->{cost_in_usd_ticks} ) { $cost_usd = $hash->{cost_in_usd_ticks} / 10_000_000_000 }
208 2 elsif ( defined $hash->{cost_in_nano_usd} ) { $cost_usd = $hash->{cost_in_nano_usd} / 1_000_000_000 }
209 ▶ elsif ( ref($cost) eq 'HASH' && uc( $cost->{currency} // '' ) eq 'USD'
Condition85%12/14
ref $cost eq "HASH" and uc($cost->{"currency"} // "") eq "USD" and defined $cost->{"total_cost"} and not ref $cost->{"total_cost"} and &looks_like_number($cost->{"total_cost"})
!ll&&!rl&&r
282028
ref $cost eq "HASH" and uc($cost->{"currency"} // "") eq "USD" and defined $cost->{"total_cost"} and not ref $cost->{"total_cost"}
!ll&&!rl&&r
282028
ref $cost eq "HASH" and uc($cost->{"currency"} // "") eq "USD" and defined $cost->{"total_cost"}
!ll&&!rl&&r
281128
ref $cost eq "HASH" and uc($cost->{"currency"} // "") eq "USD"
!ll&&!rl&&r
279229
$cost->{"currency"} // ""
l!l
301
MC/DC60%3/5
ref $cost eq "HASH" and uc($cost->{"currency"} // "") eq "USD" and defined $cost->{"total_cost"} and not ref $cost->{"total_cost"} and &looks_like_number($cost->{"total_cost"})
ref $cost eq "HASH" $cost->{"currency"} defined $cost->{"total_cost"} not ref $cost->{"total_cost"} &looks_like_number($cost->{"total_cost"})
Truth table66%4/6
A and B and C and not(D) and E
A= ref $cost eq "HASH"B= $cost->{"currency"}C= defined $cost->{"total_cost"}D= not ref $cost->{"total_cost"}E= &looks_like_number($cost->{"total_cost"})
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
210 && defined $cost->{total_cost} && !ref $cost->{total_cost} && looks_like_number( $cost->{total_cost} ) ) {
211 28 $cost_usd = 0 + $cost->{total_cost};
212 }
213  
214 322 my %args = ( input_tokens => $input, output_tokens => $output );
215 322 ▶ $args{total_tokens} = 0 + $total if defined $total;
Branch: 1 branch
BranchTrueFalseTotal
if defined $total 193 129 322
216 322 ▶ $args{cached_tokens} = 0 + $cached if defined $cached;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cached 126 196 322
217 322 ▶ $args{cache_write_tokens} = 0 + $cache_write if defined $cache_write;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cache_write 57 265 322
218 322 ▶ $args{reasoning_tokens} = 0 + $reasoning if defined $reasoning;
Branch: 1 branch
BranchTrueFalseTotal
if defined $reasoning 69 253 322
219 322 ▶ $args{cost_usd} = $cost_usd if defined $cost_usd;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cost_usd 40 282 322
220 322 ▶ $args{input_includes_cache} = $includes ? 1 : 0 if defined $includes;
Branch: 2 branches
BranchTrueFalseTotal
if defined $includes 128 194 322
$includes ? : 110 18 128
221 322 $args{raw} = $hash;
222 322 return $class->new(%args);
223 }
224  
225 # Build a Usage from any response shape: a Langertha::Response, a HashRef
226 # with a usage key, or undef.
227 5 ▶sub from_response {
Subroutine from_response: called CC=11 SCAR=27.7
Pod documented
228 5 my ($class, $response) = @_;
229 5 ▶ return $class->new unless $response;
Branch: 1 branch
BranchTrueFalseTotal
unless $response 0 5 5
230  
231 5 ▶ if ( blessed($response) && $response->isa('Langertha::Response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($response) and $response->isa("Langertha::Response")) 1 4 5
Condition66%2/3
builtin::blessed($response) and $response->isa("Langertha::Response")
!ll&&!rl&&r
401
MC/DC50%1/2
builtin::blessed($response) and $response->isa("Langertha::Response")
builtin::blessed($response) $response->isa("Langertha::Response")
Truth table66%2/3
A and B
A= builtin::blessed($response)B= $response->isa("Langertha::Response")
ABresult
0X0
100
111
232 1 ▶ my $usage = $response->has_usage ? $response->usage : undef;
Branch: 1 branch
BranchTrueFalseTotal
$response->has_usage ? : 0 1 1
233 1 ▶ return $usage if blessed($usage) && $usage->isa('Langertha::Usage');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($usage) and $usage->isa("Langertha::Usage") 0 1 1
Condition33%1/3
builtin::blessed($usage) and $usage->isa("Langertha::Usage")
!ll&&!rl&&r
100
MC/DC0%0/2
builtin::blessed($usage) and $usage->isa("Langertha::Usage")
builtin::blessed($usage) $usage->isa("Langertha::Usage")
Truth table33%1/3
A and B
A= builtin::blessed($usage)B= $usage->isa("Langertha::Usage")
ABresult
0X0
100
111
234 1 ▶ return $class->from_hash( $usage || {} );
Condition50%1/2
$usage || {}
l!l
01
MC/DC0%0/1
$usage || {}
$usage
Truth table50%1/2
A
A= $usage
Aresult
11
00
235 }
236 4 ▶ if ( ref($response) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $response eq "HASH") 4 0 4
237 4 ▶ return $class->from_raw($response) // $class->from_hash( $response->{usage} || {} );
Condition60%3/5
$class->from_raw($response) // $class->from_hash($response->{"usage"} || {})
l!l&&r!l&&!r
310
$response->{'usage'} || {}
l!l
01
MC/DC0%0/2
$class->from_raw($response) // $class->from_hash($response->{"usage"} || {})
$class->from_raw($response) $class->from_hash($response->{"usage"} || {})
MC/DC0%0/1
$response->{'usage'} || {}
$response->{'usage'}
Truth table66%2/3
A // B
A= $class->from_raw($response)B= $class->from_hash($response->{"usage"} || {})
ABresult
1X1
011
000
Truth table50%1/2
A
A= $response->{'usage'}
Aresult
11
00
238 }
239 0 return $class->new;
240 }
241  
242 # Build a Usage from a raw decoded provider response body; undef when the body
243 # reports no usage. Probes with lexicals so the caller's body never autovivifies.
244 58 ▶sub from_raw {
Subroutine from_raw: called CC=13 SCAR=25.7
Pod documented
245 58 my ($class, $data) = @_;
246 58 ▶ return undef unless ref($data) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 2 56 58
247 56 for my $key (qw( usage usageMetadata )) {
248 80 ▶ return $class->from_hash( $data->{$key} ) if ref( $data->{$key} ) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $data->{$key} eq "HASH" 37 43 80
249 }
250 19 my $envelope = $data->{response};
251 19 ▶ if ( ref($envelope) eq 'HASH' && ref( $envelope->{usage} ) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $envelope eq "HASH" and ref $envelope->{"usage"} eq "HASH") 1 18 19
Condition66%2/3
ref $envelope eq "HASH" and ref $envelope->{"usage"} eq "HASH"
!ll&&!rl&&r
1801
MC/DC50%1/2
ref $envelope eq "HASH" and ref $envelope->{"usage"} eq "HASH"
ref $envelope eq "HASH" ref $envelope->{"usage"} eq "HASH"
Truth table66%2/3
A and B
A= ref $envelope eq "HASH"B= ref $envelope->{"usage"} eq "HASH"
ABresult
0X0
100
111
252 1 return $class->from_hash( $envelope->{usage} );
253 }
254 # Ollama native: top-level counts. A zero count is "not reported", as in
255 # Engine::Ollama's chat_response, so a body with only zeros has no usage.
256 18 ▶ my %ollama = map { $data->{$_} ? ( $_ => $data->{$_} ) : () } qw( prompt_eval_count eval_count );
Branch: 1 branch
BranchTrueFalseTotal
$data->{$_} ? : 6 30 36
257 18 ▶ return $class->from_hash( \%ollama ) if %ollama;
Branch: 1 branch
BranchTrueFalseTotal
if %ollama 4 14 18
258 # AKI native: top-level counts under their own names (Engine::AKI's
259 # chat_response reads the same keys, by definedness).
260 14 ▶ my %aki = map { defined $data->{$_} ? ( $_ => $data->{$_} ) : () }
Branch: 1 branch
BranchTrueFalseTotal
defined $data->{$_} ? : 7 35 42
261 qw( prompt_length num_generated_tokens num_cached_tokens );
262 14 ▶ if (%aki) {
Branch: 1 branch
BranchTrueFalseTotal
if (%aki) 3 11 14
263 return $class->new(
264 input_tokens => 0 + ( $aki{prompt_length} // 0 ),
265 output_tokens => 0 + ( $aki{num_generated_tokens} // 0 ),
266 exists $aki{num_cached_tokens}
267 3 ▶ ? ( cached_tokens => 0 + $aki{num_cached_tokens}, input_includes_cache => 1 ) : (),
Branch: 1 branch
BranchTrueFalseTotal
exists $aki{'num_cached_tokens'} ? : 3 0 3
Condition100%4/4
$aki{"prompt_length"} // 0
l!l
21
$aki{"num_generated_tokens"} // 0
l!l
21
MC/DC100%1/1
$aki{"prompt_length"} // 0
$aki{"prompt_length"}
MC/DC100%1/1
$aki{"num_generated_tokens"} // 0
$aki{"num_generated_tokens"}
Truth table100%2/2
A
A= $aki{"prompt_length"}
Aresult
11
00
Truth table100%2/2
A
A= $aki{"num_generated_tokens"}
Aresult
11
00
268 raw => \%aki,
269 );
270 }
271 11 return undef;
272 }
273  
274  
275 # Immutable merge — returns a new Usage that is the sum of self + other.
276 # Cache and reasoning counts are summed (undef only when neither side reported one). When
277 # one side counts its cache inside input_tokens (flag 1, or undef with counts)
278 # and the other beside it (flag 0), the beside side's cache counts are added to
279 # its input_tokens first, so the sum is "inside" throughout and priced without
280 # loss (k265).
281 15 ▶sub merge {
Subroutine merge: called CC=17 SCAR=28.5
Pod documented
282 15 my ($self, $other) = @_;
283 15 ▶ return $self unless $other;
Branch: 1 branch
BranchTrueFalseTotal
unless $other 0 15 15
284 15 my %cache;
285 15 for my $count (qw( cached_tokens cache_write_tokens reasoning_tokens )) {
286 45 my @seen = grep { defined } $self->$count, $other->$count;
287 45 ▶ next unless @seen;
Branch: 1 branch
BranchTrueFalseTotal
unless @seen 30 15 45
288 15 $cache{$count} = 0;
289 15 $cache{$count} += $_ for @seen;
290 }
291 15 ▶ my @reported = grep { defined $_->cached_tokens || defined $_->cache_write_tokens } $self, $other;
Condition66%2/3
defined $_->cached_tokens || defined $_->cache_write_tokens
l!l&&r!l&&!r
13017
MC/DC50%1/2
defined $_->cached_tokens || defined $_->cache_write_tokens
defined $_->cached_tokens defined $_->cache_write_tokens
Truth table66%2/3
A || B
A= defined $_->cached_tokensB= defined $_->cache_write_tokens
ABresult
1X1
011
000
292 15 ▶ my @beside = grep { defined $_->input_includes_cache && !$_->input_includes_cache } @reported;
Condition100%3/3
defined $_->input_includes_cache && !$_->input_includes_cache
!ll&&!rl&&r
247
MC/DC100%2/2
defined $_->input_includes_cache && !$_->input_includes_cache
defined $_->input_includes_cache !$_->input_includes_cache
Truth table100%3/3
A && not(B)
A= defined $_->input_includes_cacheB= !$_->input_includes_cache
ABresult
0X0
100
111
293 15 my $input = $self->input_tokens + $other->input_tokens;
294 15 my $includes;
295 15 ▶ if ( @beside && @beside < @reported ) {
Branch: 3 branches
BranchTrueFalseTotal
if (@beside and @beside < @reported) { } 4 11 15
elsif (@beside) { } 2 9 11
elsif (@reported) { } 1 8 9
Condition100%3/3
@beside and @beside < @reported
!ll&&!rl&&r
924
MC/DC100%2/2
@beside and @beside < @reported
@beside @beside < @reported
Truth table100%3/3
A and B
A= @besideB= @beside < @reported
ABresult
0X0
100
111
296 4 ▶ $input += ( $_->cached_tokens // 0 ) + ( $_->cache_write_tokens // 0 ) for @beside;
Condition50%2/4
$_->cached_tokens // 0
l!l
40
$_->cache_write_tokens // 0
l!l
40
MC/DC0%0/1
$_->cached_tokens // 0
$_->cached_tokens
MC/DC0%0/1
$_->cache_write_tokens // 0
$_->cache_write_tokens
Truth table50%1/2
A
A= $_->cached_tokens
Aresult
11
00
Truth table50%1/2
A
A= $_->cache_write_tokens
Aresult
11
00
297 4 $includes = 1;
298 }
299 elsif (@beside) {
300 2 $includes = 0;
301 }
302 elsif (@reported) {
303 # All inside: 1 when every side said so, else undef (which reads as inside).
304 1 ▶ $includes = ( grep { !defined $_->input_includes_cache } @reported ) ? undef : 1;
Branch: 1 branch
BranchTrueFalseTotal
grep({not defined $_->input_includes_cache;} @reported) ? : 0 1 1
305 }
306 # A cost is only known for the sum when both sides report one: a partial
307 # sum would read as the whole bill.
308 15 my @costs = grep { defined } $self->cost_usd, $other->cost_usd;
309 15 ▶ return ref($self)->new(
Branch: 2 branches
BranchTrueFalseTotal
@costs == 2 ? : 1 14 15
defined $includes ? : 7 8 15
310 input_tokens => $input,
311 output_tokens => $self->output_tokens + $other->output_tokens,
312 %cache,
313 @costs == 2 ? ( cost_usd => $costs[0] + $costs[1] ) : (),
314 defined $includes ? ( input_includes_cache => $includes ) : (),
315 );
316 }
317  
318  
319 # Canonical hash representation (input_tokens / output_tokens / total_tokens).
320 14 ▶sub to_hash {
Subroutine to_hash: called CC=1 SCAR=0.0
Pod undocumented
321 14 my ($self) = @_;
322 return {
323 14 input_tokens => $self->input_tokens,
324 output_tokens => $self->output_tokens,
325 total_tokens => $self->total_tokens,
326 };
327 }
328  
329 # Backing for the %{} overload. When a provider hash was captured (raw), that
330 # hash is returned verbatim so existing `$response->usage->{...}` callers keep
331 # seeing the exact engine-normalized keys they always saw — including
332 # provider-specific extras (cache tokens, token details) and the deliberate
333 # absence of keys the engine normalized away. Without a raw hash (a Usage
334 # constructed directly), the canonical to_hash shape is returned.
335 3143 ▶sub _as_hash {
Subroutine _as_hash: called CC=8 SCAR=23.0
336 3143 my ($self) = @_;
337 3143 ▶ my $d = $DATA{$self} || {};
Condition100%2/2
$DATA{$self} || {}
l!l
543089
MC/DC100%1/1
$DATA{$self} || {}
$DATA{$self}
Truth table100%2/2
A
A= $DATA{$self}
Aresult
11
00
338 3143 ▶ return $d->{raw} if $d->{raw};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"raw"} 54 3089 3143
339 return {
340 input_tokens => $d->{input_tokens} // 0,
341 output_tokens => $d->{output_tokens} // 0,
342 3089 ▶ total_tokens => $d->{total_tokens} // ( ( $d->{input_tokens} // 0 ) + ( $d->{output_tokens} // 0 ) ),
Condition45%5/11
$d->{"input_tokens"} // 0
l!l
03089
$d->{"output_tokens"} // 0
l!l
03089
$d->{"total_tokens"} // ($d->{"input_tokens"} // 0) + ($d->{"output_tokens"} // 0)
l!l&&r!l&&!r
003089
$d->{"input_tokens"} // 0
l!l
03089
$d->{"output_tokens"} // 0
l!l
03089
MC/DC0%0/1
$d->{"output_tokens"} // 0
$d->{"output_tokens"}
MC/DC0%0/2
$d->{"total_tokens"} // ($d->{"input_tokens"} // 0) + ($d->{"output_tokens"} // 0)
$d->{"total_tokens"} $d->{"input_tokens"}
MC/DC0%0/1
$d->{"output_tokens"} // 0
$d->{"output_tokens"}
Truth table50%1/2
A
A= $d->{"output_tokens"}
Aresult
11
00
Truth table33%1/3
A // B
A= $d->{"total_tokens"}B= $d->{"input_tokens"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $d->{"output_tokens"}
Aresult
11
00
343 };
344 }
345  
346 # Make the object transparent to any JSON encoder configured with
347 # convert_blessed => 1 (the house default, see Langertha::Plugin::Langfuse).
348 # to_hash is the complete canonical representation, so this is a plain
349 # delegator — nothing is dropped.
350 11 ▶sub TO_JSON { shift->to_hash }
Subroutine TO_JSON: called CC=1 SCAR=0.0
Pod undocumented
351  
352 2 ▶sub to_openai_format {
Subroutine to_openai_format: called CC=1 SCAR=0.0
Pod undocumented
353 2 my ($self) = @_;
354 return {
355 2 prompt_tokens => $self->input_tokens,
356 completion_tokens => $self->output_tokens,
357 total_tokens => $self->total_tokens,
358 };
359 }
360  
361 2 ▶sub to_anthropic_format {
Subroutine to_anthropic_format: called CC=1 SCAR=0.0
Pod undocumented
362 2 my ($self) = @_;
363 return {
364 2 input_tokens => $self->input_tokens,
365 output_tokens => $self->output_tokens,
366 };
367 }
368  
369 2 ▶sub to_ollama_format {
Subroutine to_ollama_format: called CC=1 SCAR=0.0
Pod undocumented
370 2 my ($self) = @_;
371 return {
372 2 prompt_eval_count => $self->input_tokens,
373 eval_count => $self->output_tokens,
374 };
375 }
376  
377  
378 185 __PACKAGE__->meta->make_immutable;
379 185 1;
380  
381 __END__
382  
383 =pod
384  
385 =encoding UTF-8
386  
387 =head1 NAME
388  
389 Langertha::Usage - Immutable value object for LLM token usage with cross-provider conversion
390  
391 =head1 VERSION
392  
393 version 0.503
394  
395 =head2 from_raw
396  
397 my $data = $engine->parse_response($http_response);
398 my $usage = Langertha::Usage->from_raw($data)
399 or return; # the body reported no usage
400 printf "%d in / %d out\n", $usage->input_tokens, $usage->output_tokens;
401  
402 Class method. Builds a Usage from a B<raw decoded provider response body>, the
403 HashRef C<parse_response> returns — for callers that send their own requests
404 and never get a L<Langertha::Response>. It finds the usage block wherever the
405 provider puts it: C<usage> (OpenAI-compatible, Anthropic, Open-Responses),
406 C<usageMetadata> (Gemini), C<response.usage> (an Open-Responses event
407 envelope), the top-level C<prompt_eval_count> / C<eval_count> of Ollama's
408 native API, or the top-level C<prompt_length> / C<num_generated_tokens> /
409 C<num_cached_tokens> of AKI.IO's native API. The usage block and the Ollama
410 counts are then read by L</from_hash>, so every spelling it knows applies.
411  
412 Returns C<undef> when the body reports no usage (or is not a HashRef), so a
413 caller can tell "not reported" from "zero tokens". As in
414 L<Langertha::Engine::Ollama>, an Ollama count of zero counts as not reported.
415  
416 =head2 from_response
417  
418 my $usage = Langertha::Usage->from_response($response_or_body);
419  
420 Class method. Builds a Usage from a L<Langertha::Response> (its C<usage>), or
421 from a raw body HashRef via L</from_raw>. Always returns a Usage: all-zero
422 when nothing is reported.
423  
424 =head2 from_hash
425  
426 my $usage = Langertha::Usage->from_hash($usage_block);
427  
428 Class method. Builds a Usage from a provider's usage block, accepting the
429 OpenAI (C<prompt_tokens> / C<completion_tokens>), Anthropic and Open-Responses
430 (C<input_tokens> / C<output_tokens>), Ollama (C<prompt_eval_count> /
431 C<eval_count>) and Gemini (C<promptTokenCount> / C<candidatesTokenCount> /
432 C<totalTokenCount>) spellings, in that order of preference, plus the cache
433 counts described under L</cached_tokens> and L</cache_write_tokens>, the
434 L</reasoning_tokens> share and the provider-reported L</cost_usd>.
435  
436 Gemini counts thinking and the tool-use prompt beside the prompt and the
437 answer (C<totalTokenCount> is their sum), so from the Gemini spelling
438 C<output_tokens> is C<candidatesTokenCount> plus C<thoughtsTokenCount> and
439 C<input_tokens> is C<promptTokenCount> plus C<toolUsePromptTokenCount>.
440 Thinking is billed at the output rate; C<output_tokens> then means what
441 OpenAI's C<completion_tokens> means, reasoning included.
442  
443 =head2 merge
444  
445 my $sum = $usage->merge($other);
446  
447 Returns a new Usage holding the sum of both: C<input_tokens>, C<output_tokens>,
448 and L</cached_tokens> / L</cache_write_tokens> / L</reasoning_tokens> (a side that did not report a
449 count adds nothing; the sum stays C<undef> when neither did). L</input_includes_cache>
450 comes from the sides that reported a cache count. When both count it beside
451 C<input_tokens> (false) the sum is false. When one counts it inside (true, or
452 C<undef>) and the other beside, the beside side's cache counts are added to its
453 C<input_tokens> before summing and the sum is true, so pricing the merged Usage
454 costs the same as pricing both parts. When both count it inside, the sum is
455 true, or C<undef> if either side's flag was C<undef>. L</cost_usd> is summed
456 only when both sides report one; otherwise the sum's cost is C<undef>, since
457 a partial sum would read as the whole bill. L</raw> is not carried over.
458  
459 =head1 HASH OVERLOAD — backward compatibility
460  
461 C<Langertha::Usage> overloads C<%{}>, so a Usage object can keep being
462 dereferenced as a hash: C<< $response->usage->{prompt_tokens} >> keeps working.
463 This is the deliberate back-compat seam for the coercion of
464 L<Langertha::Response/usage> from a raw HashRef to a C<Langertha::Usage>
465 object (karr #43).
466  
467 When the object was built from a provider hash (via L</from_hash>, which is
468 what L<Langertha::Response> does in C<BUILDARGS>), the overload returns that
469 hash B<verbatim> — stored in L</raw>. Callers therefore keep seeing exactly
470 the engine-normalized keys they always saw: provider-specific extras
471 (Anthropic cache tokens, OpenAI C<prompt_tokens_details> /
472 C<completion_tokens_details>) survive, and keys the engine normalized away
473 (Gemini camelCase, Ollama C<prompt_eval_count> / C<eval_count>) stay absent.
474 C<exists> checks behave exactly as they did on the raw hash.
475  
476 These engine-normalized keys are legacy: the accessors above read every
477 spelling, so no engine needs to rename for Usage's sake any more. They are
478 kept for compatibility and are B<not> deprecated. For example
479 L<Langertha::Engine::Gemini> still serves C<prompt_tokens>,
480 C<completion_tokens>, C<total_tokens> and C<cached_content_token_count> here
481 in place of Gemini's camelCase C<usageMetadata> names.
482  
483 For a Usage constructed directly (no raw hash), the overload returns the
484 canonical L</to_hash> shape (C<input_tokens> / C<output_tokens> /
485 C<total_tokens>). New code should prefer the accessors and the
486 C<to_*_format> methods over hash dereferencing.
487  
488 =head2 Why the field hash
489  
490 A naive C<%{}> overload on a Moose class is impossible: the overload hijacks
491 every C<< $self->{attr} >> deref on the object, including the ones Moose's
492 generated accessors use internally, so the accessors read through the overload
493 and recurse (verified: infinite recursion / undef reads). The canonical Perl
494 solution is to keep the attribute values in a C<Hash::Util::FieldHash> keyed
495 by object identity and route B<both> the accessors (via C<around> modifiers)
496 and the overload through it. The object's own hash is then never read, so the
497 overload only ever serves caller hash derefs.
498  
499 =head2 cached_tokens
500  
501 Number of prompt tokens served from the provider's prefix cache (the cache
502 B<read> count), when the provider reports it. L</from_hash> parses it from any
503 of its wire spellings: OpenAI's Chat wire nests it at
504 C<usage.prompt_tokens_details.cached_tokens> (also Mistral, and any
505 OpenAI-compatible server such as SGLang with C<return_cached_tokens_details>),
506 the Open-Responses envelope (OpenAI Responses, the Perplexity Agent API) nests
507 it at C<usage.input_tokens_details.cached_tokens> (or the Anthropic-named
508 C<cache_read_input_tokens> in the same block), and Anthropic reports it flat as
509 C<usage.cache_read_input_tokens>. The OpenAI Chat nesting wins, then the
510 Responses nesting, then the Anthropic flat key. Gemini reports it as
511 C<usageMetadata.cachedContentTokenCount> (C<cached_content_token_count> after
512 L<Langertha::Engine::Gemini> renames it), read after the Anthropic key. A flat
513 canonical C<cached_tokens> (what L<Langertha::Engine::AKI> puts in its usage
514 hash, from AKI.IO's native C<num_cached_tokens>) is read last. C<undef> when the
515 provider does not report a cache-read count.
516  
517 Note: on OpenAI (GPT-5.6 and later) this count excludes hidden tokens and
518 rounds down to a multiple of 128, so cost arithmetic built on it is
519 approximate by construction.
520  
521 =head2 cache_write_tokens
522  
523 Number of prompt tokens written to the provider's prefix cache (the cache
524 B<creation> count), a distinct quantity from L</cached_tokens> and deliberately
525 not folded into it. L</from_hash> parses it from any of its wire spellings:
526 OpenAI's Chat wire nests it at C<usage.prompt_tokens_details.cache_write_tokens>,
527 the Open-Responses envelope (OpenAI Responses, the Perplexity Agent API) nests
528 it at C<usage.input_tokens_details.cache_creation_input_tokens>, and Anthropic
529 reports it flat as C<usage.cache_creation_input_tokens> (Anthropic further splits
530 that count across TTL tiers under C<usage.cache_creation>, which stays verbatim
531 in L</raw>). The OpenAI Chat nesting wins, then the Responses nesting, then the
532 Anthropic flat key; without the flat key the C<ephemeral_5m_input_tokens> /
533 C<ephemeral_1h_input_tokens> of C<usage.cache_creation> are summed. C<undef>
534 when the provider does not report a cache-write count.
535  
536 =head2 input_includes_cache
537  
538 Whether L</cached_tokens> and L</cache_write_tokens> are already counted in
539 C<input_tokens>. C<input_tokens> keeps the meaning the wire gives it, and
540 that meaning differs: OpenAI's C<prompt_tokens>, the Open-Responses
541 C<input_tokens>, Gemini's C<promptTokenCount> and AKI.IO's C<prompt_length>
542 include the cached tokens; Anthropic's C<input_tokens> counts only the tokens
543 after the last cache breakpoint, with C<cache_read_input_tokens> and
544 C<cache_creation_input_tokens> beside it. L</from_hash> and L</from_raw> set
545 this flag from where they found the cache counts: true for a count nested in
546 C<prompt_tokens_details> / C<input_tokens_details>, for Gemini's and for the
547 flat C<cached_tokens>; false for Anthropic's flat keys. C<undef> when no cache
548 count was reported, or when the object was built with C<new> and the flag was
549 not passed.
550  
551 The Anthropic-compatible shims follow the Anthropic spelling, but not always
552 its meaning: AKI.IO's C</anthropic> endpoint reports the same numbers under
553 C<input_tokens> as its OpenAI face does under C<prompt_tokens> (cached reads
554 included). A canonical C<input_includes_cache> key in the usage hash therefore
555 beats the inference when a cache count was found;
556 L<Langertha::Role::AnthropicCompatible> adds it for an engine whose
557 C<_usage_input_includes_cache> hook answers (L<Langertha::Engine::AKIAnthropic>
558 answers true), so the key also shows in C<< $response->usage->{...} >>.
559  
560 =head2 reasoning_tokens
561  
562 How many of C<output_tokens> the model spent reasoning (thinking), when the
563 provider reports it. The count is already part of C<output_tokens> — never add
564 it again. L</from_hash> reads OpenAI Chat's
565 C<completion_tokens_details.reasoning_tokens>, then the Open-Responses
566 C<output_tokens_details.reasoning_tokens>, then Gemini's C<thoughtsTokenCount>
567 (which Gemini reports beside C<candidatesTokenCount>, so L</from_hash> adds it
568 into C<output_tokens>). C<undef> when the provider does not report one.
569  
570 =head2 cost_usd
571  
572 What the provider says the request was billed, in US dollars, when it reports
573 it: the actual charge after its discounts (prompt caching) and including its
574 server-side tool fees. xAI puts it in every usage block (chat completions,
575 Responses, image and video generation) as the integer C<cost_in_usd_ticks>
576 (1 USD = 10,000,000,000 ticks), and on Responses also as C<cost_in_nano_usd>
577 (1 USD = 1,000,000,000 nano-USD). L</from_hash> converts whichever is present,
578 C<cost_in_usd_ticks> first as the finer unit; the integers stay verbatim in
579 L</raw>, so C<< $usage->{cost_in_usd_ticks} >> still gives exact integer
580 accounting. A stream carries it only in its usage frame, which comes when the
581 request asks for it (C<stream_options =E<gt> { include_usage =E<gt> 1 }>).
582  
583 The Perplexity Agent API sends C<usage.cost> as an object that names its
584 currency (C<currency>, C<total_cost>, and the parts such as C<input_cost> and
585 C<tool_calls_cost>); L</from_hash> reads C<total_cost> when C<currency> is
586 C<USD>, and nothing when the currency is another one or the total is missing.
587 OpenRouter sends C<usage.cost> as a bare number in its credits, which are US
588 dollars; a bare number names no unit, so L</from_hash> does not read it on its
589 own. L<Langertha::Engine::OpenRouter> adds it to the usage block as the
590 canonical C<cost_usd> key, which L</from_hash> reads first, so it arrives on
591 the engine's responses and stream chunks, but not through L</from_raw> on an
592 OpenRouter body. For a BYOK request C<cost> is still only what OpenRouter
593 charged your credits; what the key's own provider charged is in
594 C<cost_details.upstream_inference_cost>, which stays in L</raw> and is not
595 added.
596  
597 C<undef> when the provider reports no cost, never C<0>: it is not an estimate,
598 and L<Langertha::Pricing> does not read it — that builds a L<Langertha::Cost>
599 from your own price rules.
600  
601 =head2 uncached_input_tokens
602  
603 my $fresh = $usage->uncached_input_tokens;
604  
605 The input tokens that were neither read from nor written to the prompt cache.
606 When L</input_includes_cache> is false this is C<input_tokens>; otherwise
607 (true or C<undef>) it is C<input_tokens> minus L</cached_tokens> minus
608 L</cache_write_tokens>, never below zero. An C<undef> flag is read as
609 "included" because that is what C<total_tokens> assumes of C<input_tokens>.
610 L<Langertha::Pricing/cost_for> prices this count at the input rate when a rule
611 has a cache rate.
612  
613 =head2 raw
614  
615 The provider-verbatim hash the object was built from, when it was built via
616 L</from_hash>. C<undef> for directly constructed objects. Read-only; the
617 canonical L</to_hash> and C<TO_JSON> deliberately do B<not> include it — it
618 exists solely to back the C<%{}> overload.
619  
620 =head1 SUPPORT
621  
622 =head2 Issues
623  
624 Please report bugs and feature requests on GitHub at
625 L<https://github.com/Getty/langertha/issues>.
626  
627 =head2 IRC
628  
629 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
630  
631 =head1 CONTRIBUTING
632  
633 Contributions are welcome! Please fork the repository and submit a pull request.
634  
635 =head1 AUTHOR
636  
637 Torsten Raudssus <getty@cpan.org>
638  
639 =head1 COPYRIGHT AND LICENSE
640  
641 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
642  
643 This is free software; you can redistribute it and/or modify it under
644 the same terms as the Perl 5 programming language system itself.
645  
646 =cut
« blib/lib/Langertha/Output/Tools.pm ↑ Summary blib/lib/Langertha/Role/Tools.pm »