blib/lib/Langertha/Response.pm

filter: Statementstmt 100% 111 / 111 Branchbran 93.1% 82 / 88 Conditioncond 76.0% 19 / 25 MC/DCmcdc 57.1% 8 / 14 Subroutinesub 100% 23 / 23 Podpod 85.7% 12 / 14 totaltotal 92.7% 255 / 275 CC 56 SCAR 21.7
CC
56
Cov
95%
__ANON__
19.4
to_hash
12.0
clone_with
8.1
CRAP 8.8
« blib/lib/Langertha/ServerToolCall.pm ↑ Summary blib/lib/Langertha/Runtime/Knobs.pm »
1 package Langertha::Response;
2 # ABSTRACT: LLM response with metadata
3 182 our $VERSION = '0.503';
4 182 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 182 ▶use Langertha::Moment;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 182 ▶use Langertha::ServerToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 182 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 182 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 use overload
11 86 ▶ '""' => sub { $_[0]->content },
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
12 # An object that exists is true. Without this, `fallback => 1` derives bool
13 # from the '""' overload, and a Response whose content is the empty string --
14 # a tool-call-only reply -- would be false. See "Boolean context" (karr #100).
15 77 ▶ 'bool' => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
16 182 fallback => 1;
17  
18  
19 182 has content => (
20 is => 'ro',
21 isa => 'Str',
22 required => 1,
23 );
24  
25  
26 182 has raw => (
27 is => 'ro',
28 isa => 'HashRef',
29 predicate => 'has_raw',
30 );
31  
32  
33 182 has id => (
34 is => 'ro',
35 isa => 'Str',
36 predicate => 'has_id',
37 );
38  
39  
40 182 has model => (
41 is => 'ro',
42 isa => 'Str',
43 predicate => 'has_model',
44 );
45  
46  
47 182 has finish_reason => (
48 is => 'ro',
49 isa => 'Maybe[Str]',
50 predicate => 'has_finish_reason',
51 );
52  
53  
54 182 has usage => (
55 is => 'ro',
56 isa => 'Maybe[Langertha::Usage]',
57 predicate => 'has_usage',
58 );
59  
60  
61 182 has timing => (
62 is => 'ro',
63 isa => 'Maybe[HashRef]',
64 predicate => 'has_timing',
65 );
66  
67  
68 20 ▶sub has_ttft {
Subroutine has_ttft: called CC=4 SCAR=13.9
Pod undocumented
69 20 my ($self) = @_;
70 20 ▶ my $t = $self->timing or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $self->timing or return 0 10 10 20
71 10 ▶ return exists $t->{ttft_seconds} && defined $t->{ttft_seconds} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $t->{'ttft_seconds'} && defined $t->{'ttft_seconds'} ? : 5 5 10
Condition66%2/3
exists $t->{"ttft_seconds"} and defined $t->{"ttft_seconds"}
!ll&&!rl&&r
505
MC/DC50%1/2
exists $t->{"ttft_seconds"} and defined $t->{"ttft_seconds"}
exists $t->{"ttft_seconds"} defined $t->{"ttft_seconds"}
Truth table66%2/3
A and B
A= exists $t->{"ttft_seconds"}B= defined $t->{"ttft_seconds"}
ABresult
0X0
100
111
72 }
73  
74 8 ▶sub ttft_seconds {
Subroutine ttft_seconds: called CC=2 SCAR=6.9
Pod documented
75 8 my ($self) = @_;
76 8 ▶ my $t = $self->timing or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $self->timing or return undef 7 1 8
77 7 return $t->{ttft_seconds};
78 }
79  
80 11 ▶sub has_total {
Subroutine has_total: called CC=4 SCAR=13.9
Pod undocumented
81 11 my ($self) = @_;
82 11 ▶ my $t = $self->timing or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $self->timing or return 0 9 2 11
83 9 ▶ return exists $t->{total_seconds} && defined $t->{total_seconds} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $t->{'total_seconds'} && defined $t->{'total_seconds'} ? : 8 1 9
Condition66%2/3
exists $t->{"total_seconds"} and defined $t->{"total_seconds"}
!ll&&!rl&&r
108
MC/DC50%1/2
exists $t->{"total_seconds"} and defined $t->{"total_seconds"}
exists $t->{"total_seconds"} defined $t->{"total_seconds"}
Truth table66%2/3
A and B
A= exists $t->{"total_seconds"}B= defined $t->{"total_seconds"}
ABresult
0X0
100
111
84 }
85  
86 17 ▶sub total_seconds {
Subroutine total_seconds: called CC=2 SCAR=6.9
Pod documented
87 17 my ($self) = @_;
88 17 ▶ my $t = $self->timing or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $t = $self->timing or return undef 15 2 17
89 15 return $t->{total_seconds};
90 }
91  
92  
93  
94 182 has created => (
95 is => 'ro',
96 isa => 'Maybe[Langertha::Moment]',
97 predicate => 'has_created',
98 );
99  
100  
101 182 has cached_tokens => (
102 is => 'ro',
103 isa => 'Maybe[Int]',
104 predicate => 'has_cached_tokens',
105 );
106  
107  
108 182 has thinking => (
109 is => 'ro',
110 isa => 'Maybe[Str]',
111 predicate => 'has_thinking',
112 );
113  
114 182 has refusal => (
115 is => 'ro',
116 isa => 'Maybe[Str]',
117 predicate => 'has_refusal',
118 );
119  
120 182 has rate_limit => (
121 is => 'ro',
122 isa => 'Maybe[Langertha::RateLimit]',
123 predicate => 'has_rate_limit',
124 );
125  
126 182 has tool_calls => (
127 is => 'ro',
128 isa => 'Maybe[ArrayRef[Langertha::ToolCall]]',
129 predicate => 'has_tool_calls',
130 );
131  
132 182 has server_tool_calls => (
133 is => 'ro',
134 isa => 'Maybe[ArrayRef[Langertha::ServerToolCall]]',
135 predicate => 'has_server_tool_calls',
136 );
137  
138 182 has probes => (
139 is => 'ro',
140 isa => 'Maybe[HashRef]',
141 predicate => 'has_probes',
142 );
143  
144 182 has citations => (
145 is => 'ro',
146 isa => 'Maybe[ArrayRef]',
147 predicate => 'has_citations',
148 );
149  
150 1063 ▶around BUILDARGS => sub {
Subroutine __ANON__: called CC=19 SCAR=29.6
151 1063 my ( $orig, $class, @args ) = @_;
152 1063 my $params = $class->$orig(@args);
153  
154 # Coerce the usage block to a Langertha::Usage object first (karr #43): the
155 # value object owns inbound wire-spelling parsing (ADR 0001 / 0018 home 1),
156 # including the prompt-cache read/write counts and the two wire spellings each
157 # carries. Response no longer hand-parses any usage spelling itself.
158 1063 ▶ if ( defined $params->{usage} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"usage"}) 231 832 1063
159 231 $params->{usage} = ( ref( $params->{usage} ) && eval { $params->{usage}->isa('Langertha::Usage') } )
160 ? $params->{usage}
161 231 ▶ : Langertha::Usage->from_hash( $params->{usage} );
Branch: 1 branch
BranchTrueFalseTotal
ref $params->{'usage'} && eval { do { $params->{'usage'}->isa('Langertha::Usage') } } ? : 33 198 231
Condition66%2/3
ref $params->{"usage"} and eval {
!ll&&!rl&&r
019833
MC/DC50%1/2
ref $params->{"usage"} and eval { do { $params->{"usage"}->isa("Langertha::Usage") } }
ref $params->{"usage"} eval { do { $params->{"usage"}->isa("Langertha::Usage") } }
Truth table66%2/3
A and B
A= ref $params->{"usage"}B= eval { do { $params->{"usage"}->isa("Langertha::Usage") } }
ABresult
0X0
100
111
162 }
163  
164 # Response keeps its public cached_tokens attribute (karr #61) but no longer
165 # carries the provider wire spellings — those moved onto Langertha::Usage
166 # (karr #130). Surface the prefix-cache read-back by lifting the PARSED count
167 # off the Usage object, so ANY Response assembled from provider usage —
168 # including one built from a streamed final chunk's usage — exposes it. Only
169 # when defined (cached_tokens => 0 is a real count). An explicit cached_tokens
170 # parameter always wins.
171 1063 ▶ if ( !exists $params->{cached_tokens}
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $params->{"cached_tokens"} and ref $params->{"usage"} and eval { do { $params->{"usage"}->isa("Langertha::Usage") } } and defined $params->{"usage"}->cached_tokens) 59 1004 1063
Condition88%8/9
not exists $params->{"cached_tokens"} and ref $params->{"usage"} and eval { and defined $params->{"usage"}->cached_tokens
!ll&&!rl&&r
86114359
not exists $params->{"cached_tokens"} and ref $params->{"usage"} and eval {
!ll&&!rl&&r
8610202
not exists $params->{"cached_tokens"} and ref $params->{"usage"}
!ll&&!rl&&r
31830202
MC/DC75%3/4
not exists $params->{"cached_tokens"} and ref $params->{"usage"} and eval { do { $params->{"usage"}->isa("Langertha::Usage") } } and defined $params->{"usage"}->cached_tokens
not exists $params->{"cached_tokens"} ref $params->{"usage"} eval { do { $params->{"usage"}->isa("Langertha::Usage") } } defined $params->{"usage"}->cached_tokens
Truth table80%4/5
not(A) and B and C and D
A= not exists $params->{"cached_tokens"}B= ref $params->{"usage"}C= eval { do { $params->{"usage"}->isa("Langertha::Usage") } }D= defined $params->{"usage"}->cached_tokens
ABCDresult
0XXX0
10XX0
110X0
11100
11111
172 && ref( $params->{usage} )
173 202 && eval { $params->{usage}->isa('Langertha::Usage') }
174 && defined $params->{usage}->cached_tokens ) {
175 59 $params->{cached_tokens} = $params->{usage}->cached_tokens;
176 }
177  
178 # Accept legacy ArrayRef[HashRef] input by upgrading to ToolCall objects.
179 1063 ▶ if ( ref( $params->{tool_calls} ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params->{"tool_calls"} eq "ARRAY") 204 859 1063
180 $params->{tool_calls} = [
181 map {
182 235 ▶ ref($_) && eval { $_->isa('Langertha::ToolCall') }
Branch: 4 branches
BranchTrueFalseTotal
ref $_->{'arguments'} eq 'HASH' ? : 72 0 72
$_->{'synthetic'} ? : 22 50 72
$_->{'arguments_undecodable'} ? : 5 67 72
defined $_->{'arguments_error'} ? : 5 0 5
Condition75%3/4
$_->{"name"} // ""
l!l
720
$_->{"id"} // ""
l!l
369
MC/DC0%0/1
$_->{"name"} // ""
$_->{"name"}
MC/DC100%1/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"name"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"id"}
Aresult
11
00
183 ? $_
184 : Langertha::ToolCall->new(
185 name => ( $_->{name} // '' ),
186 arguments => ( ref( $_->{arguments} ) eq 'HASH' ? $_->{arguments} : {} ),
187 id => ( $_->{id} // '' ),
188 synthetic => ( $_->{synthetic} ? 1 : 0 ),
189 # Carry the k345 undecodable flag through the legacy-hash upgrade
190 # (the hermes lift reduces a ToolCall to this shape) so the tool
191 # loop still answers a bad call an error result -- karr k350.
192 ( $_->{arguments_undecodable}
193 ? ( arguments_undecodable => 1,
194 235 ▶ ( defined $_->{arguments_error} ? ( arguments_error => $_->{arguments_error} ) : () ) )
Branch: 1 branch
BranchTrueFalseTotal
ref $_ && eval { do { $_->isa('Langertha::ToolCall') } } ? : 163 72 235
Condition66%2/3
ref $_ and eval {
!ll&&!rl&&r
072163
MC/DC50%1/2
ref $_ and eval { do { $_->isa("Langertha::ToolCall") } }
ref $_ eval { do { $_->isa("Langertha::ToolCall") } }
Truth table66%2/3
A and B
A= ref $_B= eval { do { $_->isa("Langertha::ToolCall") } }
ABresult
0X0
100
111
195 : () ),
196 );
197 204 } @{ $params->{tool_calls} }
198 ];
199 }
200  
201 # created arrives in two shapes and must survive a third: an epoch integer
202 # on the OpenAI-compatible wire, an RFC3339 string with nanoseconds from
203 # Ollama, and anything at all from a shim nobody has met yet. Normalizing
204 # here rather than in each engine means a producer only has to hand over
205 # what the provider sent (ADR 0001's inbound half: the value object owns the
206 # parse, the engine carries no per-shape code).
207 #
208 # from_wire never dies, and an unreadable value deletes the key rather than
209 # setting it to undef -- created is metadata, and a timestamp the parser
210 # cannot read must not fail the constructor for a response that is otherwise
211 # perfectly good (GitHub #3, karr #92 / #117).
212 1063 ▶ if ( exists $params->{created} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{"created"}) 130 933 1063
213 130 my $moment = Langertha::Moment->from_wire( $params->{created} );
214 130 ▶ if ( defined $moment ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $moment) { } 124 6 130
215 124 $params->{created} = $moment;
216 }
217 else {
218 6 delete $params->{created};
219 }
220 }
221  
222 1063 return $params;
223 182 };
224  
225  
226  
227 48 ▶sub tool_call {
Subroutine tool_call: called CC=6 SCAR=17.9
Pod documented
228 48 my ( $self, $name ) = @_;
229 48 ▶ my $tcs = $self->tool_calls or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $tcs = $self->tool_calls or return undef 45 3 48
230 45 ▶ return undef unless @$tcs;
Branch: 1 branch
BranchTrueFalseTotal
unless @$tcs 0 45 45
231 45 ▶ return $tcs->[0] unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 20 25 45
232 25 for my $tc (@$tcs) {
233 25 ▶ return $tc if $tc->name eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if $tc->name eq $name 24 1 25
234 }
235 1 return undef;
236 }
237  
238  
239 8 ▶sub tool_call_args {
Subroutine tool_call_args: called CC=2 SCAR=6.9
Pod documented
240 8 my ( $self, $name ) = @_;
241 8 ▶ my $tc = $self->tool_call($name) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $tc = $self->tool_call($name) or return undef 6 2 8
242 6 return $tc->arguments;
243 }
244  
245  
246  
247  
248  
249 321 ▶sub clone_with {
Subroutine clone_with: called CC=8 SCAR=20.9
Pod documented
250 321 my ( $self, %overrides ) = @_;
251 321 my %args = ( content => $self->content );
252 321 for my $attr ( $self->meta->get_all_attributes ) {
253 5136 ▶ next unless $attr->has_predicate;
Branch: 1 branch
BranchTrueFalseTotal
unless $attr->has_predicate 321 4815 5136
254 4815 ▶ next unless $attr->get_read_method;
Branch: 1 branch
BranchTrueFalseTotal
unless $attr->get_read_method 0 4815 4815
255 4815 ▶ next if $attr->is_required;
Branch: 1 branch
BranchTrueFalseTotal
if $attr->is_required 0 4815 4815
256 4815 my $name = $attr->name;
257 4815 ▶ next if $name eq 'content';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "content" 0 4815 4815
258 4815 ▶ next if exists $overrides{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $overrides{$name} 326 4489 4815
259 4489 ▶ $args{$name} = $self->$name if $self->${\"has_$name"};
Branch: 1 branch
BranchTrueFalseTotal
if $self->${\("has_$name");} 859 3630 4489
260 }
261 321 return ( ref $self )->new( %args, %overrides );
262 }
263  
264  
265  
266 18 ▶sub to_hash {
Subroutine to_hash: called CC=12 SCAR=24.8
Pod documented
267 18 my ($self) = @_;
268 return {
269 18 ▶ content => $self->content,
Branch: 11 branches
BranchTrueFalseTotal
$self->has_id ? : 7 11 18
$self->has_model ? : 12 6 18
$self->has_finish_reason ? : 7 11 18
$self->has_usage ? : 9 9 18
$self->has_timing ? : 2 16 18
$self->has_created ? : 10 8 18
$self->has_cached_tokens ? : 1 17 18
$self->has_thinking ? : 2 16 18
$self->has_refusal ? : 1 17 18
$self->has_rate_limit ? : 2 16 18
$self->has_tool_calls ? : 2 16 18
270 ( $self->has_id ? ( id => $self->id ) : () ),
271 ( $self->has_model ? ( model => $self->model ) : () ),
272 ( $self->has_finish_reason ? ( finish_reason => $self->finish_reason ) : () ),
273 ( $self->has_usage ? ( usage => $self->usage ) : () ),
274 ( $self->has_timing ? ( timing => $self->timing ) : () ),
275 # Numified on purpose: created is a Langertha::Moment, and the bounded
276 # Response hash (karr #50) is the interop surface that has emitted an
277 # epoch number for this key since the attribute existed. The sub-seconds
278 # the object carries stay reachable on the object and under raw; they are
279 # not in this hash, and were never in it.
280 ( $self->has_created ? ( created => 0 + $self->created ) : () ),
281 ( $self->has_cached_tokens ? ( cached_tokens => $self->cached_tokens ) : () ),
282 ( $self->has_thinking ? ( thinking => $self->thinking ) : () ),
283 ( $self->has_refusal ? ( refusal => $self->refusal ) : () ),
284 ( $self->has_rate_limit ? ( rate_limit => $self->rate_limit ) : () ),
285 ( $self->has_tool_calls ? ( tool_calls => $self->tool_calls ) : () ),
286 };
287 }
288  
289 12 ▶sub TO_JSON { shift->to_hash }
Subroutine TO_JSON: called CC=1 SCAR=0.0
Pod documented
290  
291 29 ▶sub prompt_tokens {
Subroutine prompt_tokens: called CC=2 SCAR=6.9
Pod documented
292 29 my ( $self ) = @_;
293 29 ▶ my $u = $self->usage or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $u = $self->usage or return undef 27 2 29
294 27 return $u->input_tokens;
295 }
296  
297  
298 23 ▶sub completion_tokens {
Subroutine completion_tokens: called CC=2 SCAR=6.9
Pod documented
299 23 my ( $self ) = @_;
300 23 ▶ my $u = $self->usage or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $u = $self->usage or return undef 21 2 23
301 21 return $u->output_tokens;
302 }
303  
304  
305 15 ▶sub total_tokens {
Subroutine total_tokens: called CC=2 SCAR=6.9
Pod documented
306 15 my ( $self ) = @_;
307 15 ▶ my $u = $self->usage or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $u = $self->usage or return undef 13 2 15
308 13 return $u->total_tokens;
309 }
310  
311  
312 2 ▶sub requests_remaining {
Subroutine requests_remaining: called CC=2 SCAR=6.9
Pod documented
313 2 my ( $self ) = @_;
314 2 ▶ my $rl = $self->rate_limit or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $rl = $self->rate_limit or return undef 1 1 2
315 1 return $rl->requests_remaining;
316 }
317  
318  
319 2 ▶sub tokens_remaining {
Subroutine tokens_remaining: called CC=2 SCAR=6.9
Pod documented
320 2 my ( $self ) = @_;
321 2 ▶ my $rl = $self->rate_limit or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $rl = $self->rate_limit or return undef 1 1 2
322 1 return $rl->tokens_remaining;
323 }
324  
325  
326  
327 182 __PACKAGE__->meta->make_immutable;
328  
329 182 1;
330  
331 __END__
332  
333 =pod
334  
335 =encoding UTF-8
336  
337 =head1 NAME
338  
339 Langertha::Response - LLM response with metadata
340  
341 =head1 VERSION
342  
343 version 0.503
344  
345 =head1 SYNOPSIS
346  
347 my $response = $engine->simple_chat('Hello');
348  
349 # Stringifies to content (backward compatible)
350 print $response;
351 print "Response: $response\n";
352  
353 # Access metadata
354 say $response->model;
355 say $response->id;
356 say $response->finish_reason;
357  
358 # Token usage
359 say "Prompt tokens: ", $response->prompt_tokens;
360 say "Completion tokens: ", $response->completion_tokens;
361 say "Total tokens: ", $response->total_tokens;
362  
363 # Full raw response
364 use Data::Dumper;
365 print Dumper($response->raw);
366  
367 =head1 DESCRIPTION
368  
369 Wraps LLM response text content together with all available metadata
370 from the API response. Uses C<overload> for string context so existing
371 code treating responses as plain strings continues to work.
372  
373 =head2 Boolean context — a Response is always true
374  
375 C<Langertha::Response> overloads C<bool> to a constant true: the object exists,
376 so it is true, whatever L</content> happens to hold. This is not cosmetic. With
377 only the C<""> overload and C<fallback =E<gt> 1>, Perl derives boolean context
378 from stringification, so a Response whose content is the empty string was
379 B<false> — and that is exactly the shape of a tool-call-only reply (an
380 Anthropic turn that is pure C<tool_use>, an Ollama reply with empty
381 C<message.content> plus a C<tool_calls> array), as well as of a model that
382 legitimately answers C<"0">. Callers writing
383  
384 my $resp = $engine->simple_chat(@messages);
385 if ($resp) { ... } # entered now; silently skipped before
386 $resp or die "no response"; # no longer dies on a perfectly good Response
387  
388 used to drop precisely the responses that carry L</tool_calls>. Decided in
389 karr #100.
390  
391 Asking whether the B<content> is empty is a different question, and keeps its
392 own spelling:
393  
394 if ( length "$resp" ) { ... } # the model produced text
395 if ( $resp->has_tool_calls ) { ... } # the model emitted tool calls
396  
397 The C<""> overload is unchanged — C<"$response"> is still L</content>, and
398 C<eq>, C<ne> and concatenation keep routing through it. The change also makes
399 this class agree with the rest of the distribution: L<Langertha::ToolCall>,
400 L<Langertha::Usage> and L<Langertha::Stream::Chunk> are already
401 true-because-they-exist. L<Langertha::Result> got the same treatment for the
402 same reason.
403  
404 =head2 TO_JSON — the canonical, bounded representation
405  
406 C<Langertha::Response> carries a C<TO_JSON> (delegating to L</to_hash>) so
407 that every L<JSON::MaybeXS> backend encodes a bare Response identically when
408 C<convert_blessed> is enabled. Decided in karr #50, after karr #43 fixed the
409 permanent shape of the class (L</usage> is now a L<Langertha::Usage> object
410 with its own C<TO_JSON>).
411  
412 The shape is deliberately bounded: L</content> plus the metadata fields that
413 are present (L</id>, L</model>, L</finish_reason>, L</usage>, L</timing>,
414 L</created>, L</thinking>, L</refusal>, L</rate_limit>, L</tool_calls>).
415 L</raw> and L</probes> are B<not> included — L</raw> is the entire provider payload
416 (duplicating every other field, including the echoed prompt) and L</probes>
417 can hold megabytes of tensor data. A C<TO_JSON> that kept them would blow up
418 every trace it touched; one that dropped them keeps the object's JSON form
419 useful without silently discarding the fields a consumer is likely to want.
420  
421 The string overload is unchanged: C<"$response"> still returns
422 L</content>, and the C<TO_JSON> does not replace it.
423  
424 =for stopwords Cpanel
425  
426 B<Backend uniformity is the point.> Before this method existed, what an
427 encoder with C<convert_blessed> did with a bare Response depended on the
428 L<JSON::MaybeXS> backend: L<Cpanel::JSON::XS> fell back to the C<"">
429 overload and emitted the content string, while L<JSON::XS> and L<JSON::PP>
430 threw. Consumers on Cpanel silently got C<{"response":"hello"}>, consumers
431 on JSON::XS/JSON::PP got an exception — the same application behaved
432 differently on two machines. With C<TO_JSON> all three emit the canonical
433 hash. The Cpanel behavior was never a contract (it is gone now); callers
434 that want the content string should stringify explicitly.
435  
436 =head2 content
437  
438 The text content of the response. Required.
439  
440 =head2 raw
441  
442 The full parsed API response as a HashRef.
443  
444 =head2 id
445  
446 Provider-specific response ID.
447  
448 =head2 model
449  
450 The actual model used for the response.
451  
452 =head2 finish_reason
453  
454 Why the response ended: C<stop>, C<end_turn>, C<length>, C<tool_calls>, etc.
455 Provider-specific values are preserved as-is.
456  
457 =head2 usage
458  
459 Token usage as a L<Langertha::Usage> object. For backward compatibility
460 C<BUILDARGS> upgrades a plain HashRef (the raw provider usage block) into a
461 C<Langertha::Usage> automatically; new code can construct the object
462 directly. The object overloads C<%{}>, so existing callers that dereference
463 C<< $response->usage->{prompt_tokens} >> keep working — the overload returns
464 the provider-verbatim hash (see L<Langertha::Usage/"HASH OVERLOAD">).
465  
466 =head2 timing
467  
468 Timing information as a HashRef. Holds client-measured
469 C<ttft_seconds> and C<total_seconds> (Float, seconds) on every engine,
470 plus provider-native stage durations that engines may populate
471 engine-specifically — e.g. Ollama's C<total_seconds>, C<load_seconds>,
472 C<prompt_eval_seconds>, C<eval_seconds> (all Float, seconds), with its
473 original C<*_duration> keys in nanoseconds preserved for backward
474 compatibility. See L</ttft_seconds> and L</total_seconds> for the
475 standard accessors.
476  
477 =for stopwords first-write-wins
478  
479 B<Merge policy: first-write-wins.> When both a provider-supplied duration
480 (e.g. Ollama's C<total_seconds> derived from C<total_duration>) and a
481 client-measured duration (Langertha::Role::Chat wrapper) are available
482 for the same key, the provider value wins. See
483 L<Langertha::Role::Chat/_merge_timing_field> and ADR 0011 in
484 F<docs/adr/0011-response-timing-seam.md> for the rationale — server-side
485 duration excludes network jitter and is the better signal for
486 model-latency observability. Callers that need the client wall-clock
487 (RTT, queue, TLS handshake, network back) should read
488 C<$response-E<gt>timing> directly: client-measured deltas are not
489 written under C<ttft_seconds> / C<total_seconds> when the provider
490 already populated those keys, but L<Langertha::Role::Chat> does not
491 delete other timing entries on conflict.
492  
493 =head2 ttft_seconds
494  
495 my $ttft = $response->ttft_seconds; # Float, undef when unmeasured
496 if ($response->has_ttft) { ... }
497  
498 Returns time-to-first-token in seconds (Float), measured client-side
499 between request send and the first streamed chunk. C<undef> for sync
500 (non-streaming) calls and for engines that did not record the metric.
501 Use C<has_ttft> to test availability without warnings.
502  
503 =head2 total_seconds
504  
505 my $total = $response->total_seconds; # Float, undef when unmeasured
506 if ($response->has_total) { ... }
507  
508 Returns end-to-end request time in seconds (Float). On engines that
509 populate the field from a provider-native metric (currently Ollama,
510 from C<total_duration>), this is the B<server-reported> duration —
511 time the model actually spent generating, excluding network jitter.
512 On engines where only the client wrapper measured, it is the
513 B<wall-clock> duration from before C<user_agent-E<gt>request> (sync) or
514 C<do_request> (async) to after the response body was fully consumed.
515  
516 =for stopwords RTT
517  
518 The two are not interchangeable: server-time answers "how fast is the
519 model", wall-clock answers "how long did my call take end-to-end".
520 Callers that need the wall-clock RTT should read C<$response-E<gt>timing>
521 directly (the client wrapper writes its measurement under a sibling key
522 when the provider has not claimed C<total_seconds>; when both are
523 present the provider value wins — see L</timing>).
524  
525 C<undef> when the engine did not record the metric. Use C<has_total>
526 to test availability without warnings.
527  
528 =head2 created
529  
530 The instant the provider says the response was created, as a
531 L<Langertha::Moment> — a L<Time::Moment> subclass, so the full civil time is
532 there: sub-seconds, UTC offset, and every L<Time::Moment> accessor.
533  
534 B<In numeric context it is the Unix timestamp it always was.> The C<0+>
535 overload yields whole seconds since the epoch, so C<0 + $response-E<gt>created>,
536 C<< $response->created > $cutoff >> and C<< int($response->created) >> keep
537 returning exactly what they returned when this attribute was a C<Maybe[Int]>.
538 In string context it is the full ISO-8601 stamp instead — which is where the
539 sub-seconds are, and which is B<not> what the old C<Int> stringified to. See
540 L</"Comparing and printing created"> below.
541  
542 Engine-agnostic by contract, and normalized here rather than per engine:
543 C<BUILDARGS> runs every incoming value through
544 L<Langertha::Moment/from_wire>, which takes the OpenAI-compatible wire's epoch
545 integer and Ollama's RFC3339 C<created_at> string alike. A value it cannot
546 read — including the C<0001-01-01T00:00:00Z> zero-value sentinel Go-based
547 servers emit — B<drops the field> instead of failing the constructor:
548 C<has_created> is then false and the response is built regardless. A timestamp
549 is metadata and must never take a whole reply down with it (GitHub issue #3,
550 karr #92 / #117).
551  
552 The provider's native form always stays available verbatim under L</raw>
553 (C<raw.created> on the OpenAI-compatible wire, C<raw.created_at> on Ollama).
554  
555 =head2 Comparing and printing created
556  
557 Numeric context, arithmetic and comparison are unchanged from the old C<Int>:
558  
559 0 + $response->created # 1700000000
560 $response->created == 1700000000 # true
561 $response->created > $cutoff # true/false, as before
562 sprintf '%d', $response->created # 1700000000
563 sort { $a->created <=> $b->created } @responses
564  
565 Three idioms do B<not> survive the change to an object:
566  
567 =over
568  
569 =item * B<String context is the stamp, not the digits.>
570 C<"$response-E<gt>created"> now interpolates C<2023-11-14T22:13:20Z>, so
571 C<eq> against the epoch digits is false and a hash keyed by C<created> re-keys
572 itself. Write C<0 + $response-E<gt>created> where the number is what is
573 wanted. This is the point of the change, not a side effect — the string form
574 is where the sub-seconds are.
575  
576 =item * B<C<ref> and C<blessed> are no longer empty.> Code branching on
577 whether the field is a reference takes the other path now.
578  
579 =item * B<A JSON encoder without C<convert_blessed> dies on it> — the same
580 way it already dies on L</usage>, L</tool_calls> and L</rate_limit>, which
581 have been objects for longer. With C<convert_blessed> enabled it encodes as
582 the epoch number, because L<Langertha::Moment> carries a C<TO_JSON> that says
583 so. L</to_hash> and C<TO_JSON> on the Response itself are unaffected: they
584 emit a plain number either way.
585  
586 =back
587  
588 One smaller change: C<created> is now true in boolean context even when the
589 stamp is the epoch zero, where the old C<Int> C<0> was false. L</has_created>
590 is the predicate for "did the provider report a stamp", and it is unaffected.
591  
592 =head2 cached_tokens
593  
594 Number of prompt tokens served from the prefix cache (the cache B<read>
595 count), when the provider reports it. This is the engine-agnostic back-compat
596 accessor: C<BUILDARGS> lifts it off the L<Langertha::Usage> object's
597 L<Langertha::Usage/cached_tokens>, which parses it from either wire spelling —
598 C<usage.prompt_tokens_details.cached_tokens> on the OpenAI-compatible wire
599 (SGLang with C<return_cached_tokens_details> enabled, and other servers that
600 emit the detail block) or C<usage.cache_read_input_tokens> on Anthropic. An
601 explicit C<cached_tokens> constructor parameter always wins. C<undef> when the
602 provider does not report a cache-read count.
603  
604 The cache B<write> count has no Response accessor — read it from the usage
605 object as C<< $response->usage->cache_write_tokens >>
606 (L<Langertha::Usage/cache_write_tokens>).
607  
608 =head2 tool_calls
609  
610 ArrayRef of L<Langertha::ToolCall> objects extracted from the
611 response, when the engine produced any. Single source of truth for
612 "what tool calls did the model emit" — both native provider tool
613 calling and synthesized fallbacks (forced-name via response_format)
614 land here in the same shape.
615  
616 For backward compatibility C<BUILDARGS> upgrades plain HashRefs
617 (C<{ name =E<gt> ..., arguments =E<gt> ..., id =E<gt> ..., synthetic =E<gt> ... }>)
618 into L<Langertha::ToolCall> objects automatically; new code should
619 construct the objects directly.
620  
621 =head2 tool_call
622  
623 my $tc = $response->tool_call; # first tool call
624 my $tc = $response->tool_call($name); # named lookup
625  
626 Returns the L<Langertha::ToolCall> for the first tool call (or the
627 first matching C<$name>), or C<undef> when no tool calls were
628 produced.
629  
630 =head2 tool_call_args
631  
632 my $args = $response->tool_call_args; # first tool call
633 my $args = $response->tool_call_args($name); # named lookup
634  
635 Returns the C<arguments> HashRef of the first tool call, or of the
636 first tool call matching C<$name>. Returns C<undef> when no tool
637 calls were produced.
638  
639 =head2 server_tool_calls
640  
641 ArrayRef of L<Langertha::ServerToolCall> records: the tool calls the
642 B<provider> ran itself during this request (a C<web_search_call>, an
643 C<mcp_call>, ...), in wire order, when there were any. They are deliberately
644 B<not> on L</tool_calls>, which lists only calls the client must execute, so
645 C<chat_with_tools_f> and C<chat_f> callers never try to run a web search
646 themselves (ADR 0003 Update k206, ADR 0030). Each record carries the item
647 verbatim in C<data>. Set by the Responses wire
648 (L<Langertha::Engine::OpenAIResponses>); C<undef> elsewhere. Survives
649 L</clone_with>. Not part of L</to_hash> / C<TO_JSON> (the bounded shape, like
650 L</citations>); read the attribute.
651  
652 =head2 rate_limit
653  
654 Optional L<Langertha::RateLimit> object with rate limit information from the
655 API response headers. Only present when the provider returns rate limit headers.
656  
657 =head2 thinking
658  
659 Chain-of-thought reasoning content. Populated automatically from native API
660 fields (DeepSeek C<reasoning_content>, Anthropic C<thinking> blocks, Gemini
661 C<thought> parts) or from C<E<lt>thinkE<gt>> tag filtering when
662 L<Langertha::Role::ThinkTag/think_tag_filter> is enabled.
663  
664 =head2 refusal
665  
666 The model's refusal text, when the provider reports a refusal in a field of
667 its own instead of as content: the OpenAI-compatible C<message.refusal> (a
668 structured-output request the model declined; C<content> is then empty) and a
669 Responses API C<refusal> content part. L</content> stays what the model
670 answered, usually C<''>, so check C<has_refusal> before treating an empty
671 reply as empty. A refusal that arrives as a stop reason (Anthropic
672 C<stop_reason> C<refusal>) is in L</finish_reason> instead. Survives
673 L</clone_with>.
674  
675 =head2 citations
676  
677 Search-augmented source citations, when the provider reports them. An ArrayRef
678 of source HashRefs (each typically carrying C<url>, C<title>, and where
679 available C<snippet>/C<date>). Populated by search-augmented engines that lift
680 them out of the raw payload — L<Langertha::Engine::Perplexity> extracts the
681 Agent API's C<search_results> block here (the classic Sonar top-level
682 C<citations[]> is gone), and the Responses wire adds the answer's
683 C<url_citation> annotations as C<< { url, title, start_index, end_index } >>
684 (the url verbatim, including OpenAI's C<?utm_source=openai>). One page is
685 listed once: entries are deduplicated by url, compared without C<utm_*>
686 query parameters, keeping the first entry and filling in only fields it
687 lacks. C<undef> for every engine that does not report
688 citations. Survives L</clone_with> so it is preserved through C<E<lt>thinkE<gt>>
689 tag filtering.
690  
691 =head2 probes
692  
693 Provider-specific probe data returned by L<Langertha::Engine::VLLMHook> when a
694 vLLM-Hook server captures attention or hidden-state tensors for a request. A
695 HashRef keyed by probe cache name (e.g. C<qk_cache>, C<hs_cache>) — each cache
696 holding serialized tensors as nested JSON lists, plus an optional C<config>
697 block of scalar metadata. C<undef> for every other engine. Survives
698 L</clone_with> so it is preserved through C<E<lt>thinkE<gt>> tag filtering.
699  
700 =head2 clone_with
701  
702 my $new = $response->clone_with(content => $filtered, thinking => $thought);
703  
704 Returns a new Response with the same attributes as the original, except for
705 the overrides provided. Used by L<Langertha::Role::ThinkTag> to produce a
706 filtered response while preserving metadata.
707  
708 Every read-only attribute with a C<has_*> predicate is automatically carried
709 forward — the implementation iterates the Moose metaclass rather than
710 maintaining a hand-rolled list, so new attributes added to
711 L<Langertha::Response> are picked up without further changes here. Required
712 attributes (currently just C<content>) are handled explicitly above the
713 loop. Attributes whose names appear in C<%overrides> are skipped during the
714 copy so the override value is what reaches C<new>.
715  
716 =head2 to_hash
717  
718 my $hash = $response->to_hash;
719  
720 Returns the canonical, bounded HashRef representation of the response:
721 C<content> plus every metadata field that is present (L</id>, L</model>,
722 L</finish_reason>, L</usage>, L</timing>, L</created>, L</cached_tokens>,
723 L</thinking>, L</refusal>, L</rate_limit>, L</tool_calls>). L</raw> and
724 L</probes> are deliberately excluded — see L</"TO_JSON — the canonical, bounded
725 representation">.
726  
727 L</created> is emitted as a plain epoch number (via its C<0+> overload), not
728 as the L<Langertha::Moment> object — the hash is a bounded interop shape and
729 that key has been a number since it existed.
730  
731 =head2 prompt_tokens
732  
733 Returns the number of prompt/input tokens. Reads the normalized
734 C<input_tokens> attribute of the L<Langertha::Usage> object (which
735 L<Langertha::Usage/from_hash> maps from C<prompt_tokens>,
736 C<input_tokens>, or C<prompt_eval_count>).
737  
738 =head2 completion_tokens
739  
740 Returns the number of completion/output tokens. Reads the normalized
741 C<output_tokens> attribute of the L<Langertha::Usage> object (which
742 L<Langertha::Usage/from_hash> maps from C<completion_tokens>,
743 C<output_tokens>, or C<eval_count>).
744  
745 =head2 total_tokens
746  
747 Returns the total token count. Reads the C<total_tokens> attribute of the
748 L<Langertha::Usage> object — the provider-supplied value when present,
749 otherwise the sum of prompt and completion tokens (lazy builder).
750  
751 =head2 requests_remaining
752  
753 Returns the number of requests remaining from rate limit headers, or C<undef>.
754  
755 =head2 tokens_remaining
756  
757 Returns the number of tokens remaining from rate limit headers, or C<undef>.
758  
759 =head1 SEE ALSO
760  
761 =over
762  
763 =item * L<Langertha::RateLimit> - Rate limit data from response headers
764  
765 =item * L<Langertha::Stream::Chunk> - Single chunk from a streaming response
766  
767 =item * L<Langertha::Role::Chat> - Chat role that produces response objects
768  
769 =item * L<Langertha::Role::OpenAICompatible> - Parses responses into this class
770  
771 =back
772  
773 =head1 SUPPORT
774  
775 =head2 Issues
776  
777 Please report bugs and feature requests on GitHub at
778 L<https://github.com/Getty/langertha/issues>.
779  
780 =head2 IRC
781  
782 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
783  
784 =head1 CONTRIBUTING
785  
786 Contributions are welcome! Please fork the repository and submit a pull request.
787  
788 =head1 AUTHOR
789  
790 Torsten Raudssus <getty@cpan.org>
791  
792 =head1 COPYRIGHT AND LICENSE
793  
794 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
795  
796 This is free software; you can redistribute it and/or modify it under
797 the same terms as the Perl 5 programming language system itself.
798  
799 =cut
« blib/lib/Langertha/ServerToolCall.pm ↑ Summary blib/lib/Langertha/Runtime/Knobs.pm »