Langertha/Role/Langfuse.pm

filter: Statementstmt 86.5% 90 / 104 Branchbran 64.4% 98 / 152 Conditioncond 38.1% 21 / 55 MC/DCmcdc 8.8% 3 / 34 Subroutinesub 89.4% 17 / 19 Podpod 100% 7 / 7 totaltotal 63.6% 236 / 371 CC 96 SCAR 31.0
CC
96
Cov
67%
__ANON__
90.0
langfuse_update_trace
29.4
langfuse_span
25.0
CRAP 22.1
« Langertha/Engine/Ollama.pm ↑ Summary Langertha/Engine/AnthropicBase.pm »
1 package Langertha::Role::Langfuse;
2 # ABSTRACT: Langfuse observability integration
3 33 our $VERSION = '0.502';
4 33 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 33 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 33 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 33 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 33 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10  
11 33 has langfuse_public_key => (
12 is => 'ro',
13 isa => 'Str',
14 predicate => 'has_langfuse_public_key',
15 );
16  
17  
18 33 has langfuse_secret_key => (
19 is => 'ro',
20 isa => 'Str',
21 predicate => 'has_langfuse_secret_key',
22 );
23  
24  
25 has langfuse_url => (
26 is => 'ro',
27 isa => 'Str',
28 lazy => 1,
29 0 ▶ default => sub { $ENV{LANGFUSE_URL} || 'https://cloud.langfuse.com' },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"LANGFUSE_URL"} or "https://cloud.langfuse.com" 0 0 0
30 33 );
31  
32  
33 33 has langfuse_enabled => (
34 is => 'ro',
35 isa => 'Bool',
36 lazy => 1,
37 builder => '_build_langfuse_enabled',
38 );
39  
40  
41 sub _build_langfuse_enabled {
42 3 ▶ my ( $self ) = @_;
Subroutine _build_langfuse_enabled: called CC=5 SCAR=16.5
43 # Enabled if keys are passed directly or via env vars
44 3 ▶ my $pub = $self->has_langfuse_public_key || $ENV{LANGFUSE_PUBLIC_KEY};
Condition66%2/3
$self->has_langfuse_public_key || $ENV{'LANGFUSE_PUBLIC_KEY'}
l!l&&r!l&&!r
201
MC/DC50%1/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
45 3 ▶ my $sec = $self->has_langfuse_secret_key || $ENV{LANGFUSE_SECRET_KEY};
Condition66%2/3
$self->has_langfuse_secret_key || $ENV{'LANGFUSE_SECRET_KEY'}
l!l&&r!l&&!r
201
MC/DC50%1/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
46 3 ▶ return $pub && $sec ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$pub && $sec ? : 2 1 3
Condition66%2/3
$pub and $sec
!ll&&!rl&&r
102
MC/DC50%1/2
$pub and $sec
$pub $sec
Truth table66%2/3
A and B
A= $pubB= $sec
ABresult
0X0
100
111
47 }
48  
49 around BUILDARGS => sub {
50 244 ▶ my ( $orig, $class, %args ) = @_;
Subroutine __ANON__: called CC=5 SCAR=22.7
51 # Auto-populate from env vars if not passed
52 $args{langfuse_public_key} //= $ENV{LANGFUSE_PUBLIC_KEY}
53 244 ▶ if $ENV{LANGFUSE_PUBLIC_KEY};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"LANGFUSE_PUBLIC_KEY"} 0 244 244
Condition0%0/3
$args{"langfuse_public_key"} //= $ENV{"LANGFUSE_PUBLIC_KEY"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"langfuse_public_key"} //= $ENV{"LANGFUSE_PUBLIC_KEY"}
$args{"langfuse_public_key"} $ENV{"LANGFUSE_PUBLIC_KEY"}
Truth table0%0/3
A //= B
A= $args{"langfuse_public_key"}B= $ENV{"LANGFUSE_PUBLIC_KEY"}
ABresult
1X1
011
000
54 $args{langfuse_secret_key} //= $ENV{LANGFUSE_SECRET_KEY}
55 244 ▶ if $ENV{LANGFUSE_SECRET_KEY};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"LANGFUSE_SECRET_KEY"} 0 244 244
Condition0%0/3
$args{"langfuse_secret_key"} //= $ENV{"LANGFUSE_SECRET_KEY"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"langfuse_secret_key"} //= $ENV{"LANGFUSE_SECRET_KEY"}
$args{"langfuse_secret_key"} $ENV{"LANGFUSE_SECRET_KEY"}
Truth table0%0/3
A //= B
A= $args{"langfuse_secret_key"}B= $ENV{"LANGFUSE_SECRET_KEY"}
ABresult
1X1
011
000
56 244 return $class->$orig(%args);
57 33 };
58  
59 has _langfuse_batch => (
60 is => 'rw',
61 isa => 'ArrayRef',
62 244 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
63 33 );
64  
65 sub _langfuse_id {
66 19 ▶ my ( $self ) = @_;
Subroutine _langfuse_id: called CC=1 SCAR=0.0
67 # Simple UUID v4 generation without external dependency
68 19 my @hex = map { sprintf("%04x", int(rand(65536))) } 1..8;
69 19 return join('-',
70 $hex[0].$hex[1],
71 $hex[2],
72 '4'.substr($hex[3], 1), # version 4
73 sprintf("%x", 8 + int(rand(4))).substr($hex[4], 1), # variant
74 $hex[5].$hex[6].$hex[7],
75 );
76 }
77  
78 sub _langfuse_timestamp {
79 11 ▶ my ( $self ) = @_;
Subroutine _langfuse_timestamp: called CC=1 SCAR=0.0
80 11 my ($s, $us) = gettimeofday;
81 11 my @t = gmtime($s);
82 11 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
83 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
84 }
85  
86 sub langfuse_trace {
87 4 ▶ my ( $self, %opts ) = @_;
Subroutine langfuse_trace: called CC=15 SCAR=27.3
Pod documented
88 4 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 3 4
89 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
90 3 ▶ push @{$self->_langfuse_batch}, {
Branch: 11 branches
BranchTrueFalseTotal
$opts{'input'} ? : 2 1 3
$opts{'output'} ? : 1 2 3
$opts{'metadata'} ? : 0 3 3
$opts{'tags'} ? : 1 2 3
$opts{'user_id'} ? : 1 2 3
$opts{'session_id'} ? : 1 2 3
$opts{'release'} ? : 1 2 3
$opts{'version'} ? : 1 2 3
defined $opts{'public'} ? : 2 1 3
$opts{'public'} ? : 1 1 2
$opts{'environment'} ? : 1 2 3
Condition50%1/2
$opts{"name"} // "langfuse-trace"
l!l
30
MC/DC0%0/1
$opts{"name"} // "langfuse-trace"
$opts{"name"}
Truth table50%1/2
A
A= $opts{"name"}
Aresult
11
00
91 id => $self->_langfuse_id,
92 type => 'trace-create',
93 timestamp => $self->_langfuse_timestamp,
94 body => {
95 id => $id,
96 name => $opts{name} // 'langfuse-trace',
97 $opts{input} ? ( input => $opts{input} ) : (),
98 $opts{output} ? ( output => $opts{output} ) : (),
99 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
100 $opts{tags} ? ( tags => $opts{tags} ) : (),
101 $opts{user_id} ? ( userId => $opts{user_id} ) : (),
102 $opts{session_id} ? ( sessionId => $opts{session_id} ) : (),
103 $opts{release} ? ( release => $opts{release} ) : (),
104 $opts{version} ? ( version => $opts{version} ) : (),
105 defined $opts{public}
106 ? ( public => $opts{public} ? JSON::MaybeXS->true : JSON::MaybeXS->false ) : (),
107 3 $opts{environment} ? ( environment => $opts{environment} ) : (),
108 },
109 };
110 3 return $id;
111 }
112  
113  
114 sub langfuse_generation {
115 4 ▶ my ( $self, %opts ) = @_;
Subroutine langfuse_generation: called CC=17 SCAR=28.9
Pod documented
116 4 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 3 4
117 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
118 3 ▶ push @{$self->_langfuse_batch}, {
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
Condition60%3/5
$opts{"trace_id"} // croak("langfuse_generation requires trace_id")
l!l&&r!l&&!r
210
$opts{"name"} // "generation"
l!l
20
MC/DC0%0/2
$opts{"trace_id"} // croak("langfuse_generation requires trace_id")
$opts{"trace_id"} croak("langfuse_generation requires trace_id")
MC/DC0%0/1
$opts{"name"} // "generation"
$opts{"name"}
Truth table33%1/3
A // B
A= $opts{"trace_id"}B= croak("langfuse_generation requires trace_id")
ABresult
1X1
011
000
Truth table50%1/2
A
A= $opts{"name"}
Aresult
11
00
119 id => $self->_langfuse_id,
120 type => 'generation-create',
121 timestamp => $self->_langfuse_timestamp,
122 body => {
123 id => $id,
124 traceId => $opts{trace_id} // croak("langfuse_generation requires trace_id"),
125 name => $opts{name} // 'generation',
126 model => $opts{model},
127 $opts{input} ? ( input => $opts{input} ) : (),
128 $opts{output} ? ( output => $opts{output} ) : (),
129 $opts{usage} ? ( usage => $opts{usage} ) : (),
130 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
131 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
132 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
133 defined $opts{completion_start_time}
134 ? ( completionStartTime => $opts{completion_start_time} ) : (),
135 $opts{parent_observation_id}
136 ? ( parentObservationId => $opts{parent_observation_id} ) : (),
137 $opts{model_parameters}
138 ? ( modelParameters => $opts{model_parameters} ) : (),
139 $opts{level} ? ( level => $opts{level} ) : (),
140 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
141 3 $opts{version} ? ( version => $opts{version} ) : (),
142 },
143 };
144 2 return $id;
145 }
146  
147  
148 sub langfuse_span {
149 3 ▶ my ( $self, %opts ) = @_;
Subroutine langfuse_span: called CC=14 SCAR=32.2
Pod documented
150 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
151 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
152 2 ▶ push @{$self->_langfuse_batch}, {
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
Condition66%2/3
$opts{"trace_id"} // croak("langfuse_span requires trace_id")
l!l&&r!l&&!r
101
MC/DC0%0/2
$opts{"trace_id"} // croak("langfuse_span requires trace_id")
$opts{"trace_id"} croak("langfuse_span requires trace_id")
Truth table33%1/3
A // B
A= $opts{"trace_id"}B= croak("langfuse_span requires trace_id")
ABresult
1X1
011
000
153 id => $self->_langfuse_id,
154 type => 'span-create',
155 timestamp => $self->_langfuse_timestamp,
156 body => {
157 id => $id,
158 traceId => $opts{trace_id} // croak("langfuse_span requires trace_id"),
159 $opts{name} ? ( name => $opts{name} ) : (),
160 $opts{input} ? ( input => $opts{input} ) : (),
161 $opts{output} ? ( output => $opts{output} ) : (),
162 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
163 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
164 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
165 $opts{parent_observation_id}
166 ? ( parentObservationId => $opts{parent_observation_id} ) : (),
167 $opts{level} ? ( level => $opts{level} ) : (),
168 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
169 2 $opts{version} ? ( version => $opts{version} ) : (),
170 },
171 };
172 1 return $id;
173 }
174  
175  
176 sub langfuse_update_trace {
177 3 ▶ my ( $self, %opts ) = @_;
Subroutine langfuse_update_trace: called CC=15 SCAR=33.8
Pod documented
178 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
179 2 ▶ my $id = $opts{id} // croak("langfuse_update_trace requires id");
Condition66%2/3
$opts{"id"} // croak("langfuse_update_trace requires id")
l!l&&r!l&&!r
101
MC/DC0%0/2
$opts{"id"} // croak("langfuse_update_trace requires id")
$opts{"id"} croak("langfuse_update_trace requires id")
Truth table33%1/3
A // B
A= $opts{"id"}B= croak("langfuse_update_trace requires id")
ABresult
1X1
011
000
180 1 ▶ push @{$self->_langfuse_batch}, {
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
181 id => $self->_langfuse_id,
182 type => 'trace-create',
183 timestamp => $self->_langfuse_timestamp,
184 body => {
185 id => $id,
186 $opts{name} ? ( name => $opts{name} ) : (),
187 $opts{input} ? ( input => $opts{input} ) : (),
188 $opts{output} ? ( output => $opts{output} ) : (),
189 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
190 $opts{tags} ? ( tags => $opts{tags} ) : (),
191 $opts{user_id} ? ( userId => $opts{user_id} ) : (),
192 $opts{session_id} ? ( sessionId => $opts{session_id} ) : (),
193 $opts{release} ? ( release => $opts{release} ) : (),
194 $opts{version} ? ( version => $opts{version} ) : (),
195 defined $opts{public}
196 ? ( public => $opts{public} ? JSON::MaybeXS->true : JSON::MaybeXS->false ) : (),
197 1 $opts{environment} ? ( environment => $opts{environment} ) : (),
198 },
199 };
200 1 return $id;
201 }
202  
203  
204 sub langfuse_update_span {
205 3 ▶ my ( $self, %opts ) = @_;
Subroutine langfuse_update_span: called CC=9 SCAR=24.2
Pod documented
206 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
207 2 ▶ my $id = $opts{id} // croak("langfuse_update_span requires id");
Condition66%2/3
$opts{"id"} // croak("langfuse_update_span requires id")
l!l&&r!l&&!r
101
MC/DC0%0/2
$opts{"id"} // croak("langfuse_update_span requires id")
$opts{"id"} croak("langfuse_update_span requires id")
Truth table33%1/3
A // B
A= $opts{"id"}B= croak("langfuse_update_span requires id")
ABresult
1X1
011
000
208 1 ▶ push @{$self->_langfuse_batch}, {
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
209 id => $self->_langfuse_id,
210 type => 'span-update',
211 timestamp => $self->_langfuse_timestamp,
212 body => {
213 id => $id,
214 $opts{trace_id} ? ( traceId => $opts{trace_id} ) : (),
215 $opts{output} ? ( output => $opts{output} ) : (),
216 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
217 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
218 $opts{level} ? ( level => $opts{level} ) : (),
219 1 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
220 },
221 };
222 1 return $id;
223 }
224  
225  
226 sub langfuse_update_generation {
227 3 ▶ my ( $self, %opts ) = @_;
Subroutine langfuse_update_generation: called CC=11 SCAR=27.4
Pod documented
228 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
229 2 ▶ my $id = $opts{id} // croak("langfuse_update_generation requires id");
Condition66%2/3
$opts{"id"} // croak("langfuse_update_generation requires id")
l!l&&r!l&&!r
101
MC/DC0%0/2
$opts{"id"} // croak("langfuse_update_generation requires id")
$opts{"id"} croak("langfuse_update_generation requires id")
Truth table33%1/3
A // B
A= $opts{"id"}B= croak("langfuse_update_generation requires id")
ABresult
1X1
011
000
230 1 ▶ push @{$self->_langfuse_batch}, {
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
231 id => $self->_langfuse_id,
232 type => 'generation-update',
233 timestamp => $self->_langfuse_timestamp,
234 body => {
235 id => $id,
236 $opts{trace_id} ? ( traceId => $opts{trace_id} ) : (),
237 $opts{output} ? ( output => $opts{output} ) : (),
238 $opts{usage} ? ( usage => $opts{usage} ) : (),
239 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
240 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
241 $opts{level} ? ( level => $opts{level} ) : (),
242 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
243 defined $opts{completion_start_time}
244 1 ? ( completionStartTime => $opts{completion_start_time} ) : (),
245 },
246 };
247 1 return $id;
248 }
249  
250  
251 sub langfuse_flush {
252 2 ▶ my ( $self ) = @_;
Subroutine langfuse_flush: called CC=4 SCAR=14.0
Pod documented
253 2 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 0 2 2
254 2 my $batch = $self->_langfuse_batch;
255 2 ▶ return unless @$batch;
Branch: 1 branch
BranchTrueFalseTotal
unless @$batch 1 1 2
256  
257 1 require LWP::UserAgent;
258 1 my $ua = LWP::UserAgent->new(agent => 'Langertha-Langfuse/'.$VERSION);
259  
260 1 my $auth = encode_base64(
261 $self->langfuse_public_key . ':' . $self->langfuse_secret_key, ''
262 );
263  
264 1 my $body = $self->json->encode({ batch => $batch });
265  
266 1 my $request = HTTP::Request->new(
267 POST => $self->langfuse_url . '/api/public/ingestion',
268 [
269 'Content-Type' => 'application/json',
270 'Authorization' => 'Basic ' . $auth,
271 ],
272 $body,
273 );
274  
275 1 my $response = $ua->request($request);
276 1 $self->_langfuse_batch([]);
277  
278 1 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 1 1
279 0 warn "Langfuse ingestion failed: " . $response->status_line;
280 }
281  
282 1 return $response;
283 }
284  
285  
286 # Auto-instrumentation: wraps simple_chat to record a trace and generation
287 # for every call when Langfuse is enabled.
288  
289 around simple_chat => sub {
290 0 ▶ my ( $orig, $self, @messages ) = @_;
Subroutine __ANON__: not called CC=9 SCAR=45.0
291 0 ▶ return $self->$orig(@messages) unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 0 0 0
292  
293 0 my $t0 = $self->_langfuse_timestamp;
294 0 my $start = [gettimeofday];
295  
296 0 my $response = $self->$orig(@messages);
297  
298 0 my $t1 = $self->_langfuse_timestamp;
299  
300 # Build usage from Response if available
301 0 my $usage;
302 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
303 0 $usage = {
304 input => $response->prompt_tokens,
305 output => $response->completion_tokens,
306 total => $response->total_tokens,
307 };
308 }
309  
310 0 my $trace_id = $self->langfuse_trace(
311 name => 'simple_chat',
312 input => \@messages,
313 output => "$response",
314 );
315  
316 0 ▶ $self->langfuse_generation(
Branch: 2 branches
BranchTrueFalseTotal
ref $response && $response->isa('Langertha::Response') && $response->has_model ? : 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
317 trace_id => $trace_id,
318 name => 'chat',
319 model => (ref $response && $response->isa('Langertha::Response') && $response->has_model)
320 ? $response->model : $self->chat_model,
321 input => \@messages,
322 output => "$response",
323 start_time => $t0,
324 end_time => $t1,
325 $usage ? ( usage => $usage ) : (),
326 );
327  
328 0 return $response;
329 33 };
330  
331  
332 33 1;
333  
334 __END__
335  
336 =pod
337  
338 =encoding UTF-8
339  
340 =head1 NAME
341  
342 Langertha::Role::Langfuse - Langfuse observability integration
343  
344 =head1 VERSION
345  
346 version 0.502
347  
348 =head1 SYNOPSIS
349  
350 Langfuse is built into every Langertha engine. Just set the env vars:
351  
352 export LANGFUSE_PUBLIC_KEY=pk-lf-...
353 export LANGFUSE_SECRET_KEY=sk-lf-...
354 export LANGFUSE_URL=http://localhost:3000 # optional, defaults to cloud
355  
356 Then use any engine as normal — C<simple_chat> is auto-traced:
357  
358 use Langertha::Engine::OpenAI;
359  
360 my $engine = Langertha::Engine::OpenAI->new(
361 api_key => $ENV{OPENAI_API_KEY},
362 model => 'gpt-4o-mini',
363 );
364  
365 my $response = $engine->simple_chat('Hello!');
366 $engine->langfuse_flush; # send events to Langfuse
367  
368 Or pass keys explicitly:
369  
370 my $engine = Langertha::Engine::Anthropic->new(
371 api_key => $ENV{ANTHROPIC_API_KEY},
372 langfuse_public_key => 'pk-lf-...',
373 langfuse_secret_key => 'sk-lf-...',
374 langfuse_url => 'http://localhost:3000',
375 );
376  
377 Manual traces for custom workflows:
378  
379 my $trace_id = $engine->langfuse_trace(
380 name => 'my-workflow',
381 input => { query => 'custom input' },
382 );
383  
384 $engine->langfuse_generation(
385 trace_id => $trace_id,
386 name => 'step-1',
387 model => 'gpt-4o',
388 input => 'prompt text',
389 output => 'response text',
390 usage => { input => 10, output => 5, total => 15 },
391 );
392  
393 $engine->langfuse_flush;
394  
395 =head1 DESCRIPTION
396  
397 This role integrates Langertha engines with L<Langfuse|https://langfuse.com/>,
398 an open-source observability platform for LLM applications. It is composed
399 into L<Langertha::Role::Chat>, so B<every engine has Langfuse support built in>.
400  
401 B<Features:>
402  
403 =over 4
404  
405 =item * Zero-config via environment variables
406  
407 =item * Auto-instrumentation of C<simple_chat> calls
408  
409 =item * Manual trace and generation event creation
410  
411 =item * Batched event ingestion via Langfuse REST API
412  
413 =item * Basic Auth using public/secret key pair
414  
415 =item * Disabled by default — only active when both keys are set
416  
417 =back
418  
419 B<Langfuse concepts:>
420  
421 =over 4
422  
423 =item * B<Trace> — Top-level unit of work (a request, a conversation turn)
424  
425 =item * B<Span> — A grouping of work within a trace (an iteration, a tool call)
426  
427 =item * B<Generation> — A single LLM call within a trace (with model, usage, timing)
428  
429 =back
430  
431 B<Hierarchy:> Traces contain spans and generations. Spans can nest via
432 C<parent_observation_id>. All observations can be updated after creation.
433  
434 =head2 langfuse_public_key
435  
436 Your Langfuse project public key. Auto-populated from C<LANGFUSE_PUBLIC_KEY>
437 environment variable if not passed.
438  
439 =head2 langfuse_secret_key
440  
441 Your Langfuse project secret key. Auto-populated from C<LANGFUSE_SECRET_KEY>
442 environment variable if not passed.
443  
444 =head2 langfuse_url
445  
446 Langfuse API URL. Defaults to C<LANGFUSE_URL> env var, or
447 C<https://cloud.langfuse.com> if not set. Set this to your
448 self-hosted instance URL (e.g. C<http://localhost:3000>).
449  
450 =head2 langfuse_enabled
451  
452 Bool indicating whether Langfuse integration is active. Lazy — defaults
453 to true when both public and secret keys are available (from constructor
454 or environment variables).
455  
456 =head2 langfuse_trace
457  
458 my $trace_id = $engine->langfuse_trace(
459 name => 'my-trace',
460 input => { ... },
461 output => '...',
462 metadata => { ... },
463 tags => ['tag1', 'tag2'],
464 user_id => 'user-123',
465 session_id => 'session-abc',
466 release => '1.0.0',
467 version => '1',
468 public => 1,
469 environment => 'production',
470 );
471  
472 Creates a trace event. Returns the trace ID for linking generations and
473 spans. Accepts optional C<tags>, C<user_id>, C<session_id>, C<release>,
474 C<version>, C<public>, and C<environment> fields. Calling with the same
475 C<id> upserts (updates) the trace.
476  
477 =head2 langfuse_generation
478  
479 $engine->langfuse_generation(
480 trace_id => $trace_id,
481 name => 'chat',
482 model => 'gpt-4o',
483 input => '...',
484 output => '...',
485 usage => { input => 10, output => 5, total => 15 },
486 start_time => $iso_timestamp,
487 end_time => $iso_timestamp,
488 parent_observation_id => $span_id,
489 model_parameters => { temperature => 0.7, max_tokens => 1000 },
490 level => 'DEFAULT',
491 status_message => 'OK',
492 version => '1',
493 );
494  
495 Creates a generation event linked to a trace. C<trace_id> is required.
496 Accepts optional C<parent_observation_id> for nesting under a span,
497 C<model_parameters>, C<level> (DEBUG/DEFAULT/WARNING/ERROR),
498 C<status_message>, and C<version>.
499  
500 =head2 langfuse_span
501  
502 my $span_id = $engine->langfuse_span(
503 trace_id => $trace_id,
504 name => 'my-span',
505 input => { ... },
506 output => '...',
507 start_time => $iso_timestamp,
508 end_time => $iso_timestamp,
509 parent_observation_id => $parent_span_id,
510 metadata => { ... },
511 level => 'DEFAULT',
512 status_message => 'OK',
513 version => '1',
514 );
515  
516 Creates a span event for grouping work within a trace. C<trace_id> is
517 required. Returns the span ID. Spans can be nested via
518 C<parent_observation_id>.
519  
520 =head2 langfuse_update_trace
521  
522 $engine->langfuse_update_trace(
523 id => $trace_id,
524 output => 'final result',
525 metadata => { ... },
526 );
527  
528 Updates a trace by upserting with the same C<id>. Uses C<trace-create>
529 event type (Langfuse upserts on matching body ID). C<id> is required.
530  
531 =head2 langfuse_update_span
532  
533 $engine->langfuse_update_span(
534 id => $span_id,
535 end_time => $iso_timestamp,
536 output => { ... },
537 );
538  
539 Updates an existing span. C<id> is required. Use this to set C<end_time>
540 and C<output> after the span's work completes.
541  
542 =head2 langfuse_update_generation
543  
544 $engine->langfuse_update_generation(
545 id => $gen_id,
546 output => 'final response text',
547 usage => { input => 100, output => 50, total => 150 },
548 );
549  
550 Updates an existing generation. C<id> is required. Use this to add
551 C<output>, C<usage>, and C<end_time> after the LLM call completes.
552  
553 =head2 langfuse_flush
554  
555 $engine->langfuse_flush;
556  
557 Sends all batched events to the Langfuse ingestion API. Clears the batch
558 after sending. Warns on HTTP errors but does not die.
559  
560 =head1 ENVIRONMENT VARIABLES
561  
562 =over 4
563  
564 =item C<LANGFUSE_PUBLIC_KEY> — Auto-populates C<langfuse_public_key>
565  
566 =item C<LANGFUSE_SECRET_KEY> — Auto-populates C<langfuse_secret_key>
567  
568 =item C<LANGFUSE_URL> — Auto-populates C<langfuse_url> (default: C<https://cloud.langfuse.com>)
569  
570 =back
571  
572 =head1 SELF-HOSTING LANGFUSE
573  
574 A ready-to-use Kubernetes manifest is included in the distribution:
575  
576 kubectl apply -f ex/langfuse-k8s.yaml
577 kubectl -n langfuse port-forward svc/langfuse-web 3000:3000 &
578  
579 export LANGFUSE_PUBLIC_KEY=pk-lf-langertha
580 export LANGFUSE_SECRET_KEY=sk-lf-langertha
581 export LANGFUSE_URL=http://localhost:3000
582  
583 The manifest pre-creates a project with known API keys so you can send
584 data immediately without going through the web UI.
585  
586 Dashboard: C<http://localhost:3000> (login: C<langertha@test.invalid> / C<langertha>)
587  
588 =head1 GETTING LANGFUSE KEYS
589  
590 For Langfuse Cloud, sign up at L<https://langfuse.com/> and generate
591 API keys in your project settings.
592  
593 =head1 SEE ALSO
594  
595 =over
596  
597 =item * L<https://langfuse.com/docs> - Langfuse documentation
598  
599 =item * L<Langertha::Role::Chat> - Chat role that composes this role
600  
601 =item * L<Langertha::Raider> - Autonomous agent with Langfuse tracing support
602  
603 =back
604  
605 =head1 SUPPORT
606  
607 =head2 Issues
608  
609 Please report bugs and feature requests on GitHub at
610 L<https://github.com/Getty/langertha/issues>.
611  
612 =head2 IRC
613  
614 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
615  
616 =head1 CONTRIBUTING
617  
618 Contributions are welcome! Please fork the repository and submit a pull request.
619  
620 =head1 AUTHOR
621  
622 Torsten Raudssus <getty@cpan.org>
623  
624 =head1 COPYRIGHT AND LICENSE
625  
626 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
627  
628 This is free software; you can redistribute it and/or modify it under
629 the same terms as the Perl 5 programming language system itself.
630  
631 =cut
« Langertha/Engine/Ollama.pm ↑ Summary Langertha/Engine/AnthropicBase.pm »