blib/lib/Langertha/Role/Langfuse.pm

filter: Statementstmt 82.0% 174 / 212 Branchbran 65.3% 132 / 202 Conditioncond 45.9% 40 / 87 MC/DCmcdc 27.4% 14 / 51 Subroutinesub 88.8% 32 / 36 Podpod 100% 10 / 10 totaltotal 67.2% 402 / 598 CC 230 SCAR 31.0
CC
230
Cov
69%
__ANON__
176.8
langfuse_update_trace
28.8
langfuse_update_trace
28.8
CRAP 22.3
« blib/lib/Langertha/Role/OpenAICompatible.pm ↑ Summary blib/lib/Langertha/Role/AnthropicCompatible.pm »
1 package Langertha::Role::Langfuse;
2 # ABSTRACT: Langfuse observability integration
3 195 our $VERSION = '0.505';
4 195 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 195 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 195 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 195 ▶use JSON::MaybeXS qw( JSON );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 195 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 195 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 195 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 195 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 195 has langfuse_public_key => (
15 is => 'ro',
16 isa => 'Str',
17 predicate => 'has_langfuse_public_key',
18 );
19  
20  
21 195 has langfuse_secret_key => (
22 is => 'ro',
23 isa => 'Str',
24 predicate => 'has_langfuse_secret_key',
25 );
26  
27  
28 has langfuse_url => (
29 is => 'ro',
30 isa => 'Str',
31 lazy => 1,
32 10 ▶ default => sub { $ENV{LANGFUSE_URL} || 'https://cloud.langfuse.com' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"LANGFUSE_URL"} or "https://cloud.langfuse.com" 0 10 10
33 195 );
34  
35  
36 195 has langfuse_enabled => (
37 is => 'ro',
38 isa => 'Bool',
39 lazy => 1,
40 builder => '_build_langfuse_enabled',
41 );
42  
43  
44 46 ▶sub _build_langfuse_enabled {
Subroutine _build_langfuse_enabled: called CC=5 SCAR=23.4
45 0 ▶ my ( $self ) = @_;
Subroutine _build_langfuse_enabled: not called CC=5 SCAR=23.4
46 # Enabled if keys are passed directly or via env vars
47 0 ▶ my $pub = $self->has_langfuse_public_key || $ENV{LANGFUSE_PUBLIC_KEY};
Condition33%2/6
$self->has_langfuse_public_key || $ENV{'LANGFUSE_PUBLIC_KEY'}
l!l&&r!l&&!r
15031
$self->has_langfuse_public_key || $ENV{'LANGFUSE_PUBLIC_KEY'}
l!l&&r!l&&!r
000
MC/DC50%1/2
$self->has_langfuse_public_key || $ENV{'LANGFUSE_PUBLIC_KEY'}
$self->has_langfuse_public_key $ENV{'LANGFUSE_PUBLIC_KEY'}
MC/DC0%0/2
$self->has_langfuse_public_key || $ENV{'LANGFUSE_PUBLIC_KEY'}
$self->has_langfuse_public_key $ENV{'LANGFUSE_PUBLIC_KEY'}
Truth table66%2/3
A || B
A= $self->has_langfuse_public_keyB= $ENV{'LANGFUSE_PUBLIC_KEY'}
ABresult
1X1
011
000
Truth table0%0/3
A || B
A= $self->has_langfuse_public_keyB= $ENV{'LANGFUSE_PUBLIC_KEY'}
ABresult
1X1
011
000
48 0 ▶ my $sec = $self->has_langfuse_secret_key || $ENV{LANGFUSE_SECRET_KEY};
Condition33%2/6
$self->has_langfuse_secret_key || $ENV{'LANGFUSE_SECRET_KEY'}
l!l&&r!l&&!r
15031
$self->has_langfuse_secret_key || $ENV{'LANGFUSE_SECRET_KEY'}
l!l&&r!l&&!r
000
MC/DC50%1/2
$self->has_langfuse_secret_key || $ENV{'LANGFUSE_SECRET_KEY'}
$self->has_langfuse_secret_key $ENV{'LANGFUSE_SECRET_KEY'}
MC/DC0%0/2
$self->has_langfuse_secret_key || $ENV{'LANGFUSE_SECRET_KEY'}
$self->has_langfuse_secret_key $ENV{'LANGFUSE_SECRET_KEY'}
Truth table66%2/3
A || B
A= $self->has_langfuse_secret_keyB= $ENV{'LANGFUSE_SECRET_KEY'}
ABresult
1X1
011
000
Truth table0%0/3
A || B
A= $self->has_langfuse_secret_keyB= $ENV{'LANGFUSE_SECRET_KEY'}
ABresult
1X1
011
000
49 0 ▶ return $pub && $sec ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
$pub && $sec ? : 15 31 46
$pub && $sec ? : 0 0 0
Condition33%2/6
$pub and $sec
!ll&&!rl&&r
31015
$pub and $sec
!ll&&!rl&&r
000
MC/DC50%1/2
$pub and $sec
$pub $sec
MC/DC0%0/2
$pub and $sec
$pub $sec
Truth table66%2/3
A and B
A= $pubB= $sec
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $pubB= $sec
ABresult
0X0
100
111
50 }
51  
52 4444 ▶around BUILDARGS => sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
53 4444 my ( $orig, $class, @args ) = @_;
54 # Let Moose normalize first: new() also takes one HashRef.
55 4444 my $args = $class->$orig(@args);
56 # Auto-populate from env vars if not passed
57 $args->{langfuse_public_key} //= $ENV{LANGFUSE_PUBLIC_KEY}
58 4437 ▶ if $ENV{LANGFUSE_PUBLIC_KEY};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"LANGFUSE_PUBLIC_KEY"} 7 4430 4437
Condition66%2/3
$args->{"langfuse_public_key"} //= $ENV{"LANGFUSE_PUBLIC_KEY"}
l!l&&r!l&&!r
250
MC/DC0%0/2
$args->{"langfuse_public_key"} //= $ENV{"LANGFUSE_PUBLIC_KEY"}
$args->{"langfuse_public_key"} $ENV{"LANGFUSE_PUBLIC_KEY"}
Truth table66%2/3
A //= B
A= $args->{"langfuse_public_key"}B= $ENV{"LANGFUSE_PUBLIC_KEY"}
ABresult
1X1
011
000
59 $args->{langfuse_secret_key} //= $ENV{LANGFUSE_SECRET_KEY}
60 4437 ▶ if $ENV{LANGFUSE_SECRET_KEY};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"LANGFUSE_SECRET_KEY"} 7 4430 4437
Condition66%2/3
$args->{"langfuse_secret_key"} //= $ENV{"LANGFUSE_SECRET_KEY"}
l!l&&r!l&&!r
250
MC/DC0%0/2
$args->{"langfuse_secret_key"} //= $ENV{"LANGFUSE_SECRET_KEY"}
$args->{"langfuse_secret_key"} $ENV{"LANGFUSE_SECRET_KEY"}
Truth table66%2/3
A //= B
A= $args->{"langfuse_secret_key"}B= $ENV{"LANGFUSE_SECRET_KEY"}
ABresult
1X1
011
000
61 4437 return $args;
62 195 };
63  
64 has _langfuse_batch => (
65 is => 'rw',
66 isa => 'ArrayRef',
67 4433 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
68 195 );
69  
70 195 has langfuse_max_batch => (
71 is => 'ro',
72 isa => 'Int',
73 default => 1000,
74 );
75  
76  
77 # Every event goes through here so the batch stays bounded (karr k305).
78 2032 ▶sub _langfuse_push {
Subroutine _langfuse_push: called CC=4 SCAR=17.9
79 0 ▶ my ( $self, $event ) = @_;
Subroutine _langfuse_push: not called CC=4 SCAR=17.9
80 0 my $batch = $self->_langfuse_batch;
81 0 push @$batch, $event;
82 0 my $max = $self->langfuse_max_batch;
83 0 ▶ if ( $max > 0 && @$batch > $max ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($max > 0 and @$batch > $max) 7 2025 2032
if ($max > 0 and @$batch > $max) 0 0 0
Condition50%3/6
$max > 0 and @$batch > $max
!ll&&!rl&&r
15005257
$max > 0 and @$batch > $max
!ll&&!rl&&r
000
MC/DC100%2/2
$max > 0 and @$batch > $max
$max > 0 @$batch > $max
MC/DC0%0/2
$max > 0 and @$batch > $max
$max > 0 @$batch > $max
Truth table100%3/3
A and B
A= $max > 0B= @$batch > $max
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $max > 0B= @$batch > $max
ABresult
0X0
100
111
84 0 splice @$batch, 0, @$batch - $max;
85 0 ▶ unless ( $self->{_langfuse_overflow_warned}++ ) {
Branch: 2 branches
BranchTrueFalseTotal
unless ($self->{"_langfuse_overflow_warned"}++) 1 6 7
unless ($$self{"_langfuse_overflow_warned"}++) 0 0 0
86 0 warn ref($self) . ": Langfuse batch reached langfuse_max_batch ($max events) "
87 . "without a flush; dropping the oldest events. Call langfuse_flush regularly.\n";
88 }
89 }
90 0 return;
91 }
92  
93 4065 ▶sub _langfuse_id {
Subroutine _langfuse_id: called CC=1 SCAR=1.2
94 0 ▶ my ( $self ) = @_;
Subroutine _langfuse_id: not called CC=1 SCAR=1.2
95 # Simple UUID v4 generation without external dependency
96 0 my @hex = map { sprintf("%04x", int(rand(65536))) } 1..8;
97 0 return join('-',
98 $hex[0].$hex[1],
99 $hex[2],
100 '4'.substr($hex[3], 1), # version 4
101 sprintf("%x", 8 + int(rand(4))).substr($hex[4], 1), # variant
102 $hex[5].$hex[6].$hex[7],
103 );
104 }
105  
106 2036 ▶sub langfuse_timestamp {
Subroutine langfuse_timestamp: called CC=1 SCAR=1.2
Pod documented
107 0 ▶ my ( $self ) = @_;
Subroutine langfuse_timestamp: not called CC=1 SCAR=1.2
Pod documented
108 0 my ($s, $us) = gettimeofday;
109 0 my @t = gmtime($s);
110 0 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
111 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
112 }
113  
114  
115 # Private alias kept for existing callers; the internal call sites use it too.
116 2035 ▶sub _langfuse_timestamp { $_[0]->langfuse_timestamp }
Subroutine _langfuse_timestamp: called CC=1 SCAR=0.0
117  
118 2027 ▶sub langfuse_trace {
Subroutine langfuse_trace: called CC=15 SCAR=27.3
Pod documented
119 2027 my ( $self, %opts ) = @_;
120 2027 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2026 2027
121 2026 ▶ my $id = $opts{id} || $self->_langfuse_id;
Condition33%1/3
$opts{'id'} || $self->_langfuse_id
l!l&&r!l&&!r
020260
MC/DC0%0/2
$opts{'id'} || $self->_langfuse_id
$opts{'id'} $self->_langfuse_id
Truth table33%1/3
A || B
A= $opts{'id'}B= $self->_langfuse_id
ABresult
1X1
011
000
122 $self->_langfuse_push({
123 id => $self->_langfuse_id,
124 type => 'trace-create',
125 timestamp => $self->_langfuse_timestamp,
126 body => {
127 id => $id,
128 name => $opts{name} // 'langfuse-trace',
129 $opts{input} ? ( input => $opts{input} ) : (),
130 $opts{output} ? ( output => $opts{output} ) : (),
131 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
132 $opts{tags} ? ( tags => $opts{tags} ) : (),
133 $opts{user_id} ? ( userId => $opts{user_id} ) : (),
134 $opts{session_id} ? ( sessionId => $opts{session_id} ) : (),
135 $opts{release} ? ( release => $opts{release} ) : (),
136 $opts{version} ? ( version => $opts{version} ) : (),
137 defined $opts{public}
138 ? ( public => $opts{public} ? JSON->true : JSON->false ) : (),
139 2026 ▶ $opts{environment} ? ( environment => $opts{environment} ) : (),
Branch: 11 branches
BranchTrueFalseTotal
$opts{'input'} ? : 2 2024 2026
$opts{'output'} ? : 1 2025 2026
$opts{'metadata'} ? : 0 2026 2026
$opts{'tags'} ? : 1 2025 2026
$opts{'user_id'} ? : 1 2025 2026
$opts{'session_id'} ? : 1 2025 2026
$opts{'release'} ? : 1 2025 2026
$opts{'version'} ? : 1 2025 2026
defined $opts{'public'} ? : 2 2024 2026
$opts{'public'} ? : 1 1 2
$opts{'environment'} ? : 1 2025 2026
Condition50%1/2
$opts{"name"} // "langfuse-trace"
l!l
20260
MC/DC0%0/1
$opts{"name"} // "langfuse-trace"
$opts{"name"}
Truth table50%1/2
A
A= $opts{"name"}
Aresult
11
00
140 },
141 });
142 2026 return $id;
143 }
144  
145  
146 4 ▶sub langfuse_generation {
Subroutine langfuse_generation: called CC=17 SCAR=28.7
Pod documented
147 4 my ( $self, %opts ) = @_;
148 4 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 3 4
149 3 ▶ my $id = $opts{id} || $self->_langfuse_id;
Condition33%1/3
$opts{'id'} || $self->_langfuse_id
l!l&&r!l&&!r
030
MC/DC0%0/2
$opts{'id'} || $self->_langfuse_id
$opts{'id'} $self->_langfuse_id
Truth table33%1/3
A || B
A= $opts{'id'}B= $self->_langfuse_id
ABresult
1X1
011
000
150 $self->_langfuse_push({
151 id => $self->_langfuse_id,
152 type => 'generation-create',
153 timestamp => $self->_langfuse_timestamp,
154 body => {
155 id => $id,
156 traceId => $opts{trace_id} // croak("langfuse_generation requires trace_id"),
157 name => $opts{name} // 'generation',
158 model => $opts{model},
159 $opts{input} ? ( input => $opts{input} ) : (),
160 $opts{output} ? ( output => $opts{output} ) : (),
161 $opts{usage} ? ( usage => $opts{usage} ) : (),
162 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
163 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
164 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
165 defined $opts{completion_start_time}
166 ? ( completionStartTime => $opts{completion_start_time} ) : (),
167 $opts{parent_observation_id}
168 ? ( parentObservationId => $opts{parent_observation_id} ) : (),
169 $opts{model_parameters}
170 ? ( modelParameters => $opts{model_parameters} ) : (),
171 $opts{level} ? ( level => $opts{level} ) : (),
172 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
173 3 ▶ $opts{version} ? ( version => $opts{version} ) : (),
Branch: 12 branches
BranchTrueFalseTotal
$opts{'input'} ? : 1 1 2
$opts{'output'} ? : 1 1 2
$opts{'usage'} ? : 1 1 2
$opts{'metadata'} ? : 0 2 2
$opts{'start_time'} ? : 1 1 2
$opts{'end_time'} ? : 1 1 2
defined $opts{'completion_start_time'} ? : 0 2 2
$opts{'parent_observation_id'} ? : 1 1 2
$opts{'model_parameters'} ? : 1 1 2
$opts{'level'} ? : 1 1 2
$opts{'status_message'} ? : 1 1 2
$opts{'version'} ? : 1 1 2
Condition75%3/4
$opts{"trace_id"} // croak("langfuse_generation requires trace_id")
l!l
21
$opts{"name"} // "generation"
l!l
20
MC/DC100%1/1
$opts{"trace_id"} // croak("langfuse_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
174 },
175 });
176 2 return $id;
177 }
178  
179  
180 3 ▶sub langfuse_span {
Subroutine langfuse_span: called CC=14 SCAR=31.9
Pod documented
181 3 my ( $self, %opts ) = @_;
182 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
183 2 ▶ my $id = $opts{id} || $self->_langfuse_id;
Condition33%1/3
$opts{'id'} || $self->_langfuse_id
l!l&&r!l&&!r
020
MC/DC0%0/2
$opts{'id'} || $self->_langfuse_id
$opts{'id'} $self->_langfuse_id
Truth table33%1/3
A || B
A= $opts{'id'}B= $self->_langfuse_id
ABresult
1X1
011
000
184 $self->_langfuse_push({
185 id => $self->_langfuse_id,
186 type => 'span-create',
187 timestamp => $self->_langfuse_timestamp,
188 body => {
189 id => $id,
190 traceId => $opts{trace_id} // croak("langfuse_span requires trace_id"),
191 $opts{name} ? ( name => $opts{name} ) : (),
192 $opts{input} ? ( input => $opts{input} ) : (),
193 $opts{output} ? ( output => $opts{output} ) : (),
194 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
195 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
196 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
197 $opts{parent_observation_id}
198 ? ( parentObservationId => $opts{parent_observation_id} ) : (),
199 $opts{level} ? ( level => $opts{level} ) : (),
200 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
201 2 ▶ $opts{version} ? ( version => $opts{version} ) : (),
Branch: 10 branches
BranchTrueFalseTotal
$opts{'name'} ? : 1 0 1
$opts{'input'} ? : 1 0 1
$opts{'output'} ? : 1 0 1
$opts{'metadata'} ? : 1 0 1
$opts{'start_time'} ? : 1 0 1
$opts{'end_time'} ? : 1 0 1
$opts{'parent_observation_id'} ? : 1 0 1
$opts{'level'} ? : 1 0 1
$opts{'status_message'} ? : 1 0 1
$opts{'version'} ? : 1 0 1
Condition100%2/2
$opts{"trace_id"} // croak("langfuse_span requires trace_id")
l!l
11
MC/DC100%1/1
$opts{"trace_id"} // croak("langfuse_span requires trace_id")
$opts{"trace_id"}
Truth table100%2/2
A
A= $opts{"trace_id"}
Aresult
11
00
202 },
203 });
204 1 return $id;
205 }
206  
207  
208 3 ▶sub langfuse_update_trace {
Subroutine langfuse_update_trace: called CC=15 SCAR=33.6
Pod documented
209 3 my ( $self, %opts ) = @_;
210 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
211 2 ▶ my $id = $opts{id} // croak("langfuse_update_trace requires id");
Condition100%2/2
$opts{"id"} // croak("langfuse_update_trace requires id")
l!l
11
MC/DC100%1/1
$opts{"id"} // croak("langfuse_update_trace requires id")
$opts{"id"}
Truth table100%2/2
A
A= $opts{"id"}
Aresult
11
00
212 $self->_langfuse_push({
213 id => $self->_langfuse_id,
214 type => 'trace-create',
215 timestamp => $self->_langfuse_timestamp,
216 body => {
217 id => $id,
218 $opts{name} ? ( name => $opts{name} ) : (),
219 $opts{input} ? ( input => $opts{input} ) : (),
220 $opts{output} ? ( output => $opts{output} ) : (),
221 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
222 $opts{tags} ? ( tags => $opts{tags} ) : (),
223 $opts{user_id} ? ( userId => $opts{user_id} ) : (),
224 $opts{session_id} ? ( sessionId => $opts{session_id} ) : (),
225 $opts{release} ? ( release => $opts{release} ) : (),
226 $opts{version} ? ( version => $opts{version} ) : (),
227 defined $opts{public}
228 ? ( public => $opts{public} ? JSON->true : JSON->false ) : (),
229 1 ▶ $opts{environment} ? ( environment => $opts{environment} ) : (),
Branch: 12 branches
BranchTrueFalseTotal
$opts{'name'} ? : 0 1 1
$opts{'input'} ? : 0 1 1
$opts{'output'} ? : 1 0 1
$opts{'metadata'} ? : 1 0 1
$opts{'tags'} ? : 0 1 1
$opts{'user_id'} ? : 0 1 1
$opts{'session_id'} ? : 0 1 1
$opts{'release'} ? : 0 1 1
$opts{'version'} ? : 0 1 1
defined $opts{'public'} ? : 0 1 1
$opts{'public'} ? : 0 0 0
$opts{'environment'} ? : 0 1 1
230 },
231 });
232 1 return $id;
233 }
234  
235  
236 3 ▶sub langfuse_update_span {
Subroutine langfuse_update_span: called CC=9 SCAR=23.9
Pod documented
237 3 my ( $self, %opts ) = @_;
238 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
239 2 ▶ my $id = $opts{id} // croak("langfuse_update_span requires id");
Condition100%2/2
$opts{"id"} // croak("langfuse_update_span requires id")
l!l
11
MC/DC100%1/1
$opts{"id"} // croak("langfuse_update_span requires id")
$opts{"id"}
Truth table100%2/2
A
A= $opts{"id"}
Aresult
11
00
240 $self->_langfuse_push({
241 id => $self->_langfuse_id,
242 type => 'span-update',
243 timestamp => $self->_langfuse_timestamp,
244 body => {
245 id => $id,
246 $opts{trace_id} ? ( traceId => $opts{trace_id} ) : (),
247 $opts{output} ? ( output => $opts{output} ) : (),
248 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
249 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
250 $opts{level} ? ( level => $opts{level} ) : (),
251 1 ▶ $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
Branch: 6 branches
BranchTrueFalseTotal
$opts{'trace_id'} ? : 0 1 1
$opts{'output'} ? : 1 0 1
$opts{'metadata'} ? : 0 1 1
$opts{'end_time'} ? : 1 0 1
$opts{'level'} ? : 1 0 1
$opts{'status_message'} ? : 1 0 1
252 },
253 });
254 1 return $id;
255 }
256  
257  
258 3 ▶sub langfuse_update_generation {
Subroutine langfuse_update_generation: called CC=11 SCAR=27.1
Pod documented
259 3 my ( $self, %opts ) = @_;
260 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
261 2 ▶ my $id = $opts{id} // croak("langfuse_update_generation requires id");
Condition100%2/2
$opts{"id"} // croak("langfuse_update_generation requires id")
l!l
11
MC/DC100%1/1
$opts{"id"} // croak("langfuse_update_generation requires id")
$opts{"id"}
Truth table100%2/2
A
A= $opts{"id"}
Aresult
11
00
262 $self->_langfuse_push({
263 id => $self->_langfuse_id,
264 type => 'generation-update',
265 timestamp => $self->_langfuse_timestamp,
266 body => {
267 id => $id,
268 $opts{trace_id} ? ( traceId => $opts{trace_id} ) : (),
269 $opts{output} ? ( output => $opts{output} ) : (),
270 $opts{usage} ? ( usage => $opts{usage} ) : (),
271 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
272 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
273 $opts{level} ? ( level => $opts{level} ) : (),
274 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
275 defined $opts{completion_start_time}
276 1 ▶ ? ( completionStartTime => $opts{completion_start_time} ) : (),
Branch: 8 branches
BranchTrueFalseTotal
$opts{'trace_id'} ? : 0 1 1
$opts{'output'} ? : 1 0 1
$opts{'usage'} ? : 1 0 1
$opts{'metadata'} ? : 0 1 1
$opts{'end_time'} ? : 1 0 1
$opts{'level'} ? : 1 0 1
$opts{'status_message'} ? : 1 0 1
defined $opts{'completion_start_time'} ? : 1 0 1
277 },
278 });
279 1 return $id;
280 }
281  
282  
283 195 has langfuse_timeout => (
284 is => 'ro',
285 isa => 'Num',
286 default => 10,
287 );
288  
289  
290 195 has langfuse_flush_batch_size => (
291 is => 'ro',
292 isa => 'Int',
293 default => 100,
294 );
295  
296  
297 # --- Ingestion transport (karr k303) -----------------------------------------
298 # The helpers below use no engine state and are called as class methods, so
299 # Langertha::Plugin::Langfuse shares them instead of carrying a copy.
300  
301 17 ▶sub _langfuse_ingestion_request {
Subroutine _langfuse_ingestion_request: called CC=1 SCAR=0.0
302 17 my ( $class, %args ) = @_;
303 17 require HTTP::Request;
304 17 my $auth = encode_base64( $args{public_key} . ':' . $args{secret_key}, '' );
305 return HTTP::Request->new(
306 POST => $args{url} . '/api/public/ingestion',
307 [
308 'Content-Type' => 'application/json',
309 'Authorization' => 'Basic ' . $auth,
310 ],
311 17 $args{json}->encode({ batch => $args{events} }),
312 );
313 }
314  
315 # Sends @{$args{chunks}} one request after another and returns a Future of
316 # the responses; it never fails. $args{engine} (anything with
317 # _async_do_request_f) carries the request on its async backend with the
318 # short timeout; without one, or when that backend is the synchronous LWP
319 # shim (whose user agent has the provider's timeout), a dedicated LWP agent
320 # with the short timeout does. A transport failure (timeout, refused) stops
321 # the flush: the remaining chunks would only wait out the same timeout.
322 13 ▶async sub _langfuse_send_chunks_f {
Subroutine _langfuse_send_chunks_f: called CC=6 SCAR=17.9
323 13 my ( $class, %args ) = @_;
324 13 my @chunks = @{ $args{chunks} };
325 13 my @responses;
326 13 ▶ while ( my $chunk = shift @chunks ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $chunk = shift @chunks) 17 12 29
327 17 my $request = $class->_langfuse_ingestion_request( %args, events => $chunk );
328 17 my $response = await $class->_langfuse_send_f( $args{engine}, $request, %args );
329 17 push @responses, $response;
330 17 $class->_langfuse_check_ingestion( $response, scalar @$chunk );
331 17 ▶ if ( @chunks && ( $response->header('Client-Warning') // '' ) eq 'Internal response' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@chunks and ($response->header("Client-Warning") // "") eq "Internal response") 1 16 17
Condition100%5/5
@chunks and ($response->header("Client-Warning") // "") eq "Internal response"
!ll&&!rl&&r
1241
$response->header("Client-Warning") // ""
l!l
14
MC/DC100%2/2
@chunks and ($response->header("Client-Warning") // "") eq "Internal response"
@chunks $response->header("Client-Warning")
Truth table100%3/3
A and B
A= @chunksB= $response->header("Client-Warning")
ABresult
0X0
100
111
332 1 my $dropped = 0;
333 1 $dropped += @$_ for @chunks;
334 1 warn "Langfuse ingestion: endpoint unreachable, dropping $dropped more event(s)\n";
335 1 last;
336 }
337 }
338 13 return @responses;
339 195 }
340  
341 17 ▶sub _langfuse_send_f {
Subroutine _langfuse_send_f: called CC=4 SCAR=13.9
342 17 my ( $class, $engine, $request, %args ) = @_;
343 17 ▶ my $http = $engine ? $engine->_async_http : undef;
Branch: 1 branch
BranchTrueFalseTotal
$engine ? : 11 6 17
344 17 ▶ unless ( blessed($http) && !$http->isa('Langertha::Request::SyncHTTP') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($http) and not $http->isa("Langertha::Request::SyncHTTP")) 7 10 17
Condition100%3/3
builtin::blessed($http) and not $http->isa("Langertha::Request::SyncHTTP")
!ll&&!rl&&r
6110
MC/DC100%2/2
builtin::blessed($http) and not $http->isa("Langertha::Request::SyncHTTP")
builtin::blessed($http) not $http->isa("Langertha::Request::SyncHTTP")
Truth table100%3/3
A and not(B)
A= builtin::blessed($http)B= not $http->isa("Langertha::Request::SyncHTTP")
ABresult
0X0
100
111
345 7 require LWP::UserAgent;
346 7 my $ua = LWP::UserAgent->new( agent => $args{agent}, timeout => $args{timeout} );
347 7 return Future->done( $ua->request($request) );
348 }
349 return $engine->_async_do_request_f( request => $request, timeout => $args{timeout} )
350 3 ▶ ->else( sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
351 3 my ( $message ) = @_;
352 3 ▶ $message = ( split /\n/, "$message" )[0] // 'request failed';
Condition50%1/2
(split(/\n/, "$message", 0))[0] // "request failed"
l!l
30
MC/DC0%0/1
(split(/\n/, "$message", 0))[0] // "request failed"
(split(/\n/, "$message", 0))[0]
Truth table50%1/2
A
A= (split(/\n/, "$message", 0))[0]
Aresult
11
00
353 # Same shape LWP gives a transport failure, so both paths report alike.
354 3 require HTTP::Response;
355 3 return Future->done( HTTP::Response->new(
356 500, $message, [ 'Client-Warning' => 'Internal response' ],
357 ) );
358 10 } );
359 }
360  
361 # Warns about what did not arrive; never dies. Langfuse answers a batch with
362 # 207 Multi-Status, listing per-event failures under "errors".
363 17 ▶sub _langfuse_check_ingestion {
Subroutine _langfuse_check_ingestion: called CC=10 SCAR=24.5
364 17 my ( $class, $response, $count ) = @_;
365 17 ▶ unless ( $response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 5 12 17
366 5 warn "Langfuse ingestion failed: " . $response->status_line . " ($count event(s) lost)\n";
367 5 return;
368 }
369 12 ▶ return unless $response->code == 207;
Branch: 1 branch
BranchTrueFalseTotal
unless $response->code == 207 3 9 12
370 9 my $data = eval { JSON::MaybeXS->new( utf8 => 1 )->decode( $response->content ) };
371 9 ▶ my $errors = ref $data eq 'HASH' && ref $data->{errors} eq 'ARRAY' ? $data->{errors} : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' && ref $data->{'errors'} eq 'ARRAY' ? : 9 0 9
Condition33%1/3
ref $data eq "HASH" and ref $data->{"errors"} eq "ARRAY"
!ll&&!rl&&r
009
MC/DC0%0/2
ref $data eq "HASH" and ref $data->{"errors"} eq "ARRAY"
ref $data eq "HASH" ref $data->{"errors"} eq "ARRAY"
Truth table33%1/3
A and B
A= ref $data eq "HASH"B= ref $data->{"errors"} eq "ARRAY"
ABresult
0X0
100
111
372 9 ▶ return unless @$errors;
Branch: 1 branch
BranchTrueFalseTotal
unless @$errors 6 3 9
373 3 ▶ my $first = ref $errors->[0] eq 'HASH' ? $errors->[0] : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $errors->[0] eq 'HASH' ? : 3 0 3
374 3 ▶ my $detail = join ' ', grep { defined && !ref && length } @{$first}{qw( status message )};
Condition33%2/6
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
006
defined $_ and not ref $_
!ll&&!rl&&r
006
MC/DC0%0/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
Truth table25%1/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
375 3 ▶ warn sprintf "Langfuse ingestion: %d of %d event(s) rejected%s\n",
Branch: 1 branch
BranchTrueFalseTotal
length $detail ? : 3 0 3
376 scalar @$errors, $count, length $detail ? " (first: $detail)" : '';
377 3 return;
378 }
379  
380 7 ▶sub _langfuse_flush_args {
Subroutine _langfuse_flush_args: called CC=4 SCAR=13.9
381 7 my ( $self ) = @_;
382 7 my @events = @{ $self->_langfuse_batch };
383 7 ▶ return unless @events;
Branch: 1 branch
BranchTrueFalseTotal
unless @events 1 6 7
384 6 $self->_langfuse_batch([]);
385 6 my $size = $self->langfuse_flush_batch_size;
386 6 ▶ $size = 1 if $size < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $size < 1 0 6 6
387 6 my @chunks;
388 6 ▶ push @chunks, [ splice @events, 0, $size ] while @events;
Branch: 1 branch
BranchTrueFalseTotal
@events and do { push @chunks, [splice(@events, 0, $size)] } 10 6 16
389 return (
390 6 chunks => \@chunks,
391 url => $self->langfuse_url,
392 public_key => $self->langfuse_public_key,
393 secret_key => $self->langfuse_secret_key,
394 json => $self->json,
395 agent => 'Langertha-Langfuse/' . $VERSION,
396 timeout => $self->langfuse_timeout,
397 );
398 }
399  
400 4 ▶sub langfuse_flush {
Subroutine langfuse_flush: called CC=3 SCAR=11.0
Pod documented
401 4 my ( $self ) = @_;
402 4 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 0 4 4
403 4 ▶ my %args = $self->_langfuse_flush_args or return;
Branch: 1 branch
BranchTrueFalseTotal
my(%args) = $self->_langfuse_flush_args or return 3 1 4
404 3 my @responses = __PACKAGE__->_langfuse_send_chunks_f(%args)->get;
405 3 return $responses[-1];
406 }
407  
408  
409 3 ▶async sub langfuse_flush_f {
Subroutine langfuse_flush_f: called CC=3 SCAR=11.3
Pod documented
410 3 my ( $self ) = @_;
411 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 0 3 3
412 3 ▶ my %args = $self->_langfuse_flush_args or return;
Branch: 1 branch
BranchTrueFalseTotal
my(%args) = $self->_langfuse_flush_args or return 3 0 3
413 3 return await __PACKAGE__->_langfuse_send_chunks_f( %args, engine => $self );
414 195 }
415  
416  
417 # Auto-instrumentation: wraps simple_chat to record a trace and generation
418 # for every call when Langfuse is enabled.
419  
420 # Returns an ISO-8601 timestamp (UTC, ms resolution) at
421 # $start_hires + $delta_seconds. Used to compute endTime /
422 # completionStartTime from a client-measured total_seconds / ttft_seconds
423 # carried on a Langertha::Response, anchored to the moment the simple_chat
424 # wrapper entered — not to wall-clock now, which has already advanced
425 # past end. Sub-millisecond precision in the underlying hires time is
426 # rounded to whole milliseconds to match the rest of Langfuse timestamp
427 # formatting.
428 18 ▶sub _langfuse_iso_after {
Subroutine _langfuse_iso_after: called CC=3 SCAR=11.0
429 18 my ( $self, $start_hires, $delta_seconds ) = @_;
430 # Guard against clock skew / monotonic drift producing a negative delta
431 # (Perl's % preserves sign on negatives, which would yield a negative $us
432 # and an out-of-range millisecond field below). Clamp to zero — better
433 # to report a same-instant end_time than a wall-clock trip into the past.
434 18 ▶ $delta_seconds = 0 if $delta_seconds < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $delta_seconds < 0 3 15 18
435 18 my ($s, $us) = @$start_hires;
436 18 my $delta_us = $delta_seconds * 1_000_000;
437 18 $s += int( ($us + $delta_us) / 1_000_000 );
438 18 $us = int( ($us + $delta_us) % 1_000_000 );
439 18 ▶ $us = 0 if $us < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $us < 0 0 18 18
440 18 my @t = gmtime($s);
441 18 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
442 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
443 }
444  
445 64 ▶around simple_chat => sub {
Subroutine __ANON__: called CC=14 SCAR=51.7
446 64 my ( $orig, $self, @messages ) = @_;
447 64 ▶ return $self->$orig(@messages) unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 64 0 64
448  
449 0 my $start = [gettimeofday];
450 0 my $start_time = $self->_langfuse_timestamp;
451  
452 0 my $response = $self->$orig(@messages);
453  
454 0 my $t1 = $self->_langfuse_timestamp;
455 0 my $end_time = $t1;
456  
457 # Build usage from Response if available
458 0 my $usage;
459 0 ▶ if (ref $response && $response->isa('Langertha::Response') && $response->has_usage) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $response and $response->isa("Langertha::Response") and $response->has_usage) 0 0 0
Condition0%0/6
ref $response and $response->isa("Langertha::Response") and $response->has_usage
!ll&&!rl&&r
000
ref $response and $response->isa("Langertha::Response")
!ll&&!rl&&r
000
MC/DC0%0/3
ref $response and $response->isa("Langertha::Response") and $response->has_usage
ref $response $response->isa("Langertha::Response") $response->has_usage
Truth table0%0/4
A and B and C
A= ref $responseB= $response->isa("Langertha::Response")C= $response->has_usage
ABCresult
0XX0
10X0
1100
1111
460 0 $usage = {
461 input => $response->prompt_tokens,
462 output => $response->completion_tokens,
463 total => $response->total_tokens,
464 };
465 }
466  
467 # Prefer response-side timing (carries total_seconds and optionally
468 # ttft_seconds) when available. Both are deltas measured from the
469 # same anchor as our wrapper's $start — anchor end / completion_start
470 # to that anchor so the generation event spans the real call window
471 # rather than drifting into the future.
472 0 my $completion_start_time;
473 0 ▶ if (ref $response && $response->isa('Langertha::Response')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $response and $response->isa("Langertha::Response")) 0 0 0
Condition0%0/3
ref $response and $response->isa("Langertha::Response")
!ll&&!rl&&r
000
MC/DC0%0/2
ref $response and $response->isa("Langertha::Response")
ref $response $response->isa("Langertha::Response")
Truth table0%0/3
A and B
A= ref $responseB= $response->isa("Langertha::Response")
ABresult
0X0
100
111
474 0 ▶ if ($response->has_total) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->has_total) 0 0 0
475 0 $end_time = $self->_langfuse_iso_after($start, $response->total_seconds);
476 }
477 0 ▶ if ($response->has_ttft) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->has_ttft) 0 0 0
478 0 $completion_start_time = $self->_langfuse_iso_after($start, $response->ttft_seconds);
479 }
480 }
481  
482 0 my $trace_id = $self->langfuse_trace(
483 name => 'simple_chat',
484 input => \@messages,
485 output => "$response",
486 );
487  
488 0 ▶ $self->langfuse_generation(
Branch: 3 branches
BranchTrueFalseTotal
ref $response && $response->isa('Langertha::Response') && $response->has_model ? : 0 0 0
defined $completion_start_time ? : 0 0 0
$usage ? : 0 0 0
Condition0%0/6
ref $response and $response->isa("Langertha::Response") and $response->has_model
!ll&&!rl&&r
000
ref $response and $response->isa("Langertha::Response")
!ll&&!rl&&r
000
MC/DC0%0/3
ref $response and $response->isa("Langertha::Response") and $response->has_model
ref $response $response->isa("Langertha::Response") $response->has_model
Truth table0%0/4
A and B and C
A= ref $responseB= $response->isa("Langertha::Response")C= $response->has_model
ABCresult
0XX0
10X0
1100
1111
489 trace_id => $trace_id,
490 name => 'chat',
491 model => (ref $response && $response->isa('Langertha::Response') && $response->has_model)
492 ? $response->model : $self->chat_model,
493 input => \@messages,
494 output => "$response",
495 start_time => $start_time,
496 end_time => $end_time,
497 defined $completion_start_time ? ( completion_start_time => $completion_start_time ) : (),
498 $usage ? ( usage => $usage ) : (),
499 );
500  
501 0 return $response;
502 195 };
503  
504  
505 195 1;
506  
507 __END__
« blib/lib/Langertha/Role/OpenAICompatible.pm ↑ Summary blib/lib/Langertha/Role/AnthropicCompatible.pm »