blib/lib/Langertha/Plugin/Langfuse.pm

filter: Statementstmt 99.2% 276 / 278 Branchbran 75.0% 168 / 224 Conditioncond 55.2% 42 / 76 MC/DCmcdc 27.6% 13 / 47 Subroutinesub 97.8% 45 / 46 Podpod 100% 14 / 14 totaltotal 81.4% 558 / 685 CC 142 SCAR 23.9
CC
142
Cov
84%
_generation_details
31.3
create_generation
17.9
create_span
14.5
CRAP 11.0
« blib/lib/Langertha/Role/Capabilities.pm ↑ Summary blib/lib/Langertha/Reasoning/Profile.pm »
1 package Langertha::Plugin::Langfuse;
2 # ABSTRACT: Langfuse observability plugin for any PluginHost
3 7 our $VERSION = '0.505';
4 7 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use Time::HiRes qw( gettimeofday );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use Langertha::Role::Langfuse ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 7 ▶use Scalar::Util qw( blessed refaddr weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 7 extends 'Langertha::Plugin';
16  
17  
18 has public_key => (
19 is => 'ro',
20 isa => 'Str',
21 lazy => 1,
22 1 ▶ default => sub { $ENV{LANGFUSE_PUBLIC_KEY} // '' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$ENV{"LANGFUSE_PUBLIC_KEY"} // ""
l!l
01
MC/DC0%0/1
$ENV{"LANGFUSE_PUBLIC_KEY"} // ""
$ENV{"LANGFUSE_PUBLIC_KEY"}
Truth table50%1/2
A
A= $ENV{"LANGFUSE_PUBLIC_KEY"}
Aresult
11
00
23 7 );
24  
25  
26 has secret_key => (
27 is => 'ro',
28 isa => 'Str',
29 lazy => 1,
30 0 ▶ default => sub { $ENV{LANGFUSE_SECRET_KEY} // '' },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/2
$ENV{"LANGFUSE_SECRET_KEY"} // ""
l!l
00
MC/DC0%0/1
$ENV{"LANGFUSE_SECRET_KEY"} // ""
$ENV{"LANGFUSE_SECRET_KEY"}
Truth table0%0/2
A
A= $ENV{"LANGFUSE_SECRET_KEY"}
Aresult
11
00
31 7 );
32  
33  
34 has url => (
35 is => 'ro',
36 isa => 'Str',
37 lazy => 1,
38 2 ▶ default => sub { $ENV{LANGFUSE_URL} // 'https://cloud.langfuse.com' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$ENV{"LANGFUSE_URL"} // "https://cloud.langfuse.com"
l!l
02
MC/DC0%0/1
$ENV{"LANGFUSE_URL"} // "https://cloud.langfuse.com"
$ENV{"LANGFUSE_URL"}
Truth table50%1/2
A
A= $ENV{"LANGFUSE_URL"}
Aresult
11
00
39 7 );
40  
41  
42 7 has enabled => (
43 is => 'ro',
44 isa => 'Bool',
45 lazy => 1,
46 builder => '_build_enabled',
47 );
48  
49  
50 33 ▶sub _build_enabled {
Subroutine _build_enabled: called CC=3 SCAR=11.1
51 33 my ( $self ) = @_;
52 33 ▶ return length($self->public_key) && length($self->secret_key) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $self->public_key && length $self->secret_key ? : 32 1 33
Condition66%2/3
length $self->public_key and length $self->secret_key
!ll&&!rl&&r
1032
MC/DC50%1/2
length $self->public_key and length $self->secret_key
length $self->public_key length $self->secret_key
Truth table66%2/3
A and B
A= length $self->public_keyB= length $self->secret_key
ABresult
0X0
100
111
53 }
54  
55 7 has trace_name => (
56 is => 'ro',
57 isa => 'Str',
58 default => 'llm-call',
59 );
60  
61  
62 7 has user_id => (
63 is => 'ro',
64 isa => 'Str',
65 predicate => 'has_user_id',
66 );
67  
68  
69 7 has session_id => (
70 is => 'ro',
71 isa => 'Str',
72 predicate => 'has_session_id',
73 );
74  
75  
76 7 has tags => (
77 is => 'ro',
78 isa => 'ArrayRef[Str]',
79 predicate => 'has_tags',
80 );
81  
82  
83 7 has metadata => (
84 is => 'ro',
85 isa => 'HashRef',
86 predicate => 'has_metadata',
87 );
88  
89  
90 7 has auto_flush => (
91 is => 'ro',
92 isa => 'Bool',
93 default => 0,
94 );
95  
96  
97 7 has flush_timeout => (
98 is => 'ro',
99 isa => 'Num',
100 default => 10,
101 );
102  
103  
104 7 has flush_batch_size => (
105 is => 'ro',
106 isa => 'Int',
107 default => 100,
108 );
109  
110  
111 has _pending_flushes => (
112 is => 'ro',
113 33 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
114 7 );
115  
116 # --- Internal state ---
117  
118 has _batch => (
119 is => 'rw',
120 isa => 'ArrayRef',
121 33 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
122 7 );
123  
124 7 has max_batch => (
125 is => 'ro',
126 isa => 'Int',
127 default => 1000,
128 );
129  
130  
131 # Every event goes through here so the batch stays bounded (karr k305).
132 98 ▶sub _push {
Subroutine _push: called CC=4 SCAR=13.9
133 98 my ( $self, $event ) = @_;
134 98 my $batch = $self->_batch;
135 98 push @$batch, $event;
136 98 my $max = $self->max_batch;
137 98 ▶ if ( $max > 0 && @$batch > $max ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max > 0 and @$batch > $max) 4 94 98
Condition66%2/3
$max > 0 and @$batch > $max
!ll&&!rl&&r
0944
MC/DC50%1/2
$max > 0 and @$batch > $max
$max > 0 @$batch > $max
Truth table66%2/3
A and B
A= $max > 0B= @$batch > $max
ABresult
0X0
100
111
138 4 splice @$batch, 0, @$batch - $max;
139 4 ▶ unless ( $self->{_overflow_warned}++ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($$self{"_overflow_warned"}++) 1 3 4
140 1 warn ref($self) . ": Langfuse batch reached max_batch ($max events) without a flush; "
141 . "dropping the oldest events. Call flush regularly or set auto_flush.\n";
142 }
143 }
144 98 return;
145 }
146  
147 7 has _trace_id => (
148 is => 'rw',
149 isa => 'Maybe[Str]',
150 );
151  
152 7 has _iter_start => (
153 is => 'rw',
154 isa => 'Maybe[Str]',
155 );
156  
157 7 has _iter_start_hires => (
158 is => 'rw',
159 isa => 'Maybe[ArrayRef]',
160 );
161  
162 7 has _iter_input => (
163 is => 'rw',
164 );
165  
166 7 has pricing => (
167 is => 'ro',
168 isa => 'Langertha::Pricing',
169 predicate => 'has_pricing',
170 );
171  
172  
173 has _json => (
174 is => 'ro',
175 lazy => 1,
176 18 ▶ default => sub { JSON::MaybeXS->new(utf8 => 1, canonical => 1, convert_blessed => 1) },
Subroutine __ANON__: called CC=1 SCAR=0.0
177 7 );
178  
179 # --- Langfuse utility methods ---
180  
181 172 ▶sub _id {
Subroutine _id: called CC=1 SCAR=0.0
182 172 my @hex = map { sprintf("%04x", int(rand(65536))) } 1..8;
183 172 return join('-',
184 $hex[0].$hex[1],
185 $hex[2],
186 '4'.substr($hex[3], 1),
187 sprintf("%x", 8 + int(rand(4))).substr($hex[4], 1),
188 $hex[5].$hex[6].$hex[7],
189 );
190 }
191  
192 150 ▶sub _timestamp {
Subroutine _timestamp: called CC=1 SCAR=0.0
193 150 my ($s, $us) = gettimeofday;
194 150 my @t = gmtime($s);
195 150 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
196 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
197 }
198  
199 # --- Langfuse event creation ---
200  
201 44 ▶sub create_trace {
Subroutine create_trace: called CC=10 SCAR=23.9
Pod documented
202 44 my ( $self, %opts ) = @_;
203 44 ▶ return unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 44 44
204 44 ▶ my $id = $opts{id} || _id();
Condition33%1/3
$opts{'id'} || _id()
l!l&&r!l&&!r
0440
MC/DC0%0/2
$opts{'id'} || _id()
$opts{'id'} _id()
Truth table33%1/3
A || B
A= $opts{'id'}B= _id()
ABresult
1X1
011
000
205 $self->_push({
206 id => _id(),
207 type => 'trace-create',
208 timestamp => _timestamp(),
209 body => {
210 id => $id,
211 name => $opts{name} // 'langfuse-trace',
212 $opts{input} ? ( input => $opts{input} ) : (),
213 $opts{output} ? ( output => $opts{output} ) : (),
214 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
215 $opts{tags} ? ( tags => $opts{tags} ) : (),
216 $opts{user_id} ? ( userId => $opts{user_id} ) : (),
217 44 ▶ $opts{session_id} ? ( sessionId => $opts{session_id} ) : (),
Branch: 6 branches
BranchTrueFalseTotal
$opts{'input'} ? : 23 21 44
$opts{'output'} ? : 0 44 44
$opts{'metadata'} ? : 1 43 44
$opts{'tags'} ? : 1 43 44
$opts{'user_id'} ? : 1 43 44
$opts{'session_id'} ? : 1 43 44
Condition50%1/2
$opts{"name"} // "langfuse-trace"
l!l
440
MC/DC0%0/1
$opts{"name"} // "langfuse-trace"
$opts{"name"}
Truth table50%1/2
A
A= $opts{"name"}
Aresult
11
00
218 },
219 });
220 44 return $id;
221 }
222  
223  
224 27 ▶sub create_generation {
Subroutine create_generation: called CC=15 SCAR=28.9
Pod documented
225 27 my ( $self, %opts ) = @_;
226 27 ▶ return unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 27 27
227 27 ▶ my $id = $opts{id} || _id();
Condition33%1/3
$opts{'id'} || _id()
l!l&&r!l&&!r
0270
MC/DC0%0/2
$opts{'id'} || _id()
$opts{'id'} _id()
Truth table33%1/3
A || B
A= $opts{'id'}B= _id()
ABresult
1X1
011
000
228 $self->_push({
229 id => _id(),
230 type => 'generation-create',
231 timestamp => _timestamp(),
232 body => {
233 id => $id,
234 traceId => $opts{trace_id} // croak("create_generation requires trace_id"),
235 name => $opts{name} // 'generation',
236 $opts{model} ? ( model => $opts{model} ) : (),
237 $opts{input} ? ( input => $opts{input} ) : (),
238 $opts{output} ? ( output => $opts{output} ) : (),
239 $opts{usage} ? ( usage => $opts{usage} ) : (),
240 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
241 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
242 $opts{parent_observation_id}? ( parentObservationId => $opts{parent_observation_id} ) : (),
243 $opts{model_parameters} ? ( modelParameters => $opts{model_parameters} ) : (),
244 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
245 defined $opts{completion_start_time}
246 27 ▶ ? ( completionStartTime => $opts{completion_start_time} ) : (),
Branch: 10 branches
BranchTrueFalseTotal
$opts{'model'} ? : 14 12 26
$opts{'input'} ? : 25 1 26
$opts{'output'} ? : 19 7 26
$opts{'usage'} ? : 9 17 26
$opts{'start_time'} ? : 26 0 26
$opts{'end_time'} ? : 26 0 26
$opts{'parent_observation_id'} ? : 0 26 26
$opts{'model_parameters'} ? : 0 26 26
$opts{'metadata'} ? : 2 24 26
defined $opts{'completion_start_time'} ? : 1 25 26
Condition75%3/4
$opts{"trace_id"} // croak("create_generation requires trace_id")
l!l
261
$opts{"name"} // "generation"
l!l
260
MC/DC100%1/1
$opts{"trace_id"} // croak("create_generation requires trace_id")
$opts{"trace_id"}
MC/DC0%0/1
$opts{"name"} // "generation"
$opts{"name"}
Truth table100%2/2
A
A= $opts{"trace_id"}
Aresult
11
00
Truth table50%1/2
A
A= $opts{"name"}
Aresult
11
00
247 },
248 });
249 26 return $id;
250 }
251  
252  
253 2 ▶sub create_span {
Subroutine create_span: called CC=11 SCAR=26.8
Pod documented
254 2 my ( $self, %opts ) = @_;
255 2 ▶ return unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 2 2
256 2 ▶ my $id = $opts{id} || _id();
Condition33%1/3
$opts{'id'} || _id()
l!l&&r!l&&!r
020
MC/DC0%0/2
$opts{'id'} || _id()
$opts{'id'} _id()
Truth table33%1/3
A || B
A= $opts{'id'}B= _id()
ABresult
1X1
011
000
257 $self->_push({
258 id => _id(),
259 type => 'span-create',
260 timestamp => _timestamp(),
261 body => {
262 id => $id,
263 traceId => $opts{trace_id} // croak("create_span requires trace_id"),
264 $opts{name} ? ( name => $opts{name} ) : (),
265 $opts{input} ? ( input => $opts{input} ) : (),
266 $opts{output} ? ( output => $opts{output} ) : (),
267 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
268 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
269 $opts{parent_observation_id}? ( parentObservationId => $opts{parent_observation_id} ) : (),
270 2 ▶ $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
Branch: 7 branches
BranchTrueFalseTotal
$opts{'name'} ? : 2 0 2
$opts{'input'} ? : 2 0 2
$opts{'output'} ? : 1 1 2
$opts{'start_time'} ? : 1 1 2
$opts{'end_time'} ? : 1 1 2
$opts{'parent_observation_id'} ? : 0 2 2
$opts{'metadata'} ? : 0 2 2
Condition50%1/2
$opts{"trace_id"} // croak("create_span requires trace_id")
l!l
20
MC/DC0%0/1
$opts{"trace_id"} // croak("create_span requires trace_id")
$opts{"trace_id"}
Truth table50%1/2
A
A= $opts{"trace_id"}
Aresult
11
00
271 },
272 });
273 2 return $id;
274 }
275  
276  
277 26 ▶sub update_trace {
Subroutine update_trace: called CC=5 SCAR=17.5
Pod documented
278 26 my ( $self, %opts ) = @_;
279 26 ▶ return unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 26 26
280 26 ▶ my $id = $opts{id} // croak("update_trace requires id");
Condition50%1/2
$opts{"id"} // croak("update_trace requires id")
l!l
260
MC/DC0%0/1
$opts{"id"} // croak("update_trace requires id")
$opts{"id"}
Truth table50%1/2
A
A= $opts{"id"}
Aresult
11
00
281 $self->_push({
282 id => _id(),
283 type => 'trace-create',
284 timestamp => _timestamp(),
285 body => {
286 id => $id,
287 $opts{output} ? ( output => $opts{output} ) : (),
288 26 ▶ $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
Branch: 2 branches
BranchTrueFalseTotal
$opts{'output'} ? : 26 0 26
$opts{'metadata'} ? : 0 26 26
289 },
290 });
291 26 return $id;
292 }
293  
294  
295 10 ▶sub _flush_args {
Subroutine _flush_args: called CC=4 SCAR=13.9
296 10 my ( $self ) = @_;
297 10 my @events = @{ $self->_batch };
298 10 ▶ return unless @events;
Branch: 1 branch
BranchTrueFalseTotal
unless @events 3 7 10
299 7 $self->_batch([]);
300 7 my $size = $self->flush_batch_size;
301 7 ▶ $size = 1 if $size < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $size < 1 0 7 7
302 7 my @chunks;
303 7 ▶ push @chunks, [ splice @events, 0, $size ] while @events;
Branch: 1 branch
BranchTrueFalseTotal
@events and do { push @chunks, [splice(@events, 0, $size)] } 9 7 16
304 return (
305 7 chunks => \@chunks,
306 url => $self->url,
307 public_key => $self->public_key,
308 secret_key => $self->secret_key,
309 json => $self->_json,
310 agent => 'Langertha-Plugin-Langfuse/' . $VERSION,
311 timeout => $self->flush_timeout,
312 );
313 }
314  
315 # The engine whose async backend carries a flush: the host when it is an
316 # engine itself, else the host's engine (Chat, Embedder, ImageGen, Raider).
317 # None (a host without one, or a host already gone: it is a weak ref) means
318 # the dedicated LWP agent with flush_timeout.
319 6 ▶sub _flush_engine {
Subroutine _flush_engine: called CC=6 SCAR=19.3
320 6 my ( $self ) = @_;
321 6 ▶ my $host = $self->host or return;
Branch: 1 branch
BranchTrueFalseTotal
my $host = $self->host or return 5 1 6
322 5 ▶ return $host if $host->can('_async_do_request_f');
Branch: 1 branch
BranchTrueFalseTotal
if $host->can("_async_do_request_f") 0 5 5
323 5 ▶ return unless $host->can('engine');
Branch: 1 branch
BranchTrueFalseTotal
unless $host->can("engine") 0 5 5
324 5 my $engine = $host->engine;
325 5 ▶ return blessed($engine) && $engine->can('_async_do_request_f') ? $engine : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($engine) && $engine->can('_async_do_request_f') ? : 5 0 5
Condition33%1/3
builtin::blessed($engine) and $engine->can("_async_do_request_f")
!ll&&!rl&&r
005
MC/DC0%0/2
builtin::blessed($engine) and $engine->can("_async_do_request_f")
builtin::blessed($engine) $engine->can("_async_do_request_f")
Truth table33%1/3
A and B
A= builtin::blessed($engine)B= $engine->can("_async_do_request_f")
ABresult
0X0
100
111
326 }
327  
328 5 ▶sub _send_f {
Subroutine _send_f: called CC=1 SCAR=0.0
329 5 my ( $self, %args ) = @_;
330 5 return Langertha::Role::Langfuse->_langfuse_send_chunks_f( %args, engine => scalar $self->_flush_engine );
331 }
332  
333 # auto_flush from inside an async hook: start the flush and return at once.
334 # The future is held on the object until it is ready (flush_timeout bounds
335 # that), so it is not lost to garbage collection; flush / flush_f wait for it.
336 4 ▶sub _auto_flush {
Subroutine _auto_flush: called CC=3 SCAR=11.0
337 4 my ( $self ) = @_;
338 4 ▶ my %args = $self->_flush_args or return;
Branch: 1 branch
BranchTrueFalseTotal
my(%args) = $self->_flush_args or return 4 0 4
339 4 my $future = $self->_send_f(%args);
340 4 ▶ return if $future->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $future->is_ready 2 2 4
341 2 my $pending = $self->_pending_flushes;
342 2 my $key = refaddr $future;
343 2 $pending->{$key} = $future;
344 2 weaken( my $weak = $pending );
345 2 ▶ $future->on_ready( sub { delete $weak->{$key} if $weak } );
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $weak 2 0 2
346 2 return;
347 }
348  
349 4 ▶sub flush {
Subroutine flush: called CC=6 SCAR=18.1
Pod documented
350 4 my ( $self ) = @_;
351 4 ▶ return unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 4 4
352 4 ▶ if ( my @pending = values %{ $self->_pending_flushes } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@pending) = values %{$self->_pending_flushes;}) 1 3 4
353 # Only the Net::Async::HTTP path leaves a flush pending, so there is a loop.
354 1 my $engine = $self->_flush_engine;
355 1 ▶ my $loop = $engine ? $engine->async_loop : undef;
Branch: 1 branch
BranchTrueFalseTotal
$engine ? : 1 0 1
356 1 ▶ $loop->await_all(@pending) if $loop;
Branch: 1 branch
BranchTrueFalseTotal
if $loop 1 0 1
357 }
358 4 ▶ my %args = $self->_flush_args or return;
Branch: 1 branch
BranchTrueFalseTotal
my(%args) = $self->_flush_args or return 2 2 4
359 2 my @responses = Langertha::Role::Langfuse->_langfuse_send_chunks_f(%args)->get;
360 2 return $responses[-1];
361 }
362  
363  
364 2 ▶async sub flush_f {
Subroutine flush_f: called CC=4 SCAR=13.9
Pod documented
365 2 my ( $self ) = @_;
366 2 ▶ return unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 2 2
367 2 my @pending = values %{ $self->_pending_flushes };
368 2 ▶ await Future->wait_all(@pending) if @pending;
Branch: 1 branch
BranchTrueFalseTotal
if @pending 1 1 2
369 2 ▶ my %args = $self->_flush_args or return;
Branch: 1 branch
BranchTrueFalseTotal
my(%args) = $self->_flush_args or return 1 1 2
370 1 return await $self->_send_f(%args);
371 7 }
372  
373  
374 # Deep copy through the encoder: JSON-safe, and a Langertha::Content::Image
375 # becomes its compact TO_JSON description (never the image data). A Chat
376 # hands the hooks messages already in the engine's wire shape, where an image
377 # is a data: URL or a bare base64 string; those are shortened too, or every
378 # trace would carry every image once per iteration (as karr k273 for TO_JSON).
379 21 ▶sub _json_safe {
Subroutine _json_safe: called CC=3 SCAR=11.0
380 21 my ( $self, $data ) = @_;
381 21 ▶ return $data unless ref $data;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data 0 21 21
382 21 my $copy = eval { $self->_json->decode( $self->_json->encode($data) ) };
383 21 ▶ return $data unless defined $copy;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $copy 0 21 21
384 21 my $walk;
385 55 ▶ $walk = sub {
Subroutine __ANON__: called CC=9 SCAR=22.1
386 55 my ($node) = @_;
387 63 ▶ my @slots = ref $node eq 'HASH' ? ( map { \$node->{$_} } keys %$node )
Branch: 1 branch
BranchTrueFalseTotal
ref $node eq 'ARRAY' ? : 23 0 23
388 55 ▶ : ref $node eq 'ARRAY' ? ( map { \$_ } @$node ) : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $node eq 'HASH' ? : 32 23 55
389 55 for my $slot (@slots) {
390 91 ▶ if ( ref $$slot ) { $walk->($$slot); next }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$slot) 34 57 91
391 57 ▶ next unless defined $$slot;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$slot 0 57 57
392 57 ▶ if ( $$slot =~ m{\A(data:[^;,]+;base64,)(.*)\z}s ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$slot =~ /\A(data:[^;,]+;base64,)(.*)\z/s) { } 1 56 57
elsif (length $$slot >= 512 and $$slot =~ m[\A[A-Za-z0-9+/]+={0,2}\z]) { } 1 110 111
393 1 $$slot = $1 . '[' . _base64_bytes($2) . ' bytes omitted]';
394 }
395 ▶ elsif ( length $$slot >= 512 && $$slot =~ m{\A[A-Za-z0-9+/]+={0,2}\z} ) {
Condition66%2/3
length $$slot >= 512 and $$slot =~ m[\A[A-Za-z0-9+/]+={0,2}\z]
!ll&&!rl&&r
5501
MC/DC50%1/2
length $$slot >= 512 and $$slot =~ m[\A[A-Za-z0-9+/]+={0,2}\z]
length $$slot >= 512 $$slot =~ m[\A[A-Za-z0-9+/]+={0,2}\z]
Truth table66%2/3
A and B
A= length $$slot >= 512B= $$slot =~ m[\A[A-Za-z0-9+/]+={0,2}\z]
ABresult
0X0
100
111
396 1 $$slot = '[base64: ' . _base64_bytes($$slot) . ' bytes omitted]';
397 }
398 }
399 21 };
400 21 $walk->($copy);
401 21 undef $walk;
402 21 return $copy;
403 }
404  
405 2 ▶sub _base64_bytes {
Subroutine _base64_bytes: called CC=2 SCAR=7.0
406 2 my ($b64) = @_;
407 2 $b64 =~ s/\s+//g;
408 2 ▶ my $pad = $b64 =~ /(=+)\z/ ? length $1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$b64 =~ /(=+)\z/ ? : 0 2 2
409 2 return int( length($b64) * 3 / 4 ) - $pad;
410 }
411  
412 19 ▶sub _host_engine {
Subroutine _host_engine: called CC=4 SCAR=13.9
413 19 my ( $self ) = @_;
414 19 ▶ my $host = $self->host or return;
Branch: 1 branch
BranchTrueFalseTotal
my $host = $self->host or return 11 8 19
415 11 ▶ return $host->engine if $host->can('engine') && blessed( $host->engine );
Branch: 1 branch
BranchTrueFalseTotal
if $host->can("engine") and builtin::blessed($host->engine) 7 4 11
Condition66%2/3
$host->can("engine") and builtin::blessed($host->engine)
!ll&&!rl&&r
407
MC/DC50%1/2
$host->can("engine") and builtin::blessed($host->engine)
$host->can("engine") builtin::blessed($host->engine)
Truth table66%2/3
A and B
A= $host->can("engine")B= builtin::blessed($host->engine)
ABresult
0X0
100
111
416 4 return $host;
417 }
418  
419 # model, usage (+ cost), output and completionStartTime of one LLM answer
420 # (karr k304), from a Langertha::Response or, in the tool loop, the raw
421 # decoded provider body. Observability must never break the call: anything
422 # that cannot be read is left out.
423 19 ▶sub _generation_details {
Subroutine _generation_details: called CC=28 SCAR=34.4
424 19 my ( $self, $data ) = @_;
425 19 my $engine = $self->_host_engine;
426 19 my ( $model, $usage, $output, $completion_start );
427  
428 19 ▶ if ( blessed($data) && $data->isa('Langertha::Response') ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($data) and $data->isa('Langertha::Response')) { } 9 10 19
elsif (ref $data eq 'HASH') { } 3 7 10
Condition66%2/3
builtin::blessed($data) and $data->isa("Langertha::Response")
!ll&&!rl&&r
1009
MC/DC50%1/2
builtin::blessed($data) and $data->isa("Langertha::Response")
builtin::blessed($data) $data->isa("Langertha::Response")
Truth table66%2/3
A and B
A= builtin::blessed($data)B= $data->isa("Langertha::Response")
ABresult
0X0
100
111
429 9 ▶ $model = $data->model if $data->has_model;
Branch: 1 branch
BranchTrueFalseTotal
if $data->has_model 7 2 9
430 9 ▶ $usage = $data->usage if $data->has_usage && blessed( $data->usage );
Branch: 1 branch
BranchTrueFalseTotal
if $data->has_usage and builtin::blessed($data->usage) 6 3 9
Condition66%2/3
$data->has_usage and builtin::blessed($data->usage)
!ll&&!rl&&r
306
MC/DC50%1/2
$data->has_usage and builtin::blessed($data->usage)
$data->has_usage builtin::blessed($data->usage)
Truth table66%2/3
A and B
A= $data->has_usageB= builtin::blessed($data->usage)
ABresult
0X0
100
111
431 9 ▶ my @calls = $data->has_tool_calls ? @{ $data->tool_calls } : ();
Branch: 1 branch
BranchTrueFalseTotal
$data->has_tool_calls ? : 1 8 9
432 $output = @calls
433 9 ▶ ? { content => $data->content, tool_calls => [ map { $_->to_hash } @calls ] }
Branch: 1 branch
BranchTrueFalseTotal
@calls ? : 1 8 9
434 : $data->content;
435 9 my $start = $self->_iter_start_hires;
436 9 ▶ $completion_start = Langertha::Role::Langfuse->_langfuse_iso_after( $start, $data->ttft_seconds )
Branch: 1 branch
BranchTrueFalseTotal
if $start and $data->has_ttft 1 8 9
Condition66%2/3
$start and $data->has_ttft
!ll&&!rl&&r
081
MC/DC50%1/2
$start and $data->has_ttft
$start $data->has_ttft
Truth table66%2/3
A and B
A= $startB= $data->has_ttft
ABresult
0X0
100
111
437 if $start && $data->has_ttft;
438 }
439 elsif ( ref $data eq 'HASH' ) {
440 3 ▶ $model = $data->{model} if defined $data->{model} && !ref $data->{model};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$data{"model"} and not ref $$data{"model"} 1 2 3
Condition66%2/3
defined $$data{"model"} and not ref $$data{"model"}
!ll&&!rl&&r
201
MC/DC50%1/2
defined $$data{"model"} and not ref $$data{"model"}
defined $$data{"model"} not ref $$data{"model"}
Truth table66%2/3
A and not(B)
A= defined $$data{"model"}B= not ref $$data{"model"}
ABresult
0X0
100
111
441 3 $usage = Langertha::Usage->from_raw($data);
442 3 ▶ $output = eval {
Branch: 1 branch
BranchTrueFalseTotal
if $engine and $engine->can("response_text_content") and $engine->can("response_tool_calls") 1 2 3
Condition66%4/6
$engine and $engine->can("response_text_content") and $engine->can("response_tool_calls")
!ll&&!rl&&r
201
$engine and $engine->can("response_text_content")
!ll&&!rl&&r
201
MC/DC33%1/3
$engine and $engine->can("response_text_content") and $engine->can("response_tool_calls")
$engine $engine->can("response_text_content") $engine->can("response_tool_calls")
Truth table50%2/4
A and B and C
A= $engineB= $engine->can("response_text_content")C= $engine->can("response_tool_calls")
ABCresult
0XX0
10X0
1100
1111
443 1 my $text = $engine->response_text_content($data);
444 # The canonical ToolCall shape when the engine names its wire (as on
445 # the Response path), else the raw structures the engine locates.
446 my $calls = $engine->can('tool_wire_format')
447 0 ▶ ? [ map { $_->to_hash } Langertha::ToolCall->extract( $engine->tool_wire_format, $data ) ]
Branch: 1 branch
BranchTrueFalseTotal
$engine->can('tool_wire_format') ? : 1 0 1
448 : $self->_json_safe( $engine->response_tool_calls($data) );
449 1 ▶ ref $calls eq 'ARRAY' && @$calls ? { content => $text, tool_calls => $calls } : $text;
Branch: 1 branch
BranchTrueFalseTotal
ref $calls eq 'ARRAY' && @$calls ? : 0 1 1
Condition33%1/3
ref $calls eq "ARRAY" and @$calls
!ll&&!rl&&r
010
MC/DC0%0/2
ref $calls eq "ARRAY" and @$calls
ref $calls eq "ARRAY" @$calls
Truth table33%1/3
A and B
A= ref $calls eq "ARRAY"B= @$calls
ABresult
0X0
100
111
450 } if $engine && $engine->can('response_text_content') && $engine->can('response_tool_calls');
451 3 ▶ $output = $self->_json_safe($data) unless defined $output;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $output 2 1 3
452 }
453 else {
454 7 $output = $data;
455 }
456  
457 19 ▶ $model //= $engine->chat_model if $engine && $engine->can('chat_model');
Branch: 1 branch
BranchTrueFalseTotal
if $engine and $engine->can("chat_model") 11 8 19
Condition66%4/6
$engine and $engine->can("chat_model")
!ll&&!rl&&r
8011
$model //= $engine->chat_model
l!l&&r!l&&!r
830
MC/DC50%1/2
$engine and $engine->can("chat_model")
$engine $engine->can("chat_model")
MC/DC0%0/2
$model //= $engine->chat_model
$model $engine->chat_model
Truth table66%2/3
A and B
A= $engineB= $engine->can("chat_model")
ABresult
0X0
100
111
Truth table66%2/3
A //= B
A= $modelB= $engine->chat_model
ABresult
1X1
011
000
458  
459 19 ▶ my $usage_hash = $usage ? $self->_usage_hash( $usage, $model ) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$usage ? : 7 12 19
460  
461 return (
462 19 ▶ defined $model ? ( model => $model ) : (),
Branch: 4 branches
BranchTrueFalseTotal
defined $model ? : 11 8 19
$usage_hash ? : 7 12 19
defined $output ? : 19 0 19
defined $completion_start ? : 1 18 19
463 $usage_hash ? ( usage => $usage_hash ) : (),
464 defined $output ? ( output => $output ) : (),
465 defined $completion_start ? ( completion_start_time => $completion_start ) : (),
466 );
467 }
468  
469 # Langfuse usage (input/output/total, plus cost when a pricing rule matches)
470 # of a Langertha::Usage.
471 9 ▶sub _usage_hash {
Subroutine _usage_hash: called CC=3 SCAR=11.0
472 9 my ( $self, $usage, $model ) = @_;
473 9 my $usage_hash = {
474 input => $usage->input_tokens,
475 output => $usage->output_tokens,
476 total => $usage->total_tokens,
477 };
478 9 ▶ if ( $self->has_pricing && $self->pricing->rule_for($model) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_pricing and $self->pricing->rule_for($model)) 2 7 9
Condition66%2/3
$self->has_pricing and $self->pricing->rule_for($model)
!ll&&!rl&&r
702
MC/DC50%1/2
$self->has_pricing and $self->pricing->rule_for($model)
$self->has_pricing $self->pricing->rule_for($model)
Truth table66%2/3
A and B
A= $self->has_pricingB= $self->pricing->rule_for($model)
ABresult
0X0
100
111
479 2 my $cost = $self->pricing->cost_for( $usage, $model );
480 2 $usage_hash->{inputCost} = $cost->input_usd + $cost->cache_read_usd + $cost->cache_write_usd;
481 2 $usage_hash->{outputCost} = $cost->output_usd;
482 2 $usage_hash->{totalCost} = $cost->total_usd;
483 }
484 9 return $usage_hash;
485 }
486  
487 # model, usage (+ cost) and total_seconds (as metadata) of an embedding or
488 # image generation, from the Langertha::CallResult the *_result path hands
489 # the after-hook (k320). Nothing without one: the bare path has no metadata.
490 6 ▶sub _call_result_details {
Subroutine _call_result_details: called CC=8 SCAR=23.7
491 6 my ( $self, $call_result ) = @_;
492 6 ▶ return () unless blessed($call_result) && $call_result->isa('Langertha::CallResult');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($call_result) and $call_result->isa("Langertha::CallResult") 4 2 6
Condition66%2/3
builtin::blessed($call_result) and $call_result->isa("Langertha::CallResult")
!ll&&!rl&&r
402
MC/DC50%1/2
builtin::blessed($call_result) and $call_result->isa("Langertha::CallResult")
builtin::blessed($call_result) $call_result->isa("Langertha::CallResult")
Truth table66%2/3
A and B
A= builtin::blessed($call_result)B= $call_result->isa("Langertha::CallResult")
ABresult
0X0
100
111
493 2 ▶ my $model = $call_result->has_model ? $call_result->model : undef;
Branch: 1 branch
BranchTrueFalseTotal
$call_result->has_model ? : 2 0 2
494 return (
495 2 ▶ defined $model ? ( model => $model ) : (),
Branch: 3 branches
BranchTrueFalseTotal
defined $model ? : 2 0 2
$call_result->has_usage && builtin::blessed($call_result->usage) ? : 2 0 2
$call_result->has_total_seconds ? : 2 0 2
Condition33%1/3
$call_result->has_usage and builtin::blessed($call_result->usage)
!ll&&!rl&&r
002
MC/DC0%0/2
$call_result->has_usage and builtin::blessed($call_result->usage)
$call_result->has_usage builtin::blessed($call_result->usage)
Truth table33%1/3
A and B
A= $call_result->has_usageB= builtin::blessed($call_result->usage)
ABresult
0X0
100
111
496 $call_result->has_usage && blessed( $call_result->usage )
497 ? ( usage => $self->_usage_hash( $call_result->usage, $model ) ) : (),
498 $call_result->has_total_seconds
499 ? ( metadata => { total_seconds => $call_result->total_seconds } ) : (),
500 );
501 }
502  
503 1 ▶sub reset_trace {
Subroutine reset_trace: called CC=1 SCAR=0.0
Pod documented
504 1 my ( $self ) = @_;
505 1 $self->_trace_id(undef);
506 1 $self->_iter_start(undef);
507 1 $self->_iter_start_hires(undef);
508 1 $self->_iter_input(undef);
509 }
510  
511  
512  
513 # --- Plugin hooks ---
514  
515 20 ▶async sub plugin_before_llm_call {
Subroutine plugin_before_llm_call: called CC=7 SCAR=19.5
Pod documented
516 20 my ( $self, $conversation, $iteration ) = @_;
517 20 ▶ return $conversation unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 1 19 20
518  
519 # A snapshot: the tool loop keeps pushing onto $conversation, and the
520 # events are only encoded at flush time.
521 19 my $input = $self->_json_safe($conversation);
522  
523 # Create trace on first iteration (or if no trace exists)
524 19 ▶ if (!$self->_trace_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_trace_id) 16 3 19
525 16 ▶ $self->_trace_id($self->create_trace(
Branch: 4 branches
BranchTrueFalseTotal
$self->has_user_id ? : 1 15 16
$self->has_session_id ? : 1 15 16
$self->has_tags ? : 1 15 16
$self->has_metadata ? : 1 15 16
526 name => $self->trace_name,
527 input => $input,
528 $self->has_user_id ? ( user_id => $self->user_id ) : (),
529 $self->has_session_id ? ( session_id => $self->session_id ) : (),
530 $self->has_tags ? ( tags => $self->tags ) : (),
531 $self->has_metadata ? ( metadata => $self->metadata ) : (),
532 ));
533 }
534  
535 19 $self->_iter_start(_timestamp());
536 19 $self->_iter_start_hires([gettimeofday]);
537 19 $self->_iter_input($input);
538 19 return $conversation;
539 7 }
540  
541 19 ▶async sub plugin_after_llm_response {
Subroutine plugin_after_llm_response: called CC=3 SCAR=11.0
Pod documented
542 19 my ( $self, $data, $iteration ) = @_;
543 19 ▶ return $data unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 19 19
544  
545 19 $self->create_generation(
546 trace_id => $self->_trace_id,
547 name => "generation-$iteration",
548 start_time => $self->_iter_start,
549 end_time => _timestamp(),
550 input => $self->_iter_input,
551 $self->_generation_details($data),
552 );
553  
554 # Update trace output (last update wins via upsert)
555 19 $self->update_trace(
556 id => $self->_trace_id,
557 output => $data,
558 );
559  
560 19 ▶ $self->_auto_flush if $self->auto_flush;
Branch: 1 branch
BranchTrueFalseTotal
if $self->auto_flush 4 15 19
561  
562 19 return $data;
563 7 }
564  
565 1 ▶async sub plugin_after_tool_call {
Subroutine plugin_after_tool_call: called CC=2 SCAR=7.0
Pod documented
566 1 my ( $self, $name, $input, $result ) = @_;
567 1 ▶ return $result unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 1 1
568  
569 1 my $t = _timestamp();
570 1 $self->create_span(
571 trace_id => $self->_trace_id,
572 name => "tool:$name",
573 input => $input,
574 output => $result,
575 start_time => $t,
576 end_time => $t,
577 );
578  
579 1 return $result;
580 7 }
581  
582 2 ▶async sub plugin_before_image_gen {
Subroutine plugin_before_image_gen: called CC=7 SCAR=21.5
Pod documented
583 2 my ( $self, $prompt ) = @_;
584 2 ▶ return $prompt unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 2 2
585  
586 2 ▶ if (!$self->_trace_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_trace_id) 2 0 2
587 2 ▶ $self->_trace_id($self->create_trace(
Branch: 4 branches
BranchTrueFalseTotal
$self->has_user_id ? : 0 2 2
$self->has_session_id ? : 0 2 2
$self->has_tags ? : 0 2 2
$self->has_metadata ? : 0 2 2
588 name => $self->trace_name,
589 input => $prompt,
590 $self->has_user_id ? ( user_id => $self->user_id ) : (),
591 $self->has_session_id ? ( session_id => $self->session_id ) : (),
592 $self->has_tags ? ( tags => $self->tags ) : (),
593 $self->has_metadata ? ( metadata => $self->metadata ) : (),
594 ));
595 }
596  
597 2 $self->_iter_start(_timestamp());
598 2 return $prompt;
599 7 }
600  
601 2 ▶async sub plugin_after_image_gen {
Subroutine plugin_after_image_gen: called CC=3 SCAR=11.1
Pod documented
602 2 my ( $self, $prompt, $result, $call_result ) = @_;
603 2 ▶ return $result unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 2 2
604  
605 2 my $end_time = _timestamp();
606 2 $self->create_generation(
607 trace_id => $self->_trace_id,
608 name => 'image-generation',
609 start_time => $self->_iter_start,
610 end_time => $end_time,
611 input => $prompt,
612 $self->_call_result_details($call_result),
613 );
614  
615 2 $self->update_trace(
616 id => $self->_trace_id,
617 output => $result,
618 );
619  
620 2 ▶ $self->_auto_flush if $self->auto_flush;
Branch: 1 branch
BranchTrueFalseTotal
if $self->auto_flush 0 2 2
621  
622 2 return $result;
623 7 }
624  
625 4 ▶async sub plugin_before_embedding {
Subroutine plugin_before_embedding: called CC=7 SCAR=21.5
Pod documented
626 4 my ( $self, $text ) = @_;
627 4 ▶ return $text unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 4 4
628  
629 4 ▶ if (!$self->_trace_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_trace_id) 4 0 4
630 4 ▶ $self->_trace_id($self->create_trace(
Branch: 4 branches
BranchTrueFalseTotal
$self->has_user_id ? : 0 4 4
$self->has_session_id ? : 0 4 4
$self->has_tags ? : 0 4 4
$self->has_metadata ? : 0 4 4
631 name => $self->trace_name,
632 input => $text,
633 $self->has_user_id ? ( user_id => $self->user_id ) : (),
634 $self->has_session_id ? ( session_id => $self->session_id ) : (),
635 $self->has_tags ? ( tags => $self->tags ) : (),
636 $self->has_metadata ? ( metadata => $self->metadata ) : (),
637 ));
638 }
639  
640 4 $self->_iter_start(_timestamp());
641 4 return $text;
642 7 }
643  
644 4 ▶async sub plugin_after_embedding {
Subroutine plugin_after_embedding: called CC=5 SCAR=16.4
Pod documented
645 4 my ( $self, $text, $vector, $call_result ) = @_;
646 4 ▶ return $vector unless $self->enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->enabled 0 4 4
647  
648 4 my $end_time = _timestamp();
649 4 $self->create_generation(
650 trace_id => $self->_trace_id,
651 name => 'embedding',
652 start_time => $self->_iter_start,
653 end_time => $end_time,
654 input => $text,
655 $self->_call_result_details($call_result),
656 );
657  
658 $self->update_trace(
659 id => $self->_trace_id,
660 # A batch (k289) is an ArrayRef of vectors: report the vector's width.
661 output => { dimensions => ref $vector eq 'ARRAY'
662 4 ▶ ? ( ref $vector->[0] eq 'ARRAY' ? scalar @{$vector->[0]} : scalar @$vector )
Branch: 2 branches
BranchTrueFalseTotal
ref $vector eq 'ARRAY' ? : 4 0 4
ref $$vector[0] eq 'ARRAY' ? : 1 3 4
663 : undef },
664 );
665  
666 4 ▶ $self->_auto_flush if $self->auto_flush;
Branch: 1 branch
BranchTrueFalseTotal
if $self->auto_flush 0 4 4
667  
668 4 return $vector;
669 7 }
670  
671 7 __PACKAGE__->meta->make_immutable;
672  
673 7 1;
674  
675 __END__
« blib/lib/Langertha/Role/Capabilities.pm ↑ Summary blib/lib/Langertha/Reasoning/Profile.pm »