blib/lib/Langertha/Knarr/PassthroughUsage.pm

filter: Statementstmt 97.5% 78 / 80 Branchbran 88.1% 37 / 42 Conditioncond 70.5% 24 / 34 MC/DCmcdc 50.0% 10 / 20 Subroutinesub 100% 9 / 9 Podpod 100% 4 / 4 totaltotal 85.7% 162 / 189 CC 36 SCAR 22.4
CC
36
Cov
89%
_take
16.4
add_chunk
8.4
_read_line
6.0
CRAP 9.4
« blib/lib/Langertha/Knarr/Image.pm ↑ Summary blib/lib/Langertha/Knarr/Config.pm »
1 package Langertha::Knarr::PassthroughUsage;
2 # ABSTRACT: Token usage and model read off a copy of a raw passthrough answer
3 50 our $VERSION = '1.102';
4 50 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 50 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7  
8 50 has max_line => ( is => 'ro', isa => 'Int', default => 65536 );
9  
10 50 has usage => ( is => 'ro', init_arg => undef, writer => '_set_usage' );
11  
12 50 has model => ( is => 'ro', init_arg => undef, writer => '_set_model' );
13  
14 50 has _json => ( is => 'ro', lazy => 1, builder => '_build__json' );
15 76 ▶sub _build__json { JSON::MaybeXS->new( utf8 => 1 ) }
Subroutine _build__json: called CC=1 SCAR=0.0
16  
17 # The unfinished last line, and whether the line in progress was too long
18 # and is being skipped up to its end.
19 50 has _tail => ( is => 'rw', init_arg => undef, default => '' );
20 50 has _skipping => ( is => 'rw', init_arg => undef, default => 0 );
21  
22 2122 ▶sub add_chunk {
Subroutine add_chunk: called CC=8 SCAR=21.3
Pod documented
23 2122 my ( $self, $data ) = @_;
24 2122 ▶ return unless defined $data && length $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data and length $data 0 2122 2122
Condition33%1/3
defined $data and length $data
!ll&&!rl&&r
002122
MC/DC0%0/2
defined $data and length $data
defined $data length $data
Truth table33%1/3
A and B
A= defined $dataB= length $data
ABresult
0X0
100
111
25 2122 my $buf = $self->_tail . $data;
26 2122 ▶ if ( $self->_skipping ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_skipping) 1 2121 2122
27 1 my $nl = index( $buf, "\n" );
28 1 ▶ if ( $nl < 0 ) { $self->_tail(''); return }
Branch: 1 branch
BranchTrueFalseTotal
if ($nl < 0) 0 1 1
29 1 substr( $buf, 0, $nl + 1, '' );
30 1 $self->_skipping(0);
31 }
32 2122 my $end = rindex( $buf, "\n" );
33 2122 ▶ if ( $end >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($end >= 0) 109 2013 2122
34 109 $self->_read_line($_) for split /\n/, substr( $buf, 0, $end );
35 109 substr( $buf, 0, $end + 1, '' );
36 }
37 2122 ▶ if ( length $buf > $self->max_line ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $buf > $self->max_line) 1 2121 2122
38 1 $self->_tail('');
39 1 $self->_skipping(1);
40 1 return;
41 }
42 2121 $self->_tail($buf);
43 2121 return;
44 }
45  
46  
47 59 ▶sub read_body {
Subroutine read_body: called CC=5 SCAR=16.3
Pod documented
48 59 my ( $self, $body ) = @_;
49 59 ▶ return unless defined $body && length $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body and length $body 0 59 59
Condition33%1/3
defined $body and length $body
!ll&&!rl&&r
0059
MC/DC0%0/2
defined $body and length $body
defined $body length $body
Truth table33%1/3
A and B
A= defined $bodyB= length $body
ABresult
0X0
100
111
50 59 ▶ if ( $body =~ /\A\s*\{/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ /\A\s*\{/) 50 9 59
51 50 my $obj = eval { $self->_json->decode($body) };
52 50 ▶ return $self->_take($obj) if ref $obj eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $obj eq "HASH" 47 3 50
53 }
54 # A buffered stream (PSGI), or NDJSON.
55 12 $self->add_chunk($body);
56 12 $self->finish;
57 12 return;
58 }
59  
60  
61 106 ▶sub finish {
Subroutine finish: called CC=3 SCAR=11.0
Pod documented
62 106 my ( $self ) = @_;
63 106 my $tail = $self->_tail;
64 106 $self->_tail('');
65 106 ▶ $self->_read_line($tail) if length $tail && !$self->_skipping;
Branch: 1 branch
BranchTrueFalseTotal
if length $tail and not $self->_skipping 10 96 106
Condition66%2/3
length $tail and not $self->_skipping
!ll&&!rl&&r
96010
MC/DC50%1/2
length $tail and not $self->_skipping
length $tail not $self->_skipping
Truth table66%2/3
A and not(B)
A= length $tailB= not $self->_skipping
ABresult
0X0
100
111
66 106 $self->_skipping(0);
67 106 return;
68 }
69  
70  
71 94 ▶sub trace_args {
Subroutine trace_args: called CC=3 SCAR=11.0
Pod documented
72 94 my ( $self ) = @_;
73 94 $self->finish;
74 return (
75 94 ▶ defined $self->usage ? ( usage => $self->usage ) : (),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->usage ? : 43 51 94
defined $self->model ? : 40 54 94
76 defined $self->model ? ( model => $self->model ) : (),
77 );
78 }
79  
80  
81 # A line worth decoding carries a usage object or count, or names the
82 # model while none is known yet (OpenAI repeats it in every chunk, and
83 # sends "usage":null in every chunk but the last).
84 209 ▶sub _read_line {
Subroutine _read_line: called CC=6 SCAR=17.9
85 209 my ( $self, $line ) = @_;
86 209 $line =~ s/\r\z//;
87 209 $line =~ s/\Adata:[ \t]*//;
88 209 ▶ return unless $line =~ /\A\s*\{/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\A\s*\{/ 92 117 209
89 117 ▶ return unless $line =~ /"(?:usage"\s*:\s*\{|prompt_eval_count"|eval_count")/
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /"(?:usage"\s*:\s*\{|prompt_eval_count"|eval_count")/ or not defined $self->model and index($line, "\"model\"") != -1 64 53 117
Condition100%6/6
$line =~ /"(?:usage"\s*:\s*\{|prompt_eval_count"|eval_count")/ or not defined $self->model and index($line, "\"model\"") != -1
l!l&&r!l&&!r
351864
not defined $self->model and index($line, "\"model\"") != -1
!ll&&!rl&&r
362818
MC/DC100%3/3
$line =~ /"(?:usage"\s*:\s*\{|prompt_eval_count"|eval_count")/ or not defined $self->model and index($line, "\"model\"") != -1
$line =~ /"(?:usage"\s*:\s*\{|prompt_eval_count"|eval_count")/ not defined $self->model index($line, "\"model\"") != -1
Truth table100%4/4
A or not(B) and C
A= $line =~ /"(?:usage"\s*:\s*\{|prompt_eval_count"|eval_count")/B= not defined $self->modelC= index($line, "\"model\"") != -1
ABCresult
1XX1
0111
00X0
0100
90 || ( !defined $self->model && index( $line, '"model"' ) >= 0 );
91 53 my $obj = eval { $self->_json->decode($line) };
92 53 ▶ $self->_take($obj) if ref $obj eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $obj eq "HASH" 53 0 53
93 53 return;
94 }
95  
96 100 ▶sub _take {
Subroutine _take: called CC=16 SCAR=28.0
97 100 my ( $self, $obj ) = @_;
98 # Anthropic's message_start carries the message, model and usage inside.
99 100 ▶ my $msg = ref $obj->{message} eq 'HASH' ? $obj->{message} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $obj->{'message'} eq 'HASH' ? : 29 71 100
100 100 ▶ my $model = $obj->{model} // $msg->{model};
Condition100%3/3
$obj->{"model"} // $msg->{"model"}
l!l&&r!l&&!r
50842
MC/DC100%2/2
$obj->{"model"} // $msg->{"model"}
$obj->{"model"} $msg->{"model"}
Truth table100%3/3
A // B
A= $obj->{"model"}B= $msg->{"model"}
ABresult
1X1
011
000
101 100 ▶ $self->_set_model($model) if defined $model && !ref $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
if defined $model and not ref $model and length $model 58 42 100
Condition66%4/6
defined $model and not ref $model and length $model
!ll&&!rl&&r
42058
defined $model and not ref $model
!ll&&!rl&&r
42058
MC/DC33%1/3
defined $model and not ref $model and length $model
defined $model not ref $model length $model
Truth table50%2/4
A and not(B) and C
A= defined $modelB= not ref $modelC= length $model
ABCresult
0XX0
10X0
1100
1111
102  
103 100 ▶ my $type = $obj->{type} // '';
Condition100%2/2
$obj->{"type"} // ""
l!l
4456
MC/DC100%1/1
$obj->{"type"} // ""
$obj->{"type"}
Truth table100%2/2
A
A= $obj->{"type"}
Aresult
11
00
104 100 ▶ if ( $type eq 'message_delta' && ref $obj->{usage} eq 'HASH' ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'message_delta' and ref $obj->{'usage'} eq 'HASH') { } 8 92 100
elsif (ref $obj->{'usage'} eq 'HASH') { } 25 67 92
elsif (ref $msg->{'usage'} eq 'HASH') { } 8 59 67
elsif (defined $obj->{'prompt_eval_count'} or defined $obj->{'eval_count'}) { } 11 48 59
Condition66%2/3
$type eq "message_delta" and ref $obj->{"usage"} eq "HASH"
!ll&&!rl&&r
9208
MC/DC50%1/2
$type eq "message_delta" and ref $obj->{"usage"} eq "HASH"
$type eq "message_delta" ref $obj->{"usage"} eq "HASH"
Truth table66%2/3
A and B
A= $type eq "message_delta"B= ref $obj->{"usage"} eq "HASH"
ABresult
0X0
100
111
105 8 ▶ my %merged = %{ $self->usage // {} };
Condition50%1/2
$self->usage // {}
l!l
80
MC/DC0%0/1
$self->usage // {}
$self->usage
Truth table50%1/2
A
A= $self->usage
Aresult
11
00
106 8 my $delta = $obj->{usage};
107 8 $merged{$_} = $delta->{$_} for grep { defined $delta->{$_} } keys %$delta;
108 8 $self->_set_usage( \%merged );
109 }
110 elsif ( ref $obj->{usage} eq 'HASH' ) {
111 25 $self->_set_usage( $obj->{usage} );
112 }
113 elsif ( ref $msg->{usage} eq 'HASH' ) {
114 8 $self->_set_usage( $msg->{usage} );
115 }
116 ▶ elsif ( defined $obj->{prompt_eval_count} || defined $obj->{eval_count} ) {
Condition66%2/3
defined $obj->{"prompt_eval_count"} or defined $obj->{"eval_count"}
l!l&&r!l&&!r
11048
MC/DC50%1/2
defined $obj->{"prompt_eval_count"} or defined $obj->{"eval_count"}
defined $obj->{"prompt_eval_count"} defined $obj->{"eval_count"}
Truth table66%2/3
A or B
A= defined $obj->{"prompt_eval_count"}B= defined $obj->{"eval_count"}
ABresult
1X1
011
000
117 11 ▶ $self->_set_usage({ map { defined $obj->{$_} ? ( $_ => $obj->{$_} ) : () }
Branch: 1 branch
BranchTrueFalseTotal
defined $obj->{$_} ? : 22 0 22
118 qw( prompt_eval_count eval_count ) });
119 }
120 100 return;
121 }
122  
123 50 __PACKAGE__->meta->make_immutable;
124 50 1;
125  
126 __END__
127  
128 =pod
129  
130 =encoding UTF-8
131  
132 =head1 NAME
133  
134 Langertha::Knarr::PassthroughUsage - Token usage and model read off a copy of a raw passthrough answer
135  
136 =head1 VERSION
137  
138 version 1.102
139  
140 =head1 SYNOPSIS
141  
142 my $reader = Langertha::Knarr::PassthroughUsage->new;
143  
144 # A stream, chunk by chunk, as the bytes go to the client
145 $reader->add_chunk($_) for @chunks;
146  
147 # or a buffered answer at once
148 $reader->read_body($body);
149  
150 $tracing->end_trace( $trace, output => '[stream]', $reader->trace_args );
151  
152 =head1 DESCRIPTION
153  
154 The raw passthrough (L<Langertha::Knarr/raw_passthrough>) pipes the
155 upstream's bytes to the client untouched. For its Langfuse trace, this
156 reader looks at a copy of those bytes and keeps the token usage and the
157 model the upstream reported -- it never changes, holds back or re-frames
158 what the client gets.
159  
160 It reads what the three passthrough upstreams send, by the shape of each
161 JSON object, buffered or streamed:
162  
163 =over
164  
165 =item * OpenAI: C<model> and C<usage> of a completion; in a stream the
166 chunk carrying C<usage> (sent with C<stream_options.include_usage>).
167  
168 =item * Anthropic: C<model> and C<usage> of a message; in a stream the
169 C<usage> of C<message_start>, with the counts of every C<message_delta>
170 laid over it.
171  
172 =item * Ollama: C<model>, C<prompt_eval_count> and C<eval_count> of an
173 answer; in a stream those of the C<done> frame.
174  
175 =back
176  
177 The usage is kept in the provider's own keys, which
178 L<Langertha::Knarr::Tracing/end_trace> maps. A stream is read line by line
179 (SSE C<data:> lines, NDJSON lines), a line split across chunks included;
180 only the unfinished last line is held, at most L</max_line> bytes of it,
181 and only lines that can carry usage or a still unknown model are decoded.
182 Anything that does not parse is skipped.
183  
184 =head2 max_line
185  
186 Bytes of an unfinished line held between chunks. Default C<65536>; a longer
187 line is dropped whole -- a usage frame is far shorter.
188  
189 =head2 usage
190  
191 The provider's usage hash seen last (merged for Anthropic), or C<undef>.
192  
193 =head2 model
194  
195 The model the upstream named last, or C<undef>.
196  
197 =head2 add_chunk
198  
199 $reader->add_chunk($bytes);
200  
201 Reads the next piece of a stream. Returns nothing.
202  
203 =head2 read_body
204  
205 $reader->read_body($bytes);
206  
207 Reads a whole buffered answer: one JSON object, or a buffered stream.
208  
209 =head2 finish
210  
211 $reader->finish;
212  
213 Reads a last line the stream did not end with a newline. L</trace_args>
214 calls it.
215  
216 =head2 trace_args
217  
218 $tracing->end_trace( $trace, output => '[stream]', $reader->trace_args );
219  
220 C<usage> and C<model> as far as the answer had them, for
221 L<Langertha::Knarr::Tracing/end_trace>.
222  
223 =head1 SUPPORT
224  
225 =head2 Issues
226  
227 Please report bugs and feature requests on GitHub at
228 L<https://github.com/Getty/langertha-knarr/issues>.
229  
230 =head2 IRC
231  
232 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
233  
234 =head1 CONTRIBUTING
235  
236 Contributions are welcome! Please fork the repository and submit a pull request.
237  
238 =head1 AUTHOR
239  
240 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
241  
242 =head1 COPYRIGHT AND LICENSE
243  
244 This software is copyright (c) 2026 by Torsten Raudssus.
245  
246 This is free software; you can redistribute it and/or modify it under
247 the same terms as the Perl 5 programming language system itself.
248  
249 =cut
« blib/lib/Langertha/Knarr/Image.pm ↑ Summary blib/lib/Langertha/Knarr/Config.pm »