blib/lib/Langertha/Role/Langfuse.pm

filter: Statementstmt 90.5% 172 / 190 Branchbran 66.8% 131 / 196 Conditioncond 47.5% 38 / 80 MC/DCmcdc 18.7% 9 / 48 Subroutinesub 96.8% 31 / 32 Podpod 100% 9 / 9 totaltotal 70.2% 390 / 555 CC 128 SCAR 33.3
CC
128
Cov
73%
__ANON__
176.8
langfuse_update_trace
30.7
langfuse_span
26.0
CRAP 27.8
« blib/lib/Langertha/Engine/LMStudio.pm ↑ Summary blib/lib/Langertha/Role/OpenAICompatible.pm »
1 package Langertha::Role::Langfuse;
2 # ABSTRACT: Langfuse observability integration
3 180 our $VERSION = '0.503';
4 180 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 180 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 180 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 180 ▶use JSON::MaybeXS qw( JSON );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 180 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 180 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 180 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 180 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 180 has langfuse_public_key => (
15 is => 'ro',
16 isa => 'Str',
17 predicate => 'has_langfuse_public_key',
18 );
19  
20  
21 180 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 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
33 180 );
34  
35  
36 180 has langfuse_enabled => (
37 is => 'ro',
38 isa => 'Bool',
39 lazy => 1,
40 builder => '_build_langfuse_enabled',
41 );
42  
43  
44 18 ▶sub _build_langfuse_enabled {
Subroutine _build_langfuse_enabled: called CC=5 SCAR=16.5
45 18 my ( $self ) = @_;
46 # Enabled if keys are passed directly or via env vars
47 18 ▶ 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
909
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
48 18 ▶ 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
909
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
49 18 ▶ return $pub && $sec ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$pub && $sec ? : 9 9 18
Condition66%2/3
$pub and $sec
!ll&&!rl&&r
909
MC/DC50%1/2
$pub and $sec
$pub $sec
Truth table66%2/3
A and B
A= $pubB= $sec
ABresult
0X0
100
111
50 }
51  
52 3896 ▶around BUILDARGS => sub {
Subroutine __ANON__: called CC=5 SCAR=17.2
53 3896 my ( $orig, $class, %args ) = @_;
54 # Auto-populate from env vars if not passed
55 $args{langfuse_public_key} //= $ENV{LANGFUSE_PUBLIC_KEY}
56 3896 ▶ if $ENV{LANGFUSE_PUBLIC_KEY};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"LANGFUSE_PUBLIC_KEY"} 1 3895 3896
Condition33%1/3
$args{"langfuse_public_key"} //= $ENV{"LANGFUSE_PUBLIC_KEY"}
l!l&&r!l&&!r
010
MC/DC0%0/2
$args{"langfuse_public_key"} //= $ENV{"LANGFUSE_PUBLIC_KEY"}
$args{"langfuse_public_key"} $ENV{"LANGFUSE_PUBLIC_KEY"}
Truth table33%1/3
A //= B
A= $args{"langfuse_public_key"}B= $ENV{"LANGFUSE_PUBLIC_KEY"}
ABresult
1X1
011
000
57 $args{langfuse_secret_key} //= $ENV{LANGFUSE_SECRET_KEY}
58 3896 ▶ if $ENV{LANGFUSE_SECRET_KEY};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"LANGFUSE_SECRET_KEY"} 1 3895 3896
Condition33%1/3
$args{"langfuse_secret_key"} //= $ENV{"LANGFUSE_SECRET_KEY"}
l!l&&r!l&&!r
010
MC/DC0%0/2
$args{"langfuse_secret_key"} //= $ENV{"LANGFUSE_SECRET_KEY"}
$args{"langfuse_secret_key"} $ENV{"LANGFUSE_SECRET_KEY"}
Truth table33%1/3
A //= B
A= $args{"langfuse_secret_key"}B= $ENV{"LANGFUSE_SECRET_KEY"}
ABresult
1X1
011
000
59 3896 return $class->$orig(%args);
60 180 };
61  
62 has _langfuse_batch => (
63 is => 'rw',
64 isa => 'ArrayRef',
65 3896 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
66 180 );
67  
68 180 has langfuse_max_batch => (
69 is => 'ro',
70 isa => 'Int',
71 default => 1000,
72 );
73  
74  
75 # Every event goes through here so the batch stays bounded (karr k305).
76 2032 ▶sub _langfuse_push {
Subroutine _langfuse_push: called CC=4 SCAR=13.9
77 2032 my ( $self, $event ) = @_;
78 2032 my $batch = $self->_langfuse_batch;
79 2032 push @$batch, $event;
80 2032 my $max = $self->langfuse_max_batch;
81 2032 ▶ if ( $max > 0 && @$batch > $max ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max > 0 and @$batch > $max) 7 2025 2032
Condition100%3/3
$max > 0 and @$batch > $max
!ll&&!rl&&r
15005257
MC/DC100%2/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
82 7 splice @$batch, 0, @$batch - $max;
83 7 ▶ unless ( $self->{_langfuse_overflow_warned}++ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_langfuse_overflow_warned"}++) 1 6 7
84 1 warn ref($self) . ": Langfuse batch reached langfuse_max_batch ($max events) "
85 . "without a flush; dropping the oldest events. Call langfuse_flush regularly.\n";
86 }
87 }
88 2032 return;
89 }
90  
91 4065 ▶sub _langfuse_id {
Subroutine _langfuse_id: called CC=1 SCAR=0.0
92 4065 my ( $self ) = @_;
93 # Simple UUID v4 generation without external dependency
94 4065 my @hex = map { sprintf("%04x", int(rand(65536))) } 1..8;
95 4065 return join('-',
96 $hex[0].$hex[1],
97 $hex[2],
98 '4'.substr($hex[3], 1), # version 4
99 sprintf("%x", 8 + int(rand(4))).substr($hex[4], 1), # variant
100 $hex[5].$hex[6].$hex[7],
101 );
102 }
103  
104 2036 ▶sub langfuse_timestamp {
Subroutine langfuse_timestamp: called CC=1 SCAR=0.0
Pod documented
105 2036 my ( $self ) = @_;
106 2036 my ($s, $us) = gettimeofday;
107 2036 my @t = gmtime($s);
108 2036 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
109 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
110 }
111  
112  
113 # Private alias kept for existing callers; the internal call sites use it too.
114 2035 ▶sub _langfuse_timestamp { $_[0]->langfuse_timestamp }
Subroutine _langfuse_timestamp: called CC=1 SCAR=0.0
115  
116 2027 ▶sub langfuse_trace {
Subroutine langfuse_trace: called CC=15 SCAR=27.3
Pod documented
117 2027 my ( $self, %opts ) = @_;
118 2027 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2026 2027
119 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
120 $self->_langfuse_push({
121 id => $self->_langfuse_id,
122 type => 'trace-create',
123 timestamp => $self->_langfuse_timestamp,
124 body => {
125 id => $id,
126 name => $opts{name} // 'langfuse-trace',
127 $opts{input} ? ( input => $opts{input} ) : (),
128 $opts{output} ? ( output => $opts{output} ) : (),
129 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
130 $opts{tags} ? ( tags => $opts{tags} ) : (),
131 $opts{user_id} ? ( userId => $opts{user_id} ) : (),
132 $opts{session_id} ? ( sessionId => $opts{session_id} ) : (),
133 $opts{release} ? ( release => $opts{release} ) : (),
134 $opts{version} ? ( version => $opts{version} ) : (),
135 defined $opts{public}
136 ? ( public => $opts{public} ? JSON->true : JSON->false ) : (),
137 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
138 },
139 });
140 2026 return $id;
141 }
142  
143  
144 4 ▶sub langfuse_generation {
Subroutine langfuse_generation: called CC=17 SCAR=28.9
Pod documented
145 4 my ( $self, %opts ) = @_;
146 4 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 3 4
147 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
148 $self->_langfuse_push({
149 id => $self->_langfuse_id,
150 type => 'generation-create',
151 timestamp => $self->_langfuse_timestamp,
152 body => {
153 id => $id,
154 traceId => $opts{trace_id} // croak("langfuse_generation requires trace_id"),
155 name => $opts{name} // 'generation',
156 model => $opts{model},
157 $opts{input} ? ( input => $opts{input} ) : (),
158 $opts{output} ? ( output => $opts{output} ) : (),
159 $opts{usage} ? ( usage => $opts{usage} ) : (),
160 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
161 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
162 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
163 defined $opts{completion_start_time}
164 ? ( completionStartTime => $opts{completion_start_time} ) : (),
165 $opts{parent_observation_id}
166 ? ( parentObservationId => $opts{parent_observation_id} ) : (),
167 $opts{model_parameters}
168 ? ( modelParameters => $opts{model_parameters} ) : (),
169 $opts{level} ? ( level => $opts{level} ) : (),
170 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
171 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
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
172 },
173 });
174 2 return $id;
175 }
176  
177  
178 3 ▶sub langfuse_span {
Subroutine langfuse_span: called CC=14 SCAR=32.6
Pod documented
179 3 my ( $self, %opts ) = @_;
180 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
181 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
182 $self->_langfuse_push({
183 id => $self->_langfuse_id,
184 type => 'span-create',
185 timestamp => $self->_langfuse_timestamp,
186 body => {
187 id => $id,
188 traceId => $opts{trace_id} // croak("langfuse_span requires trace_id"),
189 $opts{name} ? ( name => $opts{name} ) : (),
190 $opts{input} ? ( input => $opts{input} ) : (),
191 $opts{output} ? ( output => $opts{output} ) : (),
192 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
193 $opts{start_time} ? ( startTime => $opts{start_time} ) : (),
194 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
195 $opts{parent_observation_id}
196 ? ( parentObservationId => $opts{parent_observation_id} ) : (),
197 $opts{level} ? ( level => $opts{level} ) : (),
198 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
199 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
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
200 },
201 });
202 1 return $id;
203 }
204  
205  
206 3 ▶sub langfuse_update_trace {
Subroutine langfuse_update_trace: called CC=15 SCAR=34.2
Pod documented
207 3 my ( $self, %opts ) = @_;
208 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
209 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
210 $self->_langfuse_push({
211 id => $self->_langfuse_id,
212 type => 'trace-create',
213 timestamp => $self->_langfuse_timestamp,
214 body => {
215 id => $id,
216 $opts{name} ? ( name => $opts{name} ) : (),
217 $opts{input} ? ( input => $opts{input} ) : (),
218 $opts{output} ? ( output => $opts{output} ) : (),
219 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
220 $opts{tags} ? ( tags => $opts{tags} ) : (),
221 $opts{user_id} ? ( userId => $opts{user_id} ) : (),
222 $opts{session_id} ? ( sessionId => $opts{session_id} ) : (),
223 $opts{release} ? ( release => $opts{release} ) : (),
224 $opts{version} ? ( version => $opts{version} ) : (),
225 defined $opts{public}
226 ? ( public => $opts{public} ? JSON->true : JSON->false ) : (),
227 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
228 },
229 });
230 1 return $id;
231 }
232  
233  
234 3 ▶sub langfuse_update_span {
Subroutine langfuse_update_span: called CC=9 SCAR=24.5
Pod documented
235 3 my ( $self, %opts ) = @_;
236 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
237 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
238 $self->_langfuse_push({
239 id => $self->_langfuse_id,
240 type => 'span-update',
241 timestamp => $self->_langfuse_timestamp,
242 body => {
243 id => $id,
244 $opts{trace_id} ? ( traceId => $opts{trace_id} ) : (),
245 $opts{output} ? ( output => $opts{output} ) : (),
246 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
247 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
248 $opts{level} ? ( level => $opts{level} ) : (),
249 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
250 },
251 });
252 1 return $id;
253 }
254  
255  
256 3 ▶sub langfuse_update_generation {
Subroutine langfuse_update_generation: called CC=11 SCAR=27.7
Pod documented
257 3 my ( $self, %opts ) = @_;
258 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 1 2 3
259 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
260 $self->_langfuse_push({
261 id => $self->_langfuse_id,
262 type => 'generation-update',
263 timestamp => $self->_langfuse_timestamp,
264 body => {
265 id => $id,
266 $opts{trace_id} ? ( traceId => $opts{trace_id} ) : (),
267 $opts{output} ? ( output => $opts{output} ) : (),
268 $opts{usage} ? ( usage => $opts{usage} ) : (),
269 $opts{metadata} ? ( metadata => $opts{metadata} ) : (),
270 $opts{end_time} ? ( endTime => $opts{end_time} ) : (),
271 $opts{level} ? ( level => $opts{level} ) : (),
272 $opts{status_message} ? ( statusMessage => $opts{status_message} ) : (),
273 defined $opts{completion_start_time}
274 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
275 },
276 });
277 1 return $id;
278 }
279  
280  
281 180 has langfuse_timeout => (
282 is => 'ro',
283 isa => 'Num',
284 default => 10,
285 );
286  
287  
288 180 has langfuse_flush_batch_size => (
289 is => 'ro',
290 isa => 'Int',
291 default => 100,
292 );
293  
294  
295 # --- Ingestion transport (karr k303) -----------------------------------------
296 # The helpers below use no engine state and are called as class methods, so
297 # Langertha::Plugin::Langfuse shares them instead of carrying a copy.
298  
299 17 ▶sub _langfuse_ingestion_request {
Subroutine _langfuse_ingestion_request: called CC=1 SCAR=0.0
300 17 my ( $class, %args ) = @_;
301 17 require HTTP::Request;
302 17 my $auth = encode_base64( $args{public_key} . ':' . $args{secret_key}, '' );
303 return HTTP::Request->new(
304 POST => $args{url} . '/api/public/ingestion',
305 [
306 'Content-Type' => 'application/json',
307 'Authorization' => 'Basic ' . $auth,
308 ],
309 17 $args{json}->encode({ batch => $args{events} }),
310 );
311 }
312  
313 # Sends @{$args{chunks}} one request after another and returns a Future of
314 # the responses; it never fails. $args{engine} (anything with
315 # _async_do_request_f) carries the request on its async backend with the
316 # short timeout; without one, or when that backend is the synchronous LWP
317 # shim (whose user agent has the provider's timeout), a dedicated LWP agent
318 # with the short timeout does. A transport failure (timeout, refused) stops
319 # the flush: the remaining chunks would only wait out the same timeout.
320 13 ▶async sub _langfuse_send_chunks_f {
Subroutine _langfuse_send_chunks_f: called CC=6 SCAR=17.9
321 13 my ( $class, %args ) = @_;
322 13 my @chunks = @{ $args{chunks} };
323 13 my @responses;
324 13 ▶ while ( my $chunk = shift @chunks ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $chunk = shift @chunks) 17 12 29
325 17 my $request = $class->_langfuse_ingestion_request( %args, events => $chunk );
326 17 my $response = await $class->_langfuse_send_f( $args{engine}, $request, %args );
327 17 push @responses, $response;
328 17 $class->_langfuse_check_ingestion( $response, scalar @$chunk );
329 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
330 1 my $dropped = 0;
331 1 $dropped += @$_ for @chunks;
332 1 warn "Langfuse ingestion: endpoint unreachable, dropping $dropped more event(s)\n";
333 1 last;
334 }
335 }
336 13 return @responses;
337 180 }
338  
339 17 ▶sub _langfuse_send_f {
Subroutine _langfuse_send_f: called CC=4 SCAR=13.9
340 17 my ( $class, $engine, $request, %args ) = @_;
341 17 ▶ my $http = $engine ? $engine->_async_http : undef;
Branch: 1 branch
BranchTrueFalseTotal
$engine ? : 11 6 17
342 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
343 7 require LWP::UserAgent;
344 7 my $ua = LWP::UserAgent->new( agent => $args{agent}, timeout => $args{timeout} );
345 7 return Future->done( $ua->request($request) );
346 }
347 return $engine->_async_do_request_f( request => $request, timeout => $args{timeout} )
348 3 ▶ ->else( sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
349 3 my ( $message ) = @_;
350 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
351 # Same shape LWP gives a transport failure, so both paths report alike.
352 3 require HTTP::Response;
353 3 return Future->done( HTTP::Response->new(
354 500, $message, [ 'Client-Warning' => 'Internal response' ],
355 ) );
356 10 } );
357 }
358  
359 # Warns about what did not arrive; never dies. Langfuse answers a batch with
360 # 207 Multi-Status, listing per-event failures under "errors".
361 17 ▶sub _langfuse_check_ingestion {
Subroutine _langfuse_check_ingestion: called CC=10 SCAR=24.5
362 17 my ( $class, $response, $count ) = @_;
363 17 ▶ unless ( $response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 5 12 17
364 5 warn "Langfuse ingestion failed: " . $response->status_line . " ($count event(s) lost)\n";
365 5 return;
366 }
367 12 ▶ return unless $response->code == 207;
Branch: 1 branch
BranchTrueFalseTotal
unless $response->code == 207 3 9 12
368 9 my $data = eval { JSON::MaybeXS->new( utf8 => 1 )->decode( $response->content ) };
369 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
370 9 ▶ return unless @$errors;
Branch: 1 branch
BranchTrueFalseTotal
unless @$errors 6 3 9
371 3 ▶ my $first = ref $errors->[0] eq 'HASH' ? $errors->[0] : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $errors->[0] eq 'HASH' ? : 3 0 3
372 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
373 3 ▶ warn sprintf "Langfuse ingestion: %d of %d event(s) rejected%s\n",
Branch: 1 branch
BranchTrueFalseTotal
length $detail ? : 3 0 3
374 scalar @$errors, $count, length $detail ? " (first: $detail)" : '';
375 3 return;
376 }
377  
378 7 ▶sub _langfuse_flush_args {
Subroutine _langfuse_flush_args: called CC=4 SCAR=13.9
379 7 my ( $self ) = @_;
380 7 my @events = @{ $self->_langfuse_batch };
381 7 ▶ return unless @events;
Branch: 1 branch
BranchTrueFalseTotal
unless @events 1 6 7
382 6 $self->_langfuse_batch([]);
383 6 my $size = $self->langfuse_flush_batch_size;
384 6 ▶ $size = 1 if $size < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $size < 1 0 6 6
385 6 my @chunks;
386 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
387 return (
388 6 chunks => \@chunks,
389 url => $self->langfuse_url,
390 public_key => $self->langfuse_public_key,
391 secret_key => $self->langfuse_secret_key,
392 json => $self->json,
393 agent => 'Langertha-Langfuse/' . $VERSION,
394 timeout => $self->langfuse_timeout,
395 );
396 }
397  
398 4 ▶sub langfuse_flush {
Subroutine langfuse_flush: called CC=3 SCAR=11.0
Pod documented
399 4 my ( $self ) = @_;
400 4 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 0 4 4
401 4 ▶ my %args = $self->_langfuse_flush_args or return;
Branch: 1 branch
BranchTrueFalseTotal
my(%args) = $self->_langfuse_flush_args or return 3 1 4
402 3 my @responses = __PACKAGE__->_langfuse_send_chunks_f(%args)->get;
403 3 return $responses[-1];
404 }
405  
406  
407 3 ▶async sub langfuse_flush_f {
Subroutine langfuse_flush_f: called CC=3 SCAR=11.3
Pod documented
408 3 my ( $self ) = @_;
409 3 ▶ return unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 0 3 3
410 3 ▶ my %args = $self->_langfuse_flush_args or return;
Branch: 1 branch
BranchTrueFalseTotal
my(%args) = $self->_langfuse_flush_args or return 3 0 3
411 3 return await __PACKAGE__->_langfuse_send_chunks_f( %args, engine => $self );
412 180 }
413  
414  
415 # Auto-instrumentation: wraps simple_chat to record a trace and generation
416 # for every call when Langfuse is enabled.
417  
418 # Returns an ISO-8601 timestamp (UTC, ms resolution) at
419 # $start_hires + $delta_seconds. Used to compute endTime /
420 # completionStartTime from a client-measured total_seconds / ttft_seconds
421 # carried on a Langertha::Response, anchored to the moment the simple_chat
422 # wrapper entered — not to wall-clock now, which has already advanced
423 # past end. Sub-millisecond precision in the underlying hires time is
424 # rounded to whole milliseconds to match the rest of Langfuse timestamp
425 # formatting.
426 18 ▶sub _langfuse_iso_after {
Subroutine _langfuse_iso_after: called CC=3 SCAR=11.0
427 18 my ( $self, $start_hires, $delta_seconds ) = @_;
428 # Guard against clock skew / monotonic drift producing a negative delta
429 # (Perl's % preserves sign on negatives, which would yield a negative $us
430 # and an out-of-range millisecond field below). Clamp to zero — better
431 # to report a same-instant end_time than a wall-clock trip into the past.
432 18 ▶ $delta_seconds = 0 if $delta_seconds < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $delta_seconds < 0 3 15 18
433 18 my ($s, $us) = @$start_hires;
434 18 my $delta_us = $delta_seconds * 1_000_000;
435 18 $s += int( ($us + $delta_us) / 1_000_000 );
436 18 $us = int( ($us + $delta_us) % 1_000_000 );
437 18 ▶ $us = 0 if $us < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $us < 0 0 18 18
438 18 my @t = gmtime($s);
439 18 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
440 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
441 }
442  
443 8 ▶around simple_chat => sub {
Subroutine __ANON__: called CC=14 SCAR=51.7
444 8 my ( $orig, $self, @messages ) = @_;
445 8 ▶ return $self->$orig(@messages) unless $self->langfuse_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->langfuse_enabled 8 0 8
446  
447 0 my $start = [gettimeofday];
448 0 my $start_time = $self->_langfuse_timestamp;
449  
450 0 my $response = $self->$orig(@messages);
451  
452 0 my $t1 = $self->_langfuse_timestamp;
453 0 my $end_time = $t1;
454  
455 # Build usage from Response if available
456 0 my $usage;
457 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
458 0 $usage = {
459 input => $response->prompt_tokens,
460 output => $response->completion_tokens,
461 total => $response->total_tokens,
462 };
463 }
464  
465 # Prefer response-side timing (carries total_seconds and optionally
466 # ttft_seconds) when available. Both are deltas measured from the
467 # same anchor as our wrapper's $start — anchor end / completion_start
468 # to that anchor so the generation event spans the real call window
469 # rather than drifting into the future.
470 0 my $completion_start_time;
471 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
472 0 ▶ if ($response->has_total) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->has_total) 0 0 0
473 0 $end_time = $self->_langfuse_iso_after($start, $response->total_seconds);
474 }
475 0 ▶ if ($response->has_ttft) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->has_ttft) 0 0 0
476 0 $completion_start_time = $self->_langfuse_iso_after($start, $response->ttft_seconds);
477 }
478 }
479  
480 0 my $trace_id = $self->langfuse_trace(
481 name => 'simple_chat',
482 input => \@messages,
483 output => "$response",
484 );
485  
486 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
487 trace_id => $trace_id,
488 name => 'chat',
489 model => (ref $response && $response->isa('Langertha::Response') && $response->has_model)
490 ? $response->model : $self->chat_model,
491 input => \@messages,
492 output => "$response",
493 start_time => $start_time,
494 end_time => $end_time,
495 defined $completion_start_time ? ( completion_start_time => $completion_start_time ) : (),
496 $usage ? ( usage => $usage ) : (),
497 );
498  
499 0 return $response;
500 180 };
501  
502  
503 180 1;
504  
505 __END__
506  
507 =pod
508  
509 =encoding UTF-8
510  
511 =head1 NAME
512  
513 Langertha::Role::Langfuse - Langfuse observability integration
514  
515 =head1 VERSION
516  
517 version 0.503
518  
519 =head1 SYNOPSIS
520  
521 Langfuse is built into every Langertha engine. Just set the env vars:
522  
523 export LANGFUSE_PUBLIC_KEY=pk-lf-...
524 export LANGFUSE_SECRET_KEY=sk-lf-...
525 export LANGFUSE_URL=http://localhost:3000 # optional, defaults to cloud
526  
527 Then use any engine as normal — C<simple_chat> is auto-traced:
528  
529 use Langertha::Engine::OpenAI;
530  
531 my $engine = Langertha::Engine::OpenAI->new(
532 api_key => $ENV{OPENAI_API_KEY},
533 model => 'gpt-4o-mini',
534 );
535  
536 my $response = $engine->simple_chat('Hello!');
537 $engine->langfuse_flush; # send events to Langfuse
538  
539 # inside an event loop, without blocking it:
540 await $engine->langfuse_flush_f;
541  
542 Or pass keys explicitly:
543  
544 my $engine = Langertha::Engine::Anthropic->new(
545 api_key => $ENV{ANTHROPIC_API_KEY},
546 langfuse_public_key => 'pk-lf-...',
547 langfuse_secret_key => 'sk-lf-...',
548 langfuse_url => 'http://localhost:3000',
549 );
550  
551 Manual traces for custom workflows:
552  
553 my $trace_id = $engine->langfuse_trace(
554 name => 'my-workflow',
555 input => { query => 'custom input' },
556 );
557  
558 $engine->langfuse_generation(
559 trace_id => $trace_id,
560 name => 'step-1',
561 model => 'gpt-4o',
562 input => 'prompt text',
563 output => 'response text',
564 usage => { input => 10, output => 5, total => 15 },
565 );
566  
567 $engine->langfuse_flush;
568  
569 =head1 DESCRIPTION
570  
571 This role integrates Langertha engines with L<Langfuse|https://langfuse.com/>,
572 an open-source observability platform for LLM applications. It is composed
573 into L<Langertha::Role::Chat>, so B<every engine has Langfuse support built in>.
574  
575 B<Features:>
576  
577 =over 4
578  
579 =item * Zero-config via environment variables
580  
581 =item * Auto-instrumentation of C<simple_chat> calls
582  
583 =item * Manual trace and generation event creation
584  
585 =item * Batched event ingestion via Langfuse REST API
586  
587 =item * Basic Auth using public/secret key pair
588  
589 =item * Disabled by default — only active when both keys are set
590  
591 =back
592  
593 B<Langfuse concepts:>
594  
595 =over 4
596  
597 =item * B<Trace> — Top-level unit of work (a request, a conversation turn)
598  
599 =item * B<Span> — A grouping of work within a trace (an iteration, a tool call)
600  
601 =item * B<Generation> — A single LLM call within a trace (with model, usage, timing)
602  
603 =back
604  
605 B<Hierarchy:> Traces contain spans and generations. Spans can nest via
606 C<parent_observation_id>. All observations can be updated after creation.
607  
608 =head2 langfuse_public_key
609  
610 Your Langfuse project public key. Auto-populated from C<LANGFUSE_PUBLIC_KEY>
611 environment variable if not passed.
612  
613 =head2 langfuse_secret_key
614  
615 Your Langfuse project secret key. Auto-populated from C<LANGFUSE_SECRET_KEY>
616 environment variable if not passed.
617  
618 =head2 langfuse_url
619  
620 Langfuse API URL. Defaults to C<LANGFUSE_URL> env var, or
621 C<https://cloud.langfuse.com> if not set. Set this to your
622 self-hosted instance URL (e.g. C<http://localhost:3000>).
623  
624 =head2 langfuse_enabled
625  
626 Bool indicating whether Langfuse integration is active. Lazy — defaults
627 to true when both public and secret keys are available (from constructor
628 or environment variables).
629  
630 =head2 langfuse_max_batch
631  
632 The most events kept in memory between two L</langfuse_flush> calls. Default
633 C<1000> (500 traced C<simple_chat> calls, each a trace and a generation). The
634 events are only sent when someone flushes, and Langfuse turns on by itself as
635 soon as C<LANGFUSE_PUBLIC_KEY> and C<LANGFUSE_SECRET_KEY> are in the
636 environment, so a long-running process that never flushes would otherwise
637 keep every prompt and answer it ever sent. When the batch is full the
638 B<oldest> event is dropped for each new one, with a single warning per engine
639 object. C<0> removes the cap.
640  
641 Nothing is flushed automatically: a flush is an HTTP request, and
642 C<simple_chat> should not pay for one at an unpredictable moment. Call
643 L</langfuse_flush> (or L</langfuse_flush_f>) yourself, for example after each
644 request in a server.
645  
646 =head2 langfuse_timestamp
647  
648 my $t0 = $engine->langfuse_timestamp; # 2026-09-25T12:34:56.789Z
649 ...
650 $engine->langfuse_span(
651 trace_id => $trace_id,
652 name => 'tool: search',
653 start_time => $t0,
654 end_time => $engine->langfuse_timestamp,
655 );
656  
657 Returns the current time as an ISO-8601 UTC string with millisecond
658 precision (C<YYYY-MM-DDTHH:MM:SS.mmmZ>) — the format this role stamps on
659 every Langfuse event. Use it for C<start_time> / C<end_time> when you create
660 spans or generations yourself. The older private name C<_langfuse_timestamp>
661 still works and returns the same.
662  
663 =head2 langfuse_trace
664  
665 my $trace_id = $engine->langfuse_trace(
666 name => 'my-trace',
667 input => { ... },
668 output => '...',
669 metadata => { ... },
670 tags => ['tag1', 'tag2'],
671 user_id => 'user-123',
672 session_id => 'session-abc',
673 release => '1.0.0',
674 version => '1',
675 public => 1,
676 environment => 'production',
677 );
678  
679 Creates a trace event. Returns the trace ID for linking generations and
680 spans. Accepts optional C<tags>, C<user_id>, C<session_id>, C<release>,
681 C<version>, C<public>, and C<environment> fields. Calling with the same
682 C<id> upserts (updates) the trace.
683  
684 =head2 langfuse_generation
685  
686 $engine->langfuse_generation(
687 trace_id => $trace_id,
688 name => 'chat',
689 model => 'gpt-4o',
690 input => '...',
691 output => '...',
692 usage => { input => 10, output => 5, total => 15 },
693 start_time => $iso_timestamp,
694 end_time => $iso_timestamp,
695 parent_observation_id => $span_id,
696 model_parameters => { temperature => 0.7, max_tokens => 1000 },
697 level => 'DEFAULT',
698 status_message => 'OK',
699 version => '1',
700 );
701  
702 Creates a generation event linked to a trace. C<trace_id> is required.
703 Accepts optional C<parent_observation_id> for nesting under a span,
704 C<model_parameters>, C<level> (DEBUG/DEFAULT/WARNING/ERROR),
705 C<status_message>, and C<version>.
706  
707 =head2 langfuse_span
708  
709 my $span_id = $engine->langfuse_span(
710 trace_id => $trace_id,
711 name => 'my-span',
712 input => { ... },
713 output => '...',
714 start_time => $iso_timestamp,
715 end_time => $iso_timestamp,
716 parent_observation_id => $parent_span_id,
717 metadata => { ... },
718 level => 'DEFAULT',
719 status_message => 'OK',
720 version => '1',
721 );
722  
723 Creates a span event for grouping work within a trace. C<trace_id> is
724 required. Returns the span ID. Spans can be nested via
725 C<parent_observation_id>.
726  
727 =head2 langfuse_update_trace
728  
729 $engine->langfuse_update_trace(
730 id => $trace_id,
731 output => 'final result',
732 metadata => { ... },
733 );
734  
735 Updates a trace by upserting with the same C<id>. Uses C<trace-create>
736 event type (Langfuse upserts on matching body ID). C<id> is required.
737  
738 =head2 langfuse_update_span
739  
740 $engine->langfuse_update_span(
741 id => $span_id,
742 end_time => $iso_timestamp,
743 output => { ... },
744 );
745  
746 Updates an existing span. C<id> is required. Use this to set C<end_time>
747 and C<output> after the span's work completes.
748  
749 =head2 langfuse_update_generation
750  
751 $engine->langfuse_update_generation(
752 id => $gen_id,
753 output => 'final response text',
754 usage => { input => 100, output => 50, total => 150 },
755 );
756  
757 Updates an existing generation. C<id> is required. Use this to add
758 C<output>, C<usage>, and C<end_time> after the LLM call completes.
759  
760 =head2 langfuse_timeout
761  
762 Seconds a flush may wait for Langfuse per request. Default C<10>, deliberately
763 short: Langfuse is observability, and an ingestion endpoint that accepts the
764 connection and never answers must not hold up the application (LWP's own
765 default would be 180 seconds). The engine's
766 L<Langertha::Role::HTTP/user_agent_timeout> does not apply here; it is meant
767 for the LLM provider. On the L<Net::Async::HTTP> backend it is the total time
768 of the request, on the synchronous LWP path the time without activity on the
769 connection.
770  
771 =head2 langfuse_flush_batch_size
772  
773 The most events sent in one ingestion request. Default C<100>. A flush with
774 more events sends several requests one after another, so a large backlog does
775 not become one body that Langfuse rejects for its size.
776  
777 =head2 langfuse_flush
778  
779 $engine->langfuse_flush;
780  
781 Sends all batched events to the Langfuse ingestion API over a dedicated
782 L<LWP::UserAgent> with L</langfuse_timeout>, and clears the batch. Blocks
783 until the requests are done, so do not call it from inside an event loop;
784 use L</langfuse_flush_f> there. More than L</langfuse_flush_batch_size>
785 events go out as several requests. Returns the L<HTTP::Response> of the last
786 request, or nothing when there was nothing to send.
787  
788 It never dies. It warns when a request fails (the events of that request are
789 lost, and after a timeout or refused connection the rest of the flush is
790 dropped too, instead of waiting out the timeout once per request), and when
791 Langfuse accepts the request but rejects single events (C<207 Multi-Status>
792 with an C<errors> list): the warning gives the number rejected and the first
793 error.
794  
795 =head2 langfuse_flush_f
796  
797 await $engine->langfuse_flush_f;
798  
799 Async L</langfuse_flush>: sends the batched events through the engine's own
800 async backend (L<Langertha::Role::AsyncHTTP>) with L</langfuse_timeout> as
801 the request's total timeout, so a slow or silent Langfuse never blocks the
802 event loop. The batch is taken when the call starts; events recorded while
803 it runs wait for the next flush. The future resolves to the
804 L<HTTP::Response> of each request and B<never fails>; problems are warned
805 about as in L</langfuse_flush>. On the synchronous fallback (no
806 L<Net::Async::HTTP>) it runs like L</langfuse_flush>.
807  
808 =head1 ENVIRONMENT VARIABLES
809  
810 =over 4
811  
812 =item C<LANGFUSE_PUBLIC_KEY> — Auto-populates C<langfuse_public_key>
813  
814 =item C<LANGFUSE_SECRET_KEY> — Auto-populates C<langfuse_secret_key>
815  
816 =item C<LANGFUSE_URL> — Auto-populates C<langfuse_url> (default: C<https://cloud.langfuse.com>)
817  
818 =back
819  
820 With both keys in the environment every engine records C<simple_chat> calls
821 without being asked to, but sends nothing until L</langfuse_flush> is called.
822 Events wait in memory up to L</langfuse_max_batch>; past that the oldest are
823 dropped with one warning. A process that has the variables set but never
824 flushes therefore holds a bounded amount of trace data, not every prompt it
825 ever sent.
826  
827 =head1 SELF-HOSTING LANGFUSE
828  
829 A ready-to-use Kubernetes manifest is included in the distribution:
830  
831 kubectl apply -f ex/langfuse-k8s.yaml
832 kubectl -n langfuse port-forward svc/langfuse-web 3000:3000 &
833  
834 export LANGFUSE_PUBLIC_KEY=pk-lf-langertha
835 export LANGFUSE_SECRET_KEY=sk-lf-langertha
836 export LANGFUSE_URL=http://localhost:3000
837  
838 The manifest pre-creates a project with known API keys so you can send
839 data immediately without going through the web UI.
840  
841 Dashboard: C<http://localhost:3000> (login: C<langertha@test.invalid> / C<langertha>)
842  
843 =head1 GETTING LANGFUSE KEYS
844  
845 For Langfuse Cloud, sign up at L<https://langfuse.com/> and generate
846 API keys in your project settings.
847  
848 =head1 SEE ALSO
849  
850 =over
851  
852 =item * L<https://langfuse.com/docs> - Langfuse documentation
853  
854 =item * L<Langertha::Role::Chat> - Chat role that composes this role
855  
856 =item * L<Langertha::Raider> - Autonomous agent with Langfuse tracing support
857  
858 =back
859  
860 =head1 SUPPORT
861  
862 =head2 Issues
863  
864 Please report bugs and feature requests on GitHub at
865 L<https://github.com/Getty/langertha/issues>.
866  
867 =head2 IRC
868  
869 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
870  
871 =head1 CONTRIBUTING
872  
873 Contributions are welcome! Please fork the repository and submit a pull request.
874  
875 =head1 AUTHOR
876  
877 Torsten Raudssus <getty@cpan.org>
878  
879 =head1 COPYRIGHT AND LICENSE
880  
881 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
882  
883 This is free software; you can redistribute it and/or modify it under
884 the same terms as the Perl 5 programming language system itself.
885  
886 =cut
« blib/lib/Langertha/Engine/LMStudio.pm ↑ Summary blib/lib/Langertha/Role/OpenAICompatible.pm »