Knarr/Tracing.pm

filter: Statementstmt 35.7% 39 / 109 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 34 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 34.6% 9 / 26 Podpod 100% 3 / 3 totaltotal 24.0% 51 / 212 CC 24 SCAR 28.2
CC
24
Cov
24%
end_trace
56.0
_build__enabled
30.0
_build_trace_name
20.0
CRAP 16.8
« Knarr/Router.pm ↑ Summary Knarr/RequestLog.pm »
1 package Langertha::Knarr::Tracing;
2 1 our $VERSION = '1.100';
3 # ABSTRACT: Automatic Langfuse tracing per proxy request
4 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Time::HiRes qw( gettimeofday );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use HTTP::Request ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Net::Async::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14  
15 1 has config => (
16 is => 'ro',
17 required => 1,
18 );
19  
20  
21 1 has _enabled => (
22 is => 'lazy',
23 builder => '_build__enabled',
24 );
25  
26 sub _build__enabled {
27 0 ▶ my ($self) = @_;
Subroutine _build__enabled: not called CC=5 SCAR=34.0
28 0 my $lf = $self->config->langfuse;
29 0 ▶ my $pub = $lf->{public_key} // _strip_quotes($ENV{LANGFUSE_PUBLIC_KEY});
Condition0%0/3
$lf->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
l!l&&r!l&&!r
000
MC/DC0%0/2
$lf->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
$lf->{"public_key"} _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
Truth table0%0/3
A // B
A= $lf->{"public_key"}B= _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
ABresult
1X1
011
000
30 0 ▶ my $sec = $lf->{secret_key} // _strip_quotes($ENV{LANGFUSE_SECRET_KEY});
Condition0%0/3
$lf->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
l!l&&r!l&&!r
000
MC/DC0%0/2
$lf->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
$lf->{"secret_key"} _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
Truth table0%0/3
A // B
A= $lf->{"secret_key"}B= _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
ABresult
1X1
011
000
31 0 ▶ return ($pub && $sec) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$pub && $sec ? : 0 0 0
Condition0%0/3
$pub and $sec
!ll&&!rl&&r
000
MC/DC0%0/2
$pub and $sec
$pub $sec
Truth table0%0/3
A and B
A= $pubB= $sec
ABresult
0X0
100
111
32 }
33  
34 1 has _public_key => (
35 is => 'lazy',
36 builder => '_build__public_key',
37 );
38  
39 sub _build__public_key {
40 0 ▶ my ($self) = @_;
Subroutine _build__public_key: not called CC=2 SCAR=17.9
41 0 ▶ return $self->config->langfuse->{public_key} // _strip_quotes($ENV{LANGFUSE_PUBLIC_KEY});
Condition0%0/3
$self->config->langfuse->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
l!l&&r!l&&!r
000
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 table0%0/3
A // B
A= $self->config->langfuse->{"public_key"}B= _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
ABresult
1X1
011
000
42 }
43  
44 1 has _secret_key => (
45 is => 'lazy',
46 builder => '_build__secret_key',
47 );
48  
49 sub _build__secret_key {
50 0 ▶ my ($self) = @_;
Subroutine _build__secret_key: not called CC=2 SCAR=17.9
51 0 ▶ return $self->config->langfuse->{secret_key} // _strip_quotes($ENV{LANGFUSE_SECRET_KEY});
Condition0%0/3
$self->config->langfuse->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
l!l&&r!l&&!r
000
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 table0%0/3
A // B
A= $self->config->langfuse->{"secret_key"}B= _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
ABresult
1X1
011
000
52 }
53  
54 1 has _url => (
55 is => 'lazy',
56 builder => '_build__url',
57 );
58  
59 1 has trace_name => (
60 is => 'lazy',
61 builder => '_build_trace_name',
62 );
63  
64  
65 sub _build_trace_name {
66 0 ▶ my ($self) = @_;
Subroutine _build_trace_name: not called CC=4 SCAR=30.0
67 return $self->config->langfuse->{trace_name}
68 // _strip_quotes($ENV{LANGFUSE_TRACE_NAME})
69 // _strip_quotes($ENV{KNARR_TRACE_NAME})
70 0 ▶ // 'knarr-proxy';
Condition0%0/8
(($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})) // "knarr-proxy"
l!l
00
($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})
l!l&&r!l&&!r
000
$self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})
l!l&&r!l&&!r
000
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 table0%0/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
71 }
72  
73 sub _build__url {
74 0 ▶ my ($self) = @_;
Subroutine _build__url: not called CC=4 SCAR=30.0
75 0 ▶ return $self->config->langfuse->{url} // _strip_quotes($ENV{LANGFUSE_URL}) // _strip_quotes($ENV{LANGFUSE_BASE_URL}) // 'https://cloud.langfuse.com';
Condition0%0/8
(($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})) // "https://cloud.langfuse.com"
l!l
00
($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})
l!l&&r!l&&!r
000
$self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})
l!l&&r!l&&!r
000
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 table0%0/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
76 }
77  
78 has _batch => (
79 is => 'rw',
80 0 ▶ default => sub { [] },
Subroutine __ANON__: not called CC=1 SCAR=6.9
81 1 );
82  
83 1 has _json => (
84 is => 'lazy',
85 builder => '_build__json',
86 );
87  
88 # Strip surrounding quotes from env values (Docker --env-file includes them literally)
89 sub _strip_quotes {
90 0 ▶ my $v = shift;
Subroutine _strip_quotes: not called CC=2 SCAR=17.9
91 0 ▶ return $v unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
92 0 $v =~ s/^["']|["']$//g;
93 0 return $v;
94 }
95  
96 sub _build__json {
97 0 ▶ return JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1);
Subroutine _build__json: not called CC=1 SCAR=6.9
98 }
99  
100 sub _uuid {
101 0 ▶ my @hex = map { sprintf("%04x", int(rand(65536))) } 1..8;
Subroutine _uuid: not called CC=1 SCAR=6.9
102 0 return join('-',
103 $hex[0].$hex[1],
104 $hex[2],
105 '4'.substr($hex[3], 1),
106 sprintf("%x", 8 + int(rand(4))).substr($hex[4], 1),
107 $hex[5].$hex[6].$hex[7],
108 );
109 }
110  
111 sub _timestamp {
112 0 ▶ my ($s, $us) = gettimeofday;
Subroutine _timestamp: not called CC=1 SCAR=6.9
113 0 my @t = gmtime($s);
114 0 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
115 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
116 }
117  
118  
119 sub start_trace {
120 0 ▶ my ($self, %opts) = @_;
Subroutine start_trace: not called CC=2 SCAR=17.9
Pod documented
121 0 ▶ return undef unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 0 0
122  
123 0 my $trace_id = _uuid();
124 0 my $gen_id = _uuid();
125 0 my $now = _timestamp();
126  
127 0 push @{$self->_batch}, {
128 id => _uuid(),
129 type => 'trace-create',
130 timestamp => $now,
131 body => {
132 id => $trace_id,
133 name => $self->trace_name,
134 input => $opts{messages},
135 metadata => {
136 format => $opts{format},
137 engine => $opts{engine},
138 model => $opts{model},
139 params => $opts{params},
140 },
141 0 tags => ['knarr'],
142 },
143 };
144  
145 0 push @{$self->_batch}, {
146 id => _uuid(),
147 type => 'generation-create',
148 timestamp => $now,
149 body => {
150 id => $gen_id,
151 traceId => $trace_id,
152 name => 'proxy-request',
153 model => $opts{model},
154 input => $opts{messages},
155 0 startTime => $now,
156 },
157 };
158  
159 0 return { trace_id => $trace_id, gen_id => $gen_id, start_time => $now };
160 }
161  
162  
163 sub end_trace {
164 0 ▶ my ($self, $trace_info, %opts) = @_;
Subroutine end_trace: not called CC=7 SCAR=40.3
Pod documented
165 0 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 0 0
166 0 ▶ return unless $trace_info;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace_info 0 0 0
167  
168 0 my $now = _timestamp();
169  
170 0 ▶ if ($opts{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'error'}) { } 0 0 0
171 0 push @{$self->_batch}, {
172 id => _uuid(),
173 type => 'generation-update',
174 timestamp => $now,
175 body => {
176 id => $trace_info->{gen_id},
177 endTime => $now,
178 level => 'ERROR',
179 statusMessage => $opts{error},
180 },
181 0 };
182 } else {
183 0 ▶ push @{$self->_batch}, {
Branch: 2 branches
BranchTrueFalseTotal
$opts{'model'} ? : 0 0 0
$opts{'usage'} ? : 0 0 0
184 id => _uuid(),
185 type => 'generation-update',
186 timestamp => $now,
187 body => {
188 id => $trace_info->{gen_id},
189 output => $opts{output},
190 endTime => $now,
191 $opts{model} ? (model => $opts{model}) : (),
192 0 $opts{usage} ? (usage => $opts{usage}) : (),
193 },
194 };
195 }
196  
197 0 ▶ push @{$self->_batch}, {
Condition0%0/3
$opts{"output"} // $opts{"error"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{"output"} // $opts{"error"}
$opts{"output"} $opts{"error"}
Truth table0%0/3
A // B
A= $opts{"output"}B= $opts{"error"}
ABresult
1X1
011
000
198 id => _uuid(),
199 type => 'trace-create',
200 timestamp => $now,
201 body => {
202 id => $trace_info->{trace_id},
203 output => $opts{output} // $opts{error},
204 },
205 0 };
206  
207 0 $self->flush;
208 }
209  
210  
211 has _loop => (
212 is => 'lazy',
213 0 ▶ builder => sub { IO::Async::Loop->new },
Subroutine __ANON__: not called CC=1 SCAR=6.9
214 1 );
215  
216 has _http => (
217 is => 'lazy',
218 builder => sub {
219 0 ▶ my ($self) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
220 0 my $h = Net::Async::HTTP->new( user_agent => 'Langertha-Knarr', timeout => 5 );
221 0 $self->_loop->add($h);
222 0 return $h;
223 },
224 1 );
225  
226 sub flush {
227 0 ▶ my ($self) = @_;
Subroutine flush: not called CC=3 SCAR=24.8
Pod documented
228 0 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 0 0
229 0 my $batch = $self->_batch;
230 0 ▶ return unless @$batch;
Branch: 1 branch
BranchTrueFalseTotal
unless @$batch 0 0 0
231 0 $self->_batch([]);
232  
233 0 my $auth = encode_base64($self->_public_key . ':' . $self->_secret_key, '');
234 0 my $body = $self->_json->encode({ batch => $batch });
235 0 my $req = HTTP::Request->new(
236 POST => $self->_url . '/api/public/ingestion',
237 [
238 'Content-Type' => 'application/json',
239 'Authorization' => 'Basic ' . $auth,
240 ],
241 $body,
242 );
243  
244 0 my $f = $self->_http->do_request( request => $req );
245 $f->on_done(sub {
246 0 ▶ my ($resp) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
247 0 ▶ return if $resp->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $resp->is_success 0 0 0
248 0 $log->warnf("Langfuse ingestion failed: %s", $resp->status_line);
249 0 });
250 $f->on_fail(sub {
251 0 ▶ my ($err) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
252 0 $log->warnf("Langfuse flush error: %s", $err);
253 0 });
254 0 $f->retain;
255 0 return;
256 }
257  
258  
259 1 1;
260  
261 __END__
262  
263 =pod
264  
265 =encoding UTF-8
266  
267 =head1 NAME
268  
269 Langertha::Knarr::Tracing - Automatic Langfuse tracing per proxy request
270  
271 =head1 VERSION
272  
273 version 1.100
274  
275 =head1 SYNOPSIS
276  
277 use Langertha::Knarr::Tracing;
278  
279 my $tracing = Langertha::Knarr::Tracing->new(config => $config);
280  
281 my $trace_id = $tracing->start_trace(
282 model => 'gpt-4o',
283 engine => 'Langertha::Engine::OpenAI',
284 messages => \@messages,
285 params => \%params,
286 format => 'openai',
287 );
288  
289 # ... handle request ...
290  
291 $tracing->end_trace($trace_id,
292 output => $response_text,
293 model => 'gpt-4o',
294 usage => { input => 100, output => 50, total => 150 },
295 );
296  
297 =head1 DESCRIPTION
298  
299 Records every proxy request as a Langfuse trace with a nested generation. When
300 tracing is not configured (no public and secret key), all methods are no-ops.
301  
302 Langfuse credentials are read from the config file's C<langfuse:> section or
303 from the C<LANGFUSE_PUBLIC_KEY>, C<LANGFUSE_SECRET_KEY>, and C<LANGFUSE_URL>
304 environment variables. The module strips surrounding quotes from environment
305 variable values, which Docker C<--env-file> sometimes adds literally.
306  
307 =head2 config
308  
309 The L<Langertha::Knarr::Config> object. Required. Provides Langfuse
310 credentials and C<trace_name>.
311  
312 =head2 trace_name
313  
314 The Langfuse trace name applied to all traces. Resolved in priority order from:
315 C<langfuse.trace_name> in config, C<LANGFUSE_TRACE_NAME> env var,
316 C<KNARR_TRACE_NAME> env var, or the default C<knarr-proxy>.
317  
318 =head2 start_trace
319  
320 my $trace_info = $tracing->start_trace(
321 model => $model_name,
322 engine => $engine_class,
323 messages => \@messages,
324 params => \%params,
325 format => 'openai',
326 );
327  
328 Creates a new Langfuse trace and generation. Returns a C<$trace_info> hashref
329 that must be passed to L</end_trace>. Returns C<undef> when tracing is
330 disabled.
331  
332 =head2 end_trace
333  
334 $tracing->end_trace($trace_info,
335 output => $response_text,
336 model => $model,
337 usage => { input => 100, output => 50, total => 150 },
338 );
339  
340 # On error:
341 $tracing->end_trace($trace_info, error => "Something went wrong");
342  
343 Closes the generation and trace started by L</start_trace>, then flushes the
344 batch to Langfuse. Pass C<error> to record a failed generation at level ERROR.
345 Does nothing when C<$trace_info> is C<undef> (tracing was disabled at start).
346  
347 =head2 flush
348  
349 $tracing->flush;
350  
351 Sends all pending trace events to the Langfuse ingestion API as a batch and
352 clears the internal buffer. Called automatically by L</end_trace>. Does nothing
353 when tracing is disabled or the batch is empty.
354  
355 =head1 SEE ALSO
356  
357 =over
358  
359 =item * L<Langertha::Knarr> — Tracing is wired in automatically for all routes
360  
361 =item * L<Langertha::Knarr::Config> — Provides Langfuse credentials
362  
363 =back
364  
365 =head1 SUPPORT
366  
367 =head2 Issues
368  
369 Please report bugs and feature requests on GitHub at
370 L<https://github.com/Getty/langertha-knarr/issues>.
371  
372 =head2 IRC
373  
374 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
375  
376 =head1 CONTRIBUTING
377  
378 Contributions are welcome! Please fork the repository and submit a pull request.
379  
380 =head1 AUTHOR
381  
382 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
383  
384 =head1 COPYRIGHT AND LICENSE
385  
386 This software is copyright (c) 2026 by Torsten Raudssus.
387  
388 This is free software; you can redistribute it and/or modify it under
389 the same terms as the Perl 5 programming language system itself.
390  
391 =cut
« Knarr/Router.pm ↑ Summary Knarr/RequestLog.pm »