blib/lib/Langertha/Knarr/Tracing.pm

filter: Statementstmt 88.3% 242 / 274 Branchbran 62.1% 92 / 148 Conditioncond 40.5% 30 / 74 MC/DCmcdc 9.0% 4 / 44 Subroutinesub 95.6% 44 / 46 Podpod 75.0% 3 / 4 totaltotal 70.3% 415 / 590 CC 107 SCAR 27.3
CC
107
Cov
73%
_input_buckets
85.8
end_trace
27.0
_tool_calls_full
22.5
CRAP 15.4
« blib/lib/Langertha/Knarr/Protocol/OpenAI.pm ↑ Summary blib/lib/Langertha/Knarr/CLI/Cmd/Models.pm »
1 package Langertha::Knarr::Tracing;
2 8 our $VERSION = '1.103';
3 # ABSTRACT: Automatic Langfuse tracing per proxy request
4 8 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use Time::HiRes qw( gettimeofday );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 8 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use Scalar::Util qw( blessed looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 8 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 8 ▶use HTTP::Request ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 8 ▶use Net::Async::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 8 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17  
18 8 has config => (
19 is => 'ro',
20 required => 1,
21 );
22  
23  
24 8 has _enabled => (
25 is => 'lazy',
26 builder => '_build__enabled',
27 );
28  
29 11 ▶sub _build__enabled {
Subroutine _build__enabled: called CC=5 SCAR=19.6
30 11 my ($self) = @_;
31 11 my $lf = $self->config->langfuse;
32 11 ▶ my $pub = $lf->{public_key} // _strip_quotes($ENV{LANGFUSE_PUBLIC_KEY});
Condition33%1/3
$lf->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
l!l&&r!l&&!r
1100
MC/DC0%0/2
$lf->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
$lf->{"public_key"} _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
Truth table33%1/3
A // B
A= $lf->{"public_key"}B= _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
ABresult
1X1
011
000
33 11 ▶ my $sec = $lf->{secret_key} // _strip_quotes($ENV{LANGFUSE_SECRET_KEY});
Condition33%1/3
$lf->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
l!l&&r!l&&!r
1100
MC/DC0%0/2
$lf->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
$lf->{"secret_key"} _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
Truth table33%1/3
A // B
A= $lf->{"secret_key"}B= _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
ABresult
1X1
011
000
34 11 ▶ return ($pub && $sec) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$pub && $sec ? : 11 0 11
Condition33%1/3
$pub and $sec
!ll&&!rl&&r
0011
MC/DC0%0/2
$pub and $sec
$pub $sec
Truth table33%1/3
A and B
A= $pubB= $sec
ABresult
0X0
100
111
35 }
36  
37 8 has _public_key => (
38 is => 'lazy',
39 builder => '_build__public_key',
40 );
41  
42 8 ▶sub _build__public_key {
Subroutine _build__public_key: called CC=2 SCAR=8.1
43 8 my ($self) = @_;
44 8 ▶ return $self->config->langfuse->{public_key} // _strip_quotes($ENV{LANGFUSE_PUBLIC_KEY});
Condition33%1/3
$self->config->langfuse->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
l!l&&r!l&&!r
800
MC/DC0%0/2
$self->config->langfuse->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
$self->config->langfuse->{"public_key"} _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
Truth table33%1/3
A // B
A= $self->config->langfuse->{"public_key"}B= _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
ABresult
1X1
011
000
45 }
46  
47 8 has _secret_key => (
48 is => 'lazy',
49 builder => '_build__secret_key',
50 );
51  
52 8 ▶sub _build__secret_key {
Subroutine _build__secret_key: called CC=2 SCAR=8.1
53 8 my ($self) = @_;
54 8 ▶ return $self->config->langfuse->{secret_key} // _strip_quotes($ENV{LANGFUSE_SECRET_KEY});
Condition33%1/3
$self->config->langfuse->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
l!l&&r!l&&!r
800
MC/DC0%0/2
$self->config->langfuse->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
$self->config->langfuse->{"secret_key"} _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
Truth table33%1/3
A // B
A= $self->config->langfuse->{"secret_key"}B= _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
ABresult
1X1
011
000
55 }
56  
57 8 has _url => (
58 is => 'lazy',
59 builder => '_build__url',
60 );
61  
62 8 has trace_name => (
63 is => 'lazy',
64 builder => '_build_trace_name',
65 );
66  
67  
68 11 ▶sub _build_trace_name {
Subroutine _build_trace_name: called CC=4 SCAR=17.9
69 11 my ($self) = @_;
70 return $self->config->langfuse->{trace_name}
71 // _strip_quotes($ENV{LANGFUSE_TRACE_NAME})
72 // _strip_quotes($ENV{KNARR_TRACE_NAME})
73 11 ▶ // 'knarr-proxy';
Condition37%3/8
(($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})) // "knarr-proxy"
l!l
011
($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})
l!l&&r!l&&!r
0011
$self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})
l!l&&r!l&&!r
0011
MC/DC0%0/3
(($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})) // "knarr-proxy"
$self->config->langfuse->{"trace_name"} _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"}) _strip_quotes($ENV{"KNARR_TRACE_NAME"})
Truth table25%1/4
A // B // C
A= $self->config->langfuse->{"trace_name"}B= _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})C= _strip_quotes($ENV{"KNARR_TRACE_NAME"})
ABCresult
1XX1
01X1
0011
0000
74 }
75  
76 8 has transport => (
77 is => 'lazy',
78 builder => '_build_transport',
79 );
80  
81  
82 11 ▶sub _build_transport {
Subroutine _build_transport: called CC=1 SCAR=0.0
83 11 my ($self) = @_;
84 11 return $self->config->langfuse_transport;
85 }
86  
87 11 ▶sub BUILD {
Subroutine BUILD: called CC=2 SCAR=7.0
Pod undocumented
88 11 my ($self) = @_;
89 11 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 11 11
90 11 $self->transport;
91 11 $self->config->langfuse_timeout;
92 }
93  
94 8 ▶sub _build__url {
Subroutine _build__url: called CC=4 SCAR=17.9
95 8 my ($self) = @_;
96 8 ▶ return $self->config->langfuse->{url} // _strip_quotes($ENV{LANGFUSE_URL}) // _strip_quotes($ENV{LANGFUSE_BASE_URL}) // 'https://cloud.langfuse.com';
Condition37%3/8
(($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})) // "https://cloud.langfuse.com"
l!l
80
($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})
l!l&&r!l&&!r
800
$self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})
l!l&&r!l&&!r
800
MC/DC0%0/3
(($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})) // "https://cloud.langfuse.com"
$self->config->langfuse->{"url"} _strip_quotes($ENV{"LANGFUSE_URL"}) _strip_quotes($ENV{"LANGFUSE_BASE_URL"})
Truth table25%1/4
A // B // C
A= $self->config->langfuse->{"url"}B= _strip_quotes($ENV{"LANGFUSE_URL"})C= _strip_quotes($ENV{"LANGFUSE_BASE_URL"})
ABCresult
1XX1
01X1
0011
0000
97 }
98  
99 has _batch => (
100 is => 'rw',
101 11 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
102 8 );
103  
104 8 has _json => (
105 is => 'lazy',
106 builder => '_build__json',
107 );
108  
109 # Strip surrounding quotes from env values (Docker --env-file includes them literally)
110 22 ▶sub _strip_quotes {
Subroutine _strip_quotes: called CC=2 SCAR=9.2
111 22 my $v = shift;
112 22 ▶ return $v unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 22 0 22
113 0 $v =~ s/^["']|["']$//g;
114 0 return $v;
115 }
116  
117 8 ▶sub _build__json {
Subroutine _build__json: called CC=1 SCAR=0.0
118 8 return JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1);
119 }
120  
121 # Encodes structured values into OTLP string attributes. Character output:
122 # the attribute ends up inside the payload _json encodes to UTF-8 bytes.
123 8 has _attr_json => (
124 is => 'lazy',
125 builder => '_build__attr_json',
126 );
127  
128 1 ▶sub _build__attr_json {
Subroutine _build__attr_json: called CC=1 SCAR=0.0
129 1 return JSON::MaybeXS->new( utf8 => 0, canonical => 1, convert_blessed => 1, allow_nonref => 1 );
130 }
131  
132 # A random OTel id of $bytes bytes as lowercase hex (OTLP/JSON sends ids as
133 # hex, not base64). All zeros is the invalid id, so it is never returned.
134 3 ▶sub _hex_id {
Subroutine _hex_id: called CC=2 SCAR=7.0
135 3 my ($bytes) = @_;
136 3 my $id;
137 3 ▶ do { $id = join '', map { sprintf '%02x', int rand 256 } 1 .. $bytes } until $id =~ /[^0]/;
Branch: 1 branch
BranchTrueFalseTotal
$id =~ /[^0]/ or do { do { $id = join("", map({sprintf "%02x", int rand 256;} 1 .. $bytes)) } } 3 0 3
138 3 return $id;
139 }
140  
141 # A gettimeofday pair as OTLP's Unix nanoseconds, a decimal string.
142 3 ▶sub _unix_nano {
Subroutine _unix_nano: called CC=1 SCAR=0.0
143 3 my ($s, $us) = @_;
144 3 return sprintf '%d%06d000', $s, $us;
145 }
146  
147 64 ▶sub _uuid {
Subroutine _uuid: called CC=1 SCAR=0.0
148 64 my @hex = map { sprintf("%04x", int(rand(65536))) } 1..8;
149 64 return join('-',
150 $hex[0].$hex[1],
151 $hex[2],
152 '4'.substr($hex[3], 1),
153 sprintf("%x", 8 + int(rand(4))).substr($hex[4], 1),
154 $hex[5].$hex[6].$hex[7],
155 );
156 }
157  
158 33 ▶sub _timestamp {
Subroutine _timestamp: called CC=2 SCAR=7.1
159 33 ▶ my ($s, $us) = @_ ? @_ : gettimeofday;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 33 0 33
160 33 my @t = gmtime($s);
161 33 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
162 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
163 }
164  
165 # The instant $start_hires + $delta_seconds, as a gettimeofday pair that
166 # either transport formats. Turns the deltas an engine measured
167 # (ttft_seconds / total_seconds on Langertha::Response) into absolute
168 # Langfuse timestamps anchored to the moment start_trace ran — not to "now",
169 # which has already moved past the end of the call.
170 2 ▶sub _after {
Subroutine _after: called CC=4 SCAR=15.0
171 2 my ($start_hires, $delta_seconds) = @_;
172 2 ▶ return undef unless ref $start_hires eq 'ARRAY' && defined $delta_seconds;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $start_hires eq "ARRAY" and defined $delta_seconds 0 2 2
Condition33%1/3
ref $start_hires eq "ARRAY" and defined $delta_seconds
!ll&&!rl&&r
002
MC/DC0%0/2
ref $start_hires eq "ARRAY" and defined $delta_seconds
ref $start_hires eq "ARRAY" defined $delta_seconds
Truth table33%1/3
A and B
A= ref $start_hires eq "ARRAY"B= defined $delta_seconds
ABresult
0X0
100
111
173 # Clamp: a negative delta (clock skew, or a provider-reported duration we
174 # did not produce) would otherwise report a trip into the past.
175 2 ▶ $delta_seconds = 0 if $delta_seconds < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $delta_seconds < 0 0 2 2
176 2 my ($s, $us) = @$start_hires;
177 2 my $sum = $us + $delta_seconds * 1_000_000;
178 2 return [ $s + int( $sum / 1_000_000 ), int($sum) % 1_000_000 ];
179 }
180  
181 # Flatten a Langertha::RateLimit (or an equivalent hashref) into plain
182 # scalars for the trace metadata. Only the quota fields — the object's raw
183 # header hash is deliberately left out so response headers never leak into
184 # Langfuse, and so the payload stays JSON-encodable without convert_blessed.
185 8 my @RATE_LIMIT_FIELDS = qw(
186 requests_limit requests_remaining requests_reset
187 tokens_limit tokens_remaining tokens_reset
188 );
189  
190 10 ▶sub _rate_limit_hash {
Subroutine _rate_limit_hash: called CC=10 SCAR=26.9
191 10 my ($rl) = @_;
192 10 ▶ return undef unless defined $rl;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rl 9 1 10
193 1 my %out;
194 1 ▶ if ( blessed $rl ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($rl)) { } 1 0 1
elsif (ref $rl eq 'HASH') { } 0 0 0
195 1 for my $f (@RATE_LIMIT_FIELDS) {
196 6 ▶ next unless $rl->can($f);
Branch: 1 branch
BranchTrueFalseTotal
unless $rl->can($f) 0 6 6
197 6 my $v = $rl->$f;
198 6 ▶ $out{$f} = $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 2 4 6
199 }
200 }
201 elsif ( ref $rl eq 'HASH' ) {
202 0 for my $f (@RATE_LIMIT_FIELDS) {
203 0 ▶ $out{$f} = $rl->{$f} if defined $rl->{$f};
Branch: 1 branch
BranchTrueFalseTotal
if defined $rl->{$f} 0 0 0
204 }
205 }
206 1 ▶ return %out ? \%out : undef;
Branch: 1 branch
BranchTrueFalseTotal
%out ? : 1 0 1
207 }
208  
209 # Langfuse's usage details are exclusive buckets, each priced on its own:
210 # input is the uncached input, prompt-cache reads and writes have their own
211 # keys (the names Langfuse's own normalizer and model prices use), and total
212 # is the sum of all of them (k65).
213 8 my @CACHE_BUCKETS = qw( input_cached_tokens input_cache_creation );
214  
215 # Token counts in the keys Langfuse stores: { input, output, total } plus
216 # the cache buckets that are not zero. Langertha::Usage's canonical
217 # input_tokens / output_tokens / total_tokens are keys Langfuse's ingestion
218 # silently drops, leaving the generation at 0 / 0 / 0 (k57). Takes a
219 # Langertha::Usage, a hashref already in Langfuse's keys (the shape
220 # end_trace's SYNOPSIS documents), or a provider's own usage hash (OpenAI,
221 # Anthropic, Ollama), which Langertha::Usage reads. Anything else, an empty
222 # hash, or one that counts nothing, is no usage at all -- never a zeroed one.
223 15 ▶sub _usage_hash {
Subroutine _usage_hash: called CC=6 SCAR=19.0
224 15 my ($u) = @_;
225 15 ▶ return undef unless defined $u;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $u 8 7 15
226 7 ▶ if ( ref $u eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $u eq "HASH") 1 6 7
227 return _langfuse_counts( $u, $u->{total} )
228 1 ▶ if grep { defined $u->{$_} } qw( input output total );
Branch: 1 branch
BranchTrueFalseTotal
if grep {defined $u->{$_};} "input", "output", "total" 1 0 1
229 0 $u = Langertha::Usage->from_hash($u);
230 }
231 6 ▶ return undef unless blessed($u) && $u->can('input_tokens');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($u) and $u->can("input_tokens") 0 6 6
Condition33%1/3
builtin::blessed($u) and $u->can("input_tokens")
!ll&&!rl&&r
006
MC/DC0%0/2
builtin::blessed($u) and $u->can("input_tokens")
builtin::blessed($u) $u->can("input_tokens")
Truth table33%1/3
A and B
A= builtin::blessed($u)B= $u->can("input_tokens")
ABresult
0X0
100
111
232 6 return _langfuse_counts( { _input_buckets($u), output => $u->output_tokens } );
233 }
234  
235 # The input of a Langertha::Usage split into Langfuse's buckets. A core
236 # that knows the cache counts says how they relate to input_tokens; older
237 # ones (0.503) keep only the provider's hash, read here for the two wires
238 # that carry cache counts: OpenAI counts cached_tokens (and
239 # cache_write_tokens) inside prompt_tokens, Anthropic counts
240 # cache_read_input_tokens and cache_creation_input_tokens beside
241 # input_tokens.
242 6 ▶sub _input_buckets {
Subroutine _input_buckets: called CC=10 SCAR=44.5
243 6 my ($u) = @_;
244 return (
245 6 ▶ input => $u->uncached_input_tokens,
Branch: 1 branch
BranchTrueFalseTotal
if $u->can("uncached_input_tokens") 6 0 6
246 input_cached_tokens => $u->cached_tokens,
247 input_cache_creation => $u->cache_write_tokens,
248 ) if $u->can('uncached_input_tokens');
249 0 my $input = $u->input_tokens;
250 0 ▶ my $raw = $u->can('raw') ? $u->raw : undef;
Branch: 1 branch
BranchTrueFalseTotal
$u->can('raw') ? : 0 0 0
251 0 ▶ return ( input => $input ) unless ref $raw eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw eq "HASH" 0 0 0
252 0 ▶ my $ptd = ref $raw->{prompt_tokens_details} eq 'HASH' ? $raw->{prompt_tokens_details} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $raw->{'prompt_tokens_details'} eq 'HASH' ? : 0 0 0
253 0 ▶ my $inside = $ptd && grep { defined $ptd->{$_} } qw( cached_tokens cache_write_tokens );
Condition0%0/3
$ptd && grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
!ll&&!rl&&r
000
MC/DC0%0/2
$ptd && grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
$ptd grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
Truth table0%0/3
A && B
A= $ptdB= grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
ABresult
0X0
100
111
254 # Copied out first: map aliases its list, which would add the missing
255 # keys to the provider's hash.
256 my @counts = $inside
257 ? ( $ptd->{cached_tokens}, $ptd->{cache_write_tokens} )
258 0 ▶ : ( $raw->{cache_read_input_tokens}, $raw->{cache_creation_input_tokens} );
Branch: 1 branch
BranchTrueFalseTotal
$inside ? : 0 0 0
259 0 ▶ my ( $read, $write ) = map { looks_like_number($_) ? int($_) : 0 } @counts;
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($_) ? : 0 0 0
260 0 ▶ if ($inside) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inside) 0 0 0
261 0 $input -= $read + $write;
262 0 ▶ $input = 0 if $input < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $input < 0 0 0 0
263 }
264 0 return ( input => $input, input_cached_tokens => $read, input_cache_creation => $write );
265 }
266  
267 # Langfuse validates the counts as integers: a count that arrived as a
268 # string would be encoded as a JSON string and the whole event rejected.
269 # A missing total is the sum of the buckets; a usage that counts nothing
270 # is none.
271 7 ▶sub _langfuse_counts {
Subroutine _langfuse_counts: called CC=7 SCAR=19.5
272 7 my ( $counts, $total ) = @_;
273 7 ▶ my %out = map { $_ => looks_like_number( $counts->{$_} ) ? int( $counts->{$_} ) : 0 }
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($counts->{$_}) ? : 17 11 28
274 qw( input output ), @CACHE_BUCKETS;
275 7 my $sum = 0;
276 7 $sum += $_ for values %out;
277 7 delete $out{$_} for grep { !$out{$_} } @CACHE_BUCKETS;
278 7 ▶ $out{total} = looks_like_number($total) ? int($total) : $sum;
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($total) ? : 1 6 7
279 7 ▶ return ( $sum || $out{total} ) ? \%out : undef;
Branch: 1 branch
BranchTrueFalseTotal
$sum || $out{'total'} ? : 6 1 7
Condition66%2/3
$sum or $out{"total"}
l!l&&r!l&&!r
601
MC/DC50%1/2
$sum or $out{"total"}
$sum $out{"total"}
Truth table66%2/3
A or B
A= $sumB= $out{"total"}
ABresult
1X1
011
000
280 }
281  
282 # Langfuse v2's usage has no cache buckets: its input is the whole input.
283 2 ▶sub _legacy_usage {
Subroutine _legacy_usage: called CC=3 SCAR=11.0
284 2 my ($usage) = @_;
285 2 my $input = 0;
286 2 ▶ $input += $usage->{$_} // 0 for 'input', @CACHE_BUCKETS;
Condition100%2/2
$usage->{$_} // 0
l!l
24
MC/DC100%1/1
$usage->{$_} // 0
$usage->{$_}
Truth table100%2/2
A
A= $usage->{$_}
Aresult
11
00
287 2 return { input => $input, output => $usage->{output}, total => $usage->{total}, unit => 'TOKENS' };
288 }
289  
290 # Flatten the response's tool calls into plain hashes for the trace metadata.
291 # The trace is the detailed view, so it records the full
292 # { id, name, arguments, synthetic } shape -- the whole point of putting tool
293 # calls in a trace is seeing which tool ran with which arguments. Langertha
294 # 0.503's ToolCall carries a TO_JSON (so it would survive flush's
295 # convert_blessed encode either way), but flattening here keeps the metadata a
296 # plain structure like usage and rate_limit.
297 10 ▶sub _tool_calls_full {
Subroutine _tool_calls_full: called CC=10 SCAR=31.1
298 10 my ($tcs) = @_;
299 10 ▶ return undef unless ref $tcs eq 'ARRAY' && @$tcs;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tcs eq "ARRAY" and @$tcs 9 1 10
Condition66%2/3
ref $tcs eq "ARRAY" and @$tcs
!ll&&!rl&&r
901
MC/DC50%1/2
ref $tcs eq "ARRAY" and @$tcs
ref $tcs eq "ARRAY" @$tcs
Truth table66%2/3
A and B
A= ref $tcs eq "ARRAY"B= @$tcs
ABresult
0X0
100
111
300 1 my @out;
301 1 for my $tc (@$tcs) {
302 2 ▶ if ( blessed($tc) && $tc->can('to_hash') ) { push @out, $tc->to_hash }
Branch: 3 branches
BranchTrueFalseTotal
if (builtin::blessed($tc) and $tc->can('to_hash')) { } 2 0 2
elsif (builtin::blessed($tc) and $tc->can('TO_JSON')) { } 0 0 0
elsif (ref $tc eq 'HASH') { } 0 0 0
Condition33%1/3
builtin::blessed($tc) and $tc->can("to_hash")
!ll&&!rl&&r
002
MC/DC0%0/2
builtin::blessed($tc) and $tc->can("to_hash")
builtin::blessed($tc) $tc->can("to_hash")
Truth table33%1/3
A and B
A= builtin::blessed($tc)B= $tc->can("to_hash")
ABresult
0X0
100
111
303 0 ▶ elsif ( blessed($tc) && $tc->can('TO_JSON') ) { push @out, $tc->TO_JSON }
Condition0%0/3
builtin::blessed($tc) and $tc->can("TO_JSON")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($tc) and $tc->can("TO_JSON")
builtin::blessed($tc) $tc->can("TO_JSON")
Truth table0%0/3
A and B
A= builtin::blessed($tc)B= $tc->can("TO_JSON")
ABresult
0X0
100
111
304 0 elsif ( ref $tc eq 'HASH' ) { push @out, $tc }
305 }
306 1 ▶ return @out ? \@out : undef;
Branch: 1 branch
BranchTrueFalseTotal
@out ? : 1 0 1
307 }
308  
309  
310 12 ▶sub start_trace {
Subroutine start_trace: called CC=5 SCAR=16.4
Pod documented
311 12 my ($self, %opts) = @_;
312 12 ▶ return undef unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 12 12
313  
314 0 ▶ my @hires = $opts{start_hires} ? @{ $opts{start_hires} } : gettimeofday;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'start_hires'} ? : 0 12 12
315 12 my $now = _timestamp(@hires);
316 # Image objects (k33) carry no TO_JSON and would fail the batch encode.
317 12 my $input = Langertha::Knarr::Image::plain_messages( $opts{messages} );
318  
319 # OTel spans are exported once, finished: nothing is sent yet, end_trace
320 # builds both spans from what is kept here.
321 return {
322 trace_id => _hex_id(16),
323 root_id => _hex_id(8),
324 gen_id => _hex_id(8),
325 start_time => $now,
326 start_hires => \@hires,
327 otel => {
328 name => $self->trace_name,
329 model => $opts{model},
330 input => $input,
331 metadata => {
332 format => $opts{format},
333 engine => $opts{engine},
334 model => $opts{model},
335 params => $opts{params},
336 # Left out when undef, like every other attribute.
337 passthrough_fallback => $opts{passthrough_fallback},
338 },
339 },
340 12 ▶ } if $self->transport eq 'otel';
Branch: 1 branch
BranchTrueFalseTotal
if $self->transport eq "otel" 1 11 12
341  
342 11 my $trace_id = _uuid();
343 11 my $gen_id = _uuid();
344  
345 11 ▶ push @{$self->_batch}, {
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'passthrough_fallback'} ? : 0 11 11
346 id => _uuid(),
347 type => 'trace-create',
348 timestamp => $now,
349 body => {
350 id => $trace_id,
351 name => $self->trace_name,
352 input => $input,
353 metadata => {
354 format => $opts{format},
355 engine => $opts{engine},
356 model => $opts{model},
357 params => $opts{params},
358 defined $opts{passthrough_fallback}
359 11 ? ( passthrough_fallback => $opts{passthrough_fallback} ) : (),
360 },
361 tags => ['knarr'],
362 },
363 };
364  
365 11 push @{$self->_batch}, {
366 id => _uuid(),
367 type => 'generation-create',
368 timestamp => $now,
369 body => {
370 id => $gen_id,
371 traceId => $trace_id,
372 name => 'proxy-request',
373 model => $opts{model},
374 11 input => $input,
375 startTime => $now,
376 },
377 };
378  
379 return {
380 11 trace_id => $trace_id,
381 gen_id => $gen_id,
382 start_time => $now,
383 start_hires => \@hires,
384 };
385 }
386  
387  
388 11 ▶sub end_trace {
Subroutine end_trace: called CC=25 SCAR=33.0
Pod documented
389 11 my ($self, $trace_info, %opts) = @_;
390 11 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 11 11
391 11 ▶ return unless $trace_info;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace_info 0 11 11
392  
393 11 my @now = gettimeofday;
394 11 my $now = _timestamp(@now);
395 11 my $otel = $self->transport eq 'otel';
396  
397 11 ▶ if ( $opts{error} && $otel ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($opts{'error'} and $otel) { } 0 11 11
elsif ($opts{'error'}) { } 1 10 11
Condition66%2/3
$opts{"error"} and $otel
!ll&&!rl&&r
1010
MC/DC0%0/2
$opts{"error"} and $otel
$opts{"error"} $otel
Truth table66%2/3
A and B
A= $opts{"error"}B= $otel
ABresult
0X0
100
111
398 0 push @{$self->_batch}, {
399 info => $trace_info,
400 now => \@now,
401 end => \@now,
402 output => $opts{output},
403 0 error => "$opts{error}",
404 };
405 } elsif ($opts{error}) {
406 1 push @{$self->_batch}, {
407 id => _uuid(),
408 type => 'generation-update',
409 timestamp => $now,
410 body => {
411 id => $trace_info->{gen_id},
412 endTime => $now,
413 level => 'ERROR',
414 statusMessage => $opts{error},
415 },
416 1 };
417 } else {
418 10 ▶ my $timing = ( ref $opts{timing} eq 'HASH' ) ? $opts{timing} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $opts{'timing'} eq 'HASH' ? : 1 9 10
419  
420 # Engine-measured deltas win over the proxy's wall clock: they are
421 # anchored to the same instant as start_time and exclude our own
422 # dispatch/formatting overhead. Without them endTime stays "now".
423 10 my $end_at = \@now;
424 10 my $completion_at = undef;
425 10 ▶ if ( $timing ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timing) 1 9 10
426 1 my $hires = $trace_info->{start_hires};
427 $end_at = _after( $hires, $timing->{total_seconds} ) // $end_at
428 1 ▶ if defined $timing->{total_seconds};
Branch: 1 branch
BranchTrueFalseTotal
if defined $timing->{"total_seconds"} 1 0 1
Condition33%1/3
_after($hires, $timing->{"total_seconds"}) // $end_at
l!l&&r!l&&!r
100
MC/DC0%0/2
_after($hires, $timing->{"total_seconds"}) // $end_at
_after($hires, $timing->{"total_seconds"}) $end_at
Truth table33%1/3
A // B
A= _after($hires, $timing->{"total_seconds"})B= $end_at
ABresult
1X1
011
000
429 $completion_at = _after( $hires, $timing->{ttft_seconds} )
430 1 ▶ if defined $timing->{ttft_seconds};
Branch: 1 branch
BranchTrueFalseTotal
if defined $timing->{"ttft_seconds"} 1 0 1
431 }
432  
433 10 my $usage = _usage_hash( $opts{usage} );
434  
435 10 my %metadata;
436 10 ▶ $metadata{timing} = $timing if $timing;
Branch: 1 branch
BranchTrueFalseTotal
if $timing 1 9 10
437 10 ▶ $metadata{response_id} = $opts{response_id} if defined $opts{response_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"response_id"} 1 9 10
438 10 ▶ $metadata{configured_model} = $opts{configured_model} if defined $opts{configured_model};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"configured_model"} 0 10 10
439 $metadata{thinking} = $opts{thinking}
440 10 ▶ if defined $opts{thinking} && length $opts{thinking};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"thinking"} and length $opts{"thinking"} 1 9 10
Condition66%2/3
defined $opts{"thinking"} and length $opts{"thinking"}
!ll&&!rl&&r
901
MC/DC50%1/2
defined $opts{"thinking"} and length $opts{"thinking"}
defined $opts{"thinking"} length $opts{"thinking"}
Truth table66%2/3
A and B
A= defined $opts{"thinking"}B= length $opts{"thinking"}
ABresult
0X0
100
111
441 10 ▶ if ( my $rl = _rate_limit_hash( $opts{rate_limit} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rl = _rate_limit_hash($opts{"rate_limit"})) 1 9 10
442 1 $metadata{rate_limit} = $rl;
443 }
444 10 ▶ if ( my $tcs = _tool_calls_full( $opts{tool_calls} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tcs = _tool_calls_full($opts{"tool_calls"})) 1 9 10
445 1 $metadata{tool_calls} = $tcs;
446 }
447  
448 10 ▶ if ($otel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($otel) { } 1 9 10
449 1 push @{$self->_batch}, {
450 info => $trace_info,
451 now => \@now,
452 end => $end_at,
453 completion_start => $completion_at,
454 output => $opts{output},
455 model => $opts{model},
456 1 usage => $usage,
457 metadata => \%metadata,
458 };
459 } else {
460 9 ▶ push @{$self->_batch}, {
Branch: 4 branches
BranchTrueFalseTotal
defined $completion_at ? : 1 8 9
$opts{'model'} ? : 6 3 9
$usage ? : 2 7 9
%metadata ? : 2 7 9
461 id => _uuid(),
462 type => 'generation-update',
463 timestamp => $now,
464 body => {
465 id => $trace_info->{gen_id},
466 output => $opts{output},
467 endTime => _timestamp(@$end_at),
468 defined $completion_at ? (completionStartTime => _timestamp(@$completion_at)) : (),
469 9 $opts{model} ? (model => $opts{model}) : (),
470 # Langfuse v2 reads usage and drops usageDetails; v3 reads both,
471 # usageDetails overriding usage.
472 $usage ? (usage => _legacy_usage($usage),
473 usageDetails => $usage) : (),
474 %metadata ? (metadata => \%metadata) : (),
475 },
476 };
477 }
478 }
479  
480 10 ▶ push @{$self->_batch}, {
Condition66%2/3
$opts{"output"} // $opts{"error"}
l!l&&r!l&&!r
910
MC/DC0%0/2
$opts{"output"} // $opts{"error"}
$opts{"output"} $opts{"error"}
Truth table66%2/3
A // B
A= $opts{"output"}B= $opts{"error"}
ABresult
1X1
011
000
481 id => _uuid(),
482 type => 'trace-create',
483 timestamp => $now,
484 body => {
485 id => $trace_info->{trace_id},
486 output => $opts{output} // $opts{error},
487 },
488 11 ▶ } unless $otel;
Branch: 1 branch
BranchTrueFalseTotal
unless $otel 10 1 11
489  
490 11 $self->flush;
491 }
492  
493  
494 has _loop => (
495 is => 'lazy',
496 0 ▶ builder => sub { IO::Async::Loop->new },
Subroutine __ANON__: not called CC=1 SCAR=1.2
Subroutine _build__loop: called CC=1 SCAR=1.2
497 8 );
498  
499 has _http => (
500 is => 'lazy',
501 0 ▶ builder => sub {
Subroutine __ANON__: not called CC=2 SCAR=10.1
Subroutine _build__http: called CC=2 SCAR=10.1
502 0 my ($self) = @_;
503 # Net::Async::HTTP times out at once on 0, so 0 (none) sets no timeout.
504 0 my $timeout = $self->config->langfuse_timeout;
505 0 ▶ my $h = Net::Async::HTTP->new( user_agent => 'Langertha-Knarr',
Branch: 2 branches
BranchTrueFalseTotal
$timeout ? : 0 0 0
$timeout ? : 2 0 2
506 $timeout ? ( timeout => $timeout ) : () );
507 0 $self->_loop->add($h);
508 0 return $h;
509 },
510 8 );
511  
512 9 ▶sub flush {
Subroutine flush: called CC=7 SCAR=19.5
Pod documented
513 9 my ($self) = @_;
514 9 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 9 9
515 9 my $batch = $self->_batch;
516 9 ▶ return unless @$batch;
Branch: 1 branch
BranchTrueFalseTotal
unless @$batch 0 9 9
517 9 $self->_batch([]);
518  
519 9 my $auth = encode_base64($self->_public_key . ':' . $self->_secret_key, '');
520 9 my $otel = $self->transport eq 'otel';
521  
522 # Tracing is observability, not the product. flush runs inside end_trace on
523 # the response path — and for streams after the last chunk was written — so
524 # an exception here turns an already-answered request into a 500, or leaves
525 # a client waiting for an end marker that never comes. The batch was
526 # detached from _batch above and is unrecoverable either way, so a failed
527 # encode is logged at error level (as loud as any request fault in
528 # Langertha::Knarr) and dropped, exactly like the ingestion failures below.
529 9 my $body;
530 9 my $encode_error = do {
531 9 local $@;
532 9 eval {
533 9 ▶ $body = $self->_json->encode(
Branch: 1 branch
BranchTrueFalseTotal
$otel ? : 1 8 9
534 $otel ? $self->_otlp_request($batch) : { batch => $batch } );
535 };
536 9 $@;
537 };
538 9 ▶ if ($encode_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($encode_error) 1 8 9
539 1 $log->errorf("Langfuse batch encode failed, dropping %d event(s): %s",
540 scalar @$batch, $encode_error);
541 1 return;
542 }
543  
544 8 ▶ my $req = HTTP::Request->new(
Branch: 2 branches
BranchTrueFalseTotal
$otel ? : 1 7 8
$otel ? : 1 7 8
545 POST => $self->_url . ( $otel ? '/api/public/otel/v1/traces' : '/api/public/ingestion' ),
546 [
547 'Content-Type' => 'application/json',
548 'Authorization' => 'Basic ' . $auth,
549 # Selects Langfuse v4's real-time OTel ingestion (else up to 10 min late).
550 $otel ? ( 'x-langfuse-ingestion-version' => '4' ) : (),
551 ],
552 $body,
553 );
554  
555 8 my $f = $self->_http->do_request( request => $req );
556 6 ▶ $f->on_done(sub {
Subroutine __ANON__: called CC=2 SCAR=8.1
557 6 my ($resp) = @_;
558 6 ▶ return if $resp->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $resp->is_success 6 0 6
559 0 $log->warnf("Langfuse ingestion failed: %s", $resp->status_line);
560 8 });
561 2 ▶ $f->on_fail(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
562 2 my ($err) = @_;
563 2 $log->warnf("Langfuse flush error: %s", $err);
564 8 });
565 8 $f->retain;
566 8 return;
567 }
568  
569 # OTLP/JSON ExportTraceServiceRequest for the traces end_trace finished.
570 # Enums (span kind, status code) are integers, ids lowercase hex and times
571 # decimal strings, as the OTLP/JSON encoding prescribes.
572 1 ▶sub _otlp_request {
Subroutine _otlp_request: called CC=1 SCAR=0.0
573 1 my ($self, $batch) = @_;
574 return {
575 resourceSpans => [ {
576 resource => { attributes => [ $self->_otel_attributes( 'service.name' => 'langertha-knarr' ) ] },
577 scopeSpans => [ {
578 scope => { name => __PACKAGE__, version => $VERSION },
579 1 spans => [ map { $self->_otel_spans($_) } @$batch ],
580 } ],
581 } ],
582 };
583 }
584  
585 8 my %SPAN_KIND = ( server => 2, client => 3 );
586 8 my $STATUS_ERROR = 2;
587  
588 # The root span (the Langfuse trace) and its generation child for one
589 # request, from the record end_trace pushed.
590 1 ▶sub _otel_spans {
Subroutine _otel_spans: called CC=8 SCAR=23.0
591 1 my ($self, $rec) = @_;
592 1 my $info = $rec->{info};
593 1 my $o = $info->{otel};
594 1 my $error = $rec->{error};
595 1 my $start = _unix_nano( @{ $info->{start_hires} } );
596  
597 # Langfuse v4 reads trace attributes off every span that carries them.
598 my @trace_attrs = (
599 1 $self->_otel_attributes( 'langfuse.trace.name' => $o->{name} ),
600 { key => 'langfuse.trace.tags',
601 value => { arrayValue => { values => [ { stringValue => 'knarr' } ] } } },
602 );
603 1 my $meta = $o->{metadata};
604 1 ▶ my $gen_meta = $rec->{metadata} // {};
Condition50%1/2
$rec->{"metadata"} // {}
l!l
10
MC/DC0%0/1
$rec->{"metadata"} // {}
$rec->{"metadata"}
Truth table50%1/2
A
A= $rec->{"metadata"}
Aresult
11
00
605  
606 # A failed request marks both the trace's span and the generation.
607 1 ▶ my @error_attrs = $error ? $self->_otel_attributes(
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 0 1 1
608 'langfuse.observation.level' => 'ERROR',
609 'langfuse.observation.status_message' => $error,
610 ) : ();
611 1 ▶ my @error_status = $error ? ( status => { code => $STATUS_ERROR, message => $error } ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 0 1 1
612  
613 my $root = {
614 traceId => $info->{trace_id},
615 spanId => $info->{root_id},
616 name => $o->{name},
617 kind => $SPAN_KIND{server},
618 startTimeUnixNano => $start,
619 1 ▶ endTimeUnixNano => _unix_nano( @{ $rec->{now} } ),
Condition33%1/3
$rec->{"output"} // $error
l!l&&r!l&&!r
100
MC/DC0%0/2
$rec->{"output"} // $error
$rec->{"output"} $error
Truth table33%1/3
A // B
A= $rec->{"output"}B= $error
ABresult
1X1
011
000
620 attributes => [
621 @trace_attrs,
622 $self->_otel_attributes(
623 'langfuse.observation.type' => 'span',
624 'langfuse.observation.input' => $o->{input},
625 'langfuse.observation.output' => $rec->{output} // $error,
626 1 map { ( 'langfuse.trace.metadata.'.$_ => $meta->{$_} ) } sort keys %$meta,
627 ),
628 @error_attrs,
629 ],
630 @error_status,
631 };
632  
633 my $gen = {
634 traceId => $info->{trace_id},
635 spanId => $info->{gen_id},
636 parentSpanId => $info->{root_id},
637 name => 'proxy-request',
638 kind => $SPAN_KIND{client},
639 startTimeUnixNano => $start,
640 1 ▶ endTimeUnixNano => _unix_nano( @{ $rec->{end} } ),
Branch: 2 branches
BranchTrueFalseTotal
$error ? : 0 1 1
$rec->{'completion_start'} ? : 0 1 1
Condition33%1/3
$rec->{'model'} || $o->{'model'}
l!l&&r!l&&!r
010
MC/DC0%0/2
$rec->{'model'} || $o->{'model'}
$rec->{'model'} $o->{'model'}
Truth table33%1/3
A || B
A= $rec->{'model'}B= $o->{'model'}
ABresult
1X1
011
000
641 attributes => [
642 @trace_attrs,
643 $self->_otel_attributes(
644 'langfuse.observation.type' => 'generation',
645 'langfuse.observation.model.name' => $rec->{model} || $o->{model},
646 'langfuse.observation.input' => $o->{input},
647 $error ? () : (
648 'langfuse.observation.output' => $rec->{output},
649 'langfuse.observation.completion_start_time' =>
650 0 $rec->{completion_start} ? _timestamp( @{ $rec->{completion_start} } ) : undef,
651 'langfuse.observation.usage_details' => $rec->{usage},
652 0 map { ( 'langfuse.observation.metadata.'.$_ => $gen_meta->{$_} ) } sort keys %$gen_meta,
653 ),
654 ),
655 @error_attrs,
656 ],
657 @error_status,
658 };
659  
660 1 return ( $root, $gen );
661 }
662  
663 # OTLP KeyValue list from key/value pairs. An undef value is left out; a
664 # reference is JSON-encoded into a string, which is how Langfuse takes
665 # structured input, output, usage and metadata; anything else is a string.
666 4 ▶sub _otel_attributes {
Subroutine _otel_attributes: called CC=4 SCAR=13.9
667 4 my ($self, @pairs) = @_;
668 4 my @attrs;
669 4 ▶ while ( my ( $key, $value ) = splice @pairs, 0, 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@pairs, 0, 2)) 16 4 20
670 16 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 4 12 16
671 12 ▶ $value = $self->_attr_json->encode($value) if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 2 10 12
672 12 push @attrs, { key => $key, value => { stringValue => "$value" } };
673 }
674 4 return @attrs;
675 }
676  
677  
678 8 1;
679  
680 __END__
« blib/lib/Langertha/Knarr/Protocol/OpenAI.pm ↑ Summary blib/lib/Langertha/Knarr/CLI/Cmd/Models.pm »