blib/lib/Langertha/Role/AnthropicCompatible.pm

filter: Statementstmt 94.8% 276 / 291 Branchbran 85.6% 197 / 230 Conditioncond 64.2% 81 / 126 MC/DCmcdc 31.2% 20 / 64 Subroutinesub 95.1% 39 / 41 Podpod 81.8% 9 / 11 totaltotal 81.5% 622 / 763 CC 172 SCAR 29.9
CC
172
Cov
86%
parse_stream_chunk
45.2
chat_stream_request
34.7
chat_response
21.9
CRAP 19.9
« blib/lib/Langertha/Role/Langfuse.pm ↑ Summary blib/lib/Langertha/HTTP/Redirect.pm »
1 package Langertha::Role::AnthropicCompatible;
2 # ABSTRACT: Role for Anthropic-compatible API format
3 68 our $VERSION = '0.505';
4 68 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 68 ▶use Carp qw( croak carp );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 68 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 68 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 68 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 68 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 68 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12  
13 264 ▶sub _build_reasoning_wire_format { 'anthropic' }
Subroutine _build_reasoning_wire_format: called CC=1 SCAR=0.0
14 5 ▶sub _build_cache_wire_format { 'anthropic' }
Subroutine _build_cache_wire_format: called CC=1 SCAR=0.0
15  
16 194 ▶sub default_response_size { 1024 }
Subroutine default_response_size: called CC=1 SCAR=0.0
Pod undocumented
17  
18 50 ▶sub content_format { 'anthropic' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod undocumented
19  
20 68 has api_key => (
21 is => 'ro',
22 lazy_build => 1,
23 );
24 0 ▶sub _build_api_key {
Subroutine _build_api_key: not called CC=1 SCAR=6.9
25 0 my ( $self ) = @_;
26 0 return croak "".(ref $self)." requires api_key to be set";
27 }
28  
29  
30 68 has api_version => (
31 is => 'ro',
32 lazy_build => 1,
33 );
34 435 ▶sub _build_api_version { '2023-06-01' }
Subroutine _build_api_version: called CC=1 SCAR=0.0
35  
36  
37 68 has effort => (
38 is => 'ro',
39 isa => 'Str',
40 predicate => 'has_effort',
41 );
42  
43  
44 68 has inference_geo => (
45 is => 'ro',
46 isa => 'Str',
47 predicate => 'has_inference_geo',
48 );
49  
50  
51 595 ▶sub update_request {
Subroutine update_request: called CC=1 SCAR=0.0
Pod documented
52 595 my ( $self, $request ) = @_;
53 595 $request->header('x-api-key', $self->api_key);
54 595 $request->header('content-type', 'application/json');
55 595 $request->header('anthropic-version', $self->api_version);
56 }
57  
58  
59 391 ▶sub chat_request {
Subroutine chat_request: called CC=13 SCAR=25.8
Pod documented
60 391 my ( $self, $messages, %extra ) = @_;
61  
62 # Canonical per-request controls (chat_f, karr #46) beat the engine
63 # attributes on a per-key basis; the rest of %extra passes straight through.
64 391 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
249142
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
65  
66 # Structured output. Engines whose wire has native structured output
67 # (Engine::Anthropic, via _native_structured_output) emit it as
68 # output_config.format and leave the content JSON on the wire (chat_response
69 # returns it verbatim). Engines without it (the legacy /anthropic shims)
70 # keep the ADR 0005 synthesized-tool + forced tool_choice rewrite, whose
71 # tool_use input chat_response lifts back into content.
72 391 my $rf_routed = 0;
73 391 my $output_config_format;
74 391 ▶ if ( $self->_native_structured_output_for_model ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_native_structured_output_for_model) { } 190 201 391
75 190 my $rf = $self->_take_response_format(\%extra, $controls);
76 # A schema-bearing response_format goes native (output_config.format); the
77 # first-party validator rejects an open schema, so it is normalized to a
78 # closed one first (k182/k149). A bare json_object has no schema and the
79 # Messages API has no native free-form JSON form, so it routes through the
80 # synthesized-tool path (open, non-strict input_schema) exactly like the
81 # legacy /anthropic shims -- forced where the model allows it, degraded to
82 # tool_choice `auto` where forced tool use 400s (fable-5-1 / mythos-5-1).
83 190 ▶ if ( $self->_rf_is_native_schema($rf) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_rf_is_native_schema($rf)) { } 11 179 190
84 11 $output_config_format = $self->_response_format_to_output_config($rf);
85 }
86 else {
87 # // 0 keeps $rf_routed defined (a non-honorable rf yields undef) so
88 # chat_response does not fall back to the has_response_format heuristic.
89 179 ▶ $rf_routed = $self->_response_format_via_tool($rf, \%extra) // 0;
Condition100%2/2
$self->_response_format_via_tool($rf, \%extra) // 0
l!l
4175
MC/DC100%1/1
$self->_response_format_via_tool($rf, \%extra) // 0
$self->_response_format_via_tool($rf, \%extra)
Truth table100%2/2
A
A= $self->_response_format_via_tool($rf, \%extra)
Aresult
11
00
90 }
91 }
92 else {
93 201 $rf_routed = $self->_translate_response_format(\%extra, $controls);
94 }
95  
96 391 $self->_normalize_tool_params(\%extra, $controls);
97 391 my @msgs;
98 391 my $system = "";
99 391 for my $message (@{$messages}) {
100 424 ▶ if ($message->{role} eq 'system') {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{'role'} eq 'system') { } 9 415 424
101 9 ▶ $system .= "\n\n" if length $system;
Branch: 1 branch
BranchTrueFalseTotal
if length $system 0 9 9
102 9 $system .= $message->{content};
103 } else {
104 415 push @msgs, $message;
105 }
106 }
107 391 ▶ if ($system and scalar @msgs == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($system and scalar @msgs == 0) 0 391 391
Condition66%2/3
$system and scalar @msgs == 0
!ll&&!rl&&r
38290
MC/DC0%0/2
$system and scalar @msgs == 0
$system scalar @msgs == 0
Truth table66%2/3
A and B
A= $systemB= scalar @msgs == 0
ABresult
0X0
100
111
108 0 push @msgs, {
109 role => 'user',
110 content => $system,
111 };
112 0 $system = undef;
113 }
114  
115 391 my %generation = $self->generation_kwargs_for(%$controls);
116 369 $self->_merge_output_config_format( \%generation, $output_config_format );
117  
118 28 ▶ return $self->generate_http_request( POST => $self->url.'/v1/messages', sub { $self->chat_response(shift, $rf_routed) },
Subroutine __ANON__: called CC=1 SCAR=0.0
119 model => $self->chat_model,
120 messages => \@msgs,
121 exists $controls->{max_tokens}
122 ? ( max_tokens => $controls->{max_tokens} )
123 369 ▶ : ( max_tokens => $self->get_response_size ), # must be always set
Branch: 3 branches
BranchTrueFalseTotal
exists $controls->{'max_tokens'} ? : 5 364 369
$self->has_inference_geo ? : 1 368 369
$system ? : 9 360 369
124 $self->_temperature_kwargs($controls),
125 %generation,
126 $self->has_inference_geo ? ( inference_geo => $self->inference_geo ) : (),
127 $system ? ( system => $system ) : (),
128 %extra,
129 );
130 }
131  
132  
133 # Whether this engine's wire has native structured output (output_config.format,
134 # GA on the first-party Claude API — see ADR 0005 amendment). Default no: the
135 # legacy /anthropic shim engines (MiniMax, Moonshot, AKI, LM Studio) keep the
136 # synthesized-tool rewrite. Engine::Anthropic overrides this to a true value.
137 212 ▶sub _native_structured_output { 0 }
Subroutine _native_structured_output: called CC=1 SCAR=0.0
138  
139  
140 # Whether THIS request's chat_model takes native output_config.format. Defaults
141 # to the endpoint predicate above; a shim whose endpoint documents the native
142 # form for some models only overrides this one (MoonshotAnthropic: kimi-k3,
143 # karr k218), so the endpoint -- and its manifest dialect -- stays a shim.
144 417 ▶sub _native_structured_output_for_model {
Subroutine _native_structured_output_for_model: called CC=1 SCAR=0.0
145 417 my ( $self ) = @_;
146 417 return $self->_native_structured_output;
147 }
148  
149  
150 # Pull a response_format hash out of the per-request controls / %extra / engine
151 # attribute (per-request beats engine attribute, chat_f/karr #46) and remove it
152 # from both — the Messages API has no top-level response_format field and 400s
153 # when one reaches the wire, on every structured-output path.
154 629 ▶sub _take_response_format {
Subroutine _take_response_format: called CC=4 SCAR=13.9
155 629 my ( $self, $extra, $controls ) = @_;
156 return exists $controls->{response_format}
157 ? delete $controls->{response_format}
158 : exists $extra->{response_format}
159 ? delete $extra->{response_format}
160 629 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $controls->{'response_format'} ? : 2 627 629
exists $extra->{'response_format'} ? : 13 614 627
$self->has_response_format ? : 11 603 614
161 }
162  
163 # True when a response_format hash is a json_schema carrying an actual schema
164 # object -- the only form with a native output_config.format home. A bare
165 # json_object (no schema) is not: it has no closed native form and routes
166 # through the synthesized-tool path instead (k182).
167 282 ▶sub _rf_is_native_schema {
Subroutine _rf_is_native_schema: called CC=6 SCAR=18.4
168 282 my ( $self, $rf ) = @_;
169 282 ▶ return 0 unless ref($rf) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rf eq "HASH" 247 35 282
170 35 ▶ return 0 unless ( $rf->{type} // '' ) eq 'json_schema';
Branch: 1 branch
BranchTrueFalseTotal
unless ($rf->{"type"} // "") eq "json_schema" 7 28 35
Condition50%1/2
$rf->{"type"} // ""
l!l
350
MC/DC0%0/1
$rf->{"type"} // ""
$rf->{"type"}
Truth table50%1/2
A
A= $rf->{"type"}
Aresult
11
00
171 28 ▶ return 0 unless ref( $rf->{json_schema} ) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rf->{"json_schema"} eq "HASH" 0 28 28
172 28 ▶ return ref( $rf->{json_schema}{schema} ) eq 'HASH' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $rf->{'json_schema'}{'schema'} eq 'HASH' ? : 28 0 28
173 }
174  
175 # Turn a json_schema response_format into the native output_config.format value.
176 # The first-party validator requires a CLOSED schema (additionalProperties:false
177 # on every object) and 400s on anything else, so the caller's schema is
178 # normalized to closed rather than passed through unchanged (k182/k149). Returns
179 # undef when the hash is not a native json_schema (json_object has no schema and
180 # goes via the synthesized-tool path).
181 14 ▶sub _response_format_to_output_config {
Subroutine _response_format_to_output_config: called CC=2 SCAR=7.1
182 14 my ( $self, $rf ) = @_;
183 14 ▶ return undef unless $self->_rf_is_native_schema($rf);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_rf_is_native_schema($rf) 0 14 14
184 return {
185 type => 'json_schema',
186 14 schema => $self->_close_schema( $rf->{json_schema}{schema} ),
187 };
188 }
189  
190 # Normalize a JSON Schema for the first-party output_config.format validator,
191 # which requires additionalProperties:false on every object and rejects an open
192 # schema (k182/k149). Recurses the standard schema carriers and sets
193 # additionalProperties:false on each object that does not already close itself,
194 # without mutating the caller's schema. An additionalProperties that is itself a
195 # schema — a dictionary/map value type, e.g. { type => 'string' } — is kept and
196 # recursed as a subschema, not clobbered to false (k183): only an absent or
197 # truthy-boolean additionalProperties means "open object" and gets closed. This
198 # is the house "normalize the wire quirk, don't gatekeep" stance; a caller who
199 # wants genuinely free-form JSON uses response_format json_object, which routes
200 # through the non-strict tool path.
201 32 ▶sub _close_schema {
Subroutine _close_schema: called CC=14 SCAR=28.1
202 32 my ( $self, $node ) = @_;
203 32 ▶ return $node unless ref($node) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" 0 32 32
204 32 my %out = %$node;
205 32 ▶ if ( ( ( $out{type} // '' ) eq 'object' ) || exists $out{properties} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($out{"type"} // "") eq "object" or exists $out{"properties"}) 17 15 32
Condition60%3/5
($out{"type"} // "") eq "object" or exists $out{"properties"}
l!l&&r!l&&!r
17015
$out{"type"} // ""
l!l
320
MC/DC0%0/2
($out{"type"} // "") eq "object" or exists $out{"properties"}
$out{"type"} exists $out{"properties"}
Truth table33%1/3
A or B
A= $out{"type"}B= exists $out{"properties"}
ABresult
1X1
011
000
206 17 my $ap = $out{additionalProperties};
207 17 ▶ if ( ref $ap eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $ap eq 'HASH') { } 2 15 17
elsif (not exists $out{'additionalProperties'} or $ap) { } 14 1 15
208 # A map/dictionary value schema: recurse into it, keep it as a schema.
209 2 $out{additionalProperties} = $self->_close_schema($ap);
210 }
211 ▶ elsif ( !exists $out{additionalProperties} || $ap ) {
Condition66%2/3
not exists $out{"additionalProperties"} or $ap
l!l&&r!l&&!r
1401
MC/DC50%1/2
not exists $out{"additionalProperties"} or $ap
not exists $out{"additionalProperties"} $ap
Truth table66%2/3
not(A) or B
A= not exists $out{"additionalProperties"}B= $ap
ABresult
1X1
011
000
212 # Absent, or a truthy boolean (JSON true) -> close the object.
213 14 $out{additionalProperties} = JSON->false;
214 }
215 # else: already explicitly false -> leave it closed.
216 }
217 32 ▶ if ( ref $out{properties} eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $out{"properties"} eq "HASH") 15 17 32
218 $out{properties} = {
219 16 map { $_ => $self->_close_schema( $out{properties}{$_} ) }
220 15 keys %{ $out{properties} }
221 };
222 }
223 32 ▶ $out{items} = $self->_close_schema( $out{items} ) if ref $out{items} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $out{"items"} eq "HASH" 0 32 32
224 32 for my $key (qw( anyOf allOf oneOf )) {
225 0 $out{$key} = [ map { $self->_close_schema($_) } @{ $out{$key} } ]
226 96 ▶ if ref $out{$key} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $out{$key} eq "ARRAY" 0 96 96
227 }
228 32 for my $key (qw( $defs definitions )) {
229 $out{$key} = {
230 0 map { $_ => $self->_close_schema( $out{$key}{$_} ) } keys %{ $out{$key} }
231 64 ▶ } if ref $out{$key} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $out{$key} eq "HASH" 0 64 64
232 }
233 32 return \%out;
234 }
235  
236 # Fold a native structured-output format into output_config, MERGING rather than
237 # replacing: Langertha::Reasoning::to_anthropic already puts effort under the
238 # same output_config key, so a naive second output_config would silently drop
239 # one of the two (k133 point 3). Mutates the generation-kwargs hash in place.
240 580 ▶sub _merge_output_config_format {
Subroutine _merge_output_config_format: called CC=3 SCAR=11.0
241 580 my ( $self, $generation, $format ) = @_;
242 580 ▶ return unless $format;
Branch: 1 branch
BranchTrueFalseTotal
unless $format 566 14 580
243 14 my $oc = $generation->{output_config};
244 $generation->{output_config} = {
245 14 ▶ ( ref($oc) eq 'HASH' ? %$oc : () ),
Branch: 1 branch
BranchTrueFalseTotal
ref $oc eq 'HASH' ? : 2 12 14
246 format => $format,
247 };
248 14 return;
249 }
250  
251 # temperature / top_p / top_k are deprecated on the Messages API and 400 with a
252 # non-default value on a growing set of models (Opus 4.7+ and the 5-series);
253 # Engine::Anthropic clears the `temperature` capability for those via
254 # model_capability_corrections (k138), and this gate keeps the field off the
255 # wire whenever the selected model rejects it — whether it came from the engine
256 # attribute or a per-request control (k135 point 1). The same capability clear
257 # covers Kimi's /anthropic face, where every current id fixes temperature
258 # server-side (karr k214). A caller-set non-default value that the gate drops
259 # carps (ADR 0025 k214 Update) -- that drop used to be silent; 1 is dropped
260 # quietly.
261 580 ▶sub _temperature_kwargs {
Subroutine _temperature_kwargs: called CC=11 SCAR=24.1
262 580 my ( $self, $controls ) = @_;
263 my $temp = exists $controls->{temperature} ? $controls->{temperature}
264 580 ▶ : $self->has_temperature ? $self->temperature
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'temperature'} ? : 15 565 580
$self->has_temperature ? : 43 522 565
265 : undef;
266 580 ▶ return () unless defined $temp;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $temp 522 58 580
267 # An engine attribute is the same on every request: warn once per engine
268 # instance (karr k247); a per-request control warns every time.
269 my $once = exists $controls->{temperature} ? undef
270 58 ▶ : 'temperature=' . $temp . ' model=' . ( $self->can('chat_model') ? $self->chat_model // '' : '' );
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'temperature'} ? : 15 43 58
$self->can('chat_model') ? : 43 0 43
Condition50%1/2
$self->chat_model // ""
l!l
430
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
271 58 ▶ unless ( $self->supports('temperature') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->supports("temperature")) 45 13 58
272 45 ▶ $self->_langertha_carp( "".( ref $self ).": dropping temperature=$temp -- model '"
Branch: 2 branches
BranchTrueFalseTotal
if $temp != 1 34 11 45
defined $once ? : 23 11 34
Condition50%1/2
$self->chat_model // ""
l!l
340
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
273 . ( $self->chat_model // '' )
274 . "' does not take a temperature (rejected or fixed server-side); "
275 . "unset temperature to silence this",
276 defined $once ? "$once unsupported" : undef )
277 if $temp != 1;
278 45 return ();
279 }
280 13 return ( temperature => $temp );
281 }
282  
283 # Anthropic has no response_format; emulate via a synthetic tool plus
284 # a forced tool_choice. The response_call will detect the synthetic
285 # tool_use block and lift its input back into the response content.
286 68 my $SYNTH_RF_TOOL_NAME = '__langertha_response_format__';
287  
288 201 ▶sub _translate_response_format {
Subroutine _translate_response_format: called CC=1 SCAR=0.0
289 201 my ( $self, $extra, $controls ) = @_;
290  
291 # A per-request response_format (chat_f, karr #46) beats the engine
292 # attribute, and is removed from the extras either way: the Messages API
293 # has no response_format field and answers 400 when one reaches the wire.
294 201 my $rf = $self->_take_response_format($extra, $controls);
295 201 return $self->_response_format_via_tool( $rf, $extra );
296 }
297  
298 # Build the synthesized tool + tool_choice for a response_format hash, push them
299 # onto %extra, and return the synthetic tool name (undef when the hash is not
300 # honorable). The tool's input_schema is not strict, so an open schema -- a
301 # caller's, or the open-object stand-in for a bare json_object -- passes here
302 # where the native output_config.format validator would 400. The tool is forced
303 # where the model allows forced tool use and degraded to `auto` where it does not
304 # (claude-fable-5-1 / claude-mythos-5-1 clear tool_choice_named, k133 point 2);
305 # under `auto` chat_response lifts the tool_use only if the model emits it, so
306 # free-form json_object has no guaranteed path on those models (k182).
307 380 ▶sub _response_format_via_tool {
Subroutine _response_format_via_tool: called CC=11 SCAR=25.1
308 380 my ( $self, $rf, $extra ) = @_;
309 380 ▶ return unless ref($rf) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rf eq "HASH" 374 6 380
310 6 ▶ my $type = $rf->{type} // '';
Condition50%1/2
$rf->{"type"} // ""
l!l
60
MC/DC0%0/1
$rf->{"type"} // ""
$rf->{"type"}
Truth table50%1/2
A
A= $rf->{"type"}
Aresult
11
00
311  
312 6 my ( $name, $schema, $description );
313 6 ▶ if ( $type eq 'json_schema' && ref( $rf->{json_schema} ) eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'json_schema' and ref $rf->{'json_schema'} eq 'HASH') { } 2 4 6
elsif ($type eq 'json_object') { } 4 0 4
Condition66%2/3
$type eq "json_schema" and ref $rf->{"json_schema"} eq "HASH"
!ll&&!rl&&r
402
MC/DC50%1/2
$type eq "json_schema" and ref $rf->{"json_schema"} eq "HASH"
$type eq "json_schema" ref $rf->{"json_schema"} eq "HASH"
Truth table66%2/3
A and B
A= $type eq "json_schema"B= ref $rf->{"json_schema"} eq "HASH"
ABresult
0X0
100
111
314 2 my $js = $rf->{json_schema};
315 2 ▶ $name = $js->{name} // $SYNTH_RF_TOOL_NAME;
Condition33%1/3
$js->{"name"} // $SYNTH_RF_TOOL_NAME
l!l&&r!l&&!r
200
MC/DC0%0/2
$js->{"name"} // $SYNTH_RF_TOOL_NAME
$js->{"name"} $SYNTH_RF_TOOL_NAME
Truth table33%1/3
A // B
A= $js->{"name"}B= $SYNTH_RF_TOOL_NAME
ABresult
1X1
011
000
316 2 $schema = $js->{schema};
317 2 $description = $js->{description};
318 }
319 elsif ( $type eq 'json_object' ) {
320 4 $name = $SYNTH_RF_TOOL_NAME;
321 4 $schema = { type => 'object', additionalProperties => JSON->true };
322 }
323 else {
324 0 return;
325 }
326 6 ▶ return unless ref($schema) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $schema eq "HASH" 0 6 6
327  
328 6 ▶ my $tool = Langertha::Tool->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $description ? : 0 6 6
329 name => $name,
330 input_schema => $schema,
331 ( defined $description ? ( description => $description ) : () ),
332 )->to_anthropic;
333  
334 6 ▶ $extra->{tools} ||= [];
Condition50%1/2
$extra->{"tools"} ||= []
l!l
06
MC/DC0%0/1
$extra->{"tools"} ||= []
$extra->{"tools"}
Truth table50%1/2
A
A= $extra->{"tools"}
Aresult
11
00
335 6 push @{ $extra->{tools} }, $tool;
336 6 ▶ $extra->{tool_choice} = $self->supports('tool_choice_named')
Branch: 1 branch
BranchTrueFalseTotal
$self->supports('tool_choice_named') ? : 4 2 6
337 ? { type => 'tool', name => $name }
338 : { type => 'auto' };
339 6 return $name;
340 }
341  
342  
343 # Normalize tool_choice (any accepted format -> Anthropic native) and fold
344 # parallel_tool_use into the tool_choice block as Anthropic expects. A
345 # per-request parallel_tool_use control (chat_f, karr #46) beats the engine
346 # attribute.
347 624 ▶sub _normalize_tool_params {
Subroutine _normalize_tool_params: called CC=12 SCAR=25.0
348 624 my ( $self, $extra, $controls ) = @_;
349  
350 624 ▶ if ( exists $extra->{tool_choice} && defined $extra->{tool_choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $extra->{"tool_choice"} and defined $extra->{"tool_choice"}) 16 608 624
Condition66%2/3
exists $extra->{"tool_choice"} and defined $extra->{"tool_choice"}
!ll&&!rl&&r
608016
MC/DC50%1/2
exists $extra->{"tool_choice"} and defined $extra->{"tool_choice"}
exists $extra->{"tool_choice"} defined $extra->{"tool_choice"}
Truth table66%2/3
A and B
A= exists $extra->{"tool_choice"}B= defined $extra->{"tool_choice"}
ABresult
0X0
100
111
351 16 ▶ if ( my $tc = Langertha::ToolChoice->from_hash( $extra->{tool_choice} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tc = "Langertha::ToolChoice"->from_hash($extra->{"tool_choice"})) 16 0 16
352 16 $extra->{tool_choice} = $tc->to( $self->tool_wire_format );
353 }
354 }
355  
356 624 ▶ return unless exists $extra->{tools};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $extra->{"tools"} 551 73 624
357  
358 73 my $ptu;
359 73 ▶ if ( exists $controls->{parallel_tool_use} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $controls->{'parallel_tool_use'}) { } 10 63 73
elsif ($self->can('has_parallel_tool_use') and $self->has_parallel_tool_use) { } 2 61 63
360 10 $ptu = $controls->{parallel_tool_use};
361 }
362 ▶ elsif ( $self->can('has_parallel_tool_use') && $self->has_parallel_tool_use ) {
Condition66%2/3
$self->can("has_parallel_tool_use") and $self->has_parallel_tool_use
!ll&&!rl&&r
0612
MC/DC50%1/2
$self->can("has_parallel_tool_use") and $self->has_parallel_tool_use
$self->can("has_parallel_tool_use") $self->has_parallel_tool_use
Truth table66%2/3
A and B
A= $self->can("has_parallel_tool_use")B= $self->has_parallel_tool_use
ABresult
0X0
100
111
363 2 $ptu = $self->parallel_tool_use;
364 }
365 73 ▶ return unless defined $ptu;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ptu 61 12 73
366  
367 12 my $tc = $extra->{tool_choice};
368 12 ▶ $tc = { type => 'auto' } unless ref($tc) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tc eq "HASH" 10 2 12
369 12 ▶ unless ( exists $tc->{disable_parallel_tool_use} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $tc->{"disable_parallel_tool_use"}) 12 0 12
370 12 ▶ $tc->{disable_parallel_tool_use} = $ptu ? JSON->false : JSON->true;
Branch: 1 branch
BranchTrueFalseTotal
$ptu ? : 5 7 12
371 }
372 12 $extra->{tool_choice} = $tc;
373 }
374  
375  
376 98 ▶sub chat_response {
Subroutine chat_response: called CC=21 SCAR=30.8
Pod documented
377 98 my ( $self, $response, $rf_routed ) = @_;
378 98 my $data = $self->parse_response($response);
379 # An error envelope ({"type":"error","error":{...}}) or an `error` object
380 # without content, delivered with a 200, is no answer: it parsed to content
381 # '' like a model that said nothing. Croak like the k301 OpenAI-compatible
382 # parser -- karr k338.
383 95 ▶ if ( ref $data eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH" and ($data->{"type"} // "") eq "error" || defined $data->{"error"} && !(ref $data->{"content"} eq "ARRAY" && @{$data->{"content"};})) 11 84 95
Condition71%10/14
ref $data eq "HASH" and ($data->{"type"} // "") eq "error" || defined $data->{"error"} && !(ref $data->{"content"} eq "ARRAY" && @{$data->{"content"};})
!ll&&!rl&&r
08411
($data->{"type"} // "") eq "error" or defined $data->{"error"} and not ref $data->{"content"} eq "ARRAY" && @{$data->{"content"};}
l!l&&r!l&&!r
10184
$data->{"type"} // ""
l!l
7916
defined $data->{"error"} and not ref $data->{"content"} eq "ARRAY" && @{$data->{"content"};}
!ll&&!rl&&r
8401
ref $data->{'content'} eq 'ARRAY' && @{$data->{'content'};}
!ll&&!rl&&r
100
MC/DC40%2/5
ref $data eq "HASH" and ($data->{"type"} // "") eq "error" || defined $data->{"error"} && !(ref $data->{"content"} eq "ARRAY" && @{$data->{"content"};})
ref $data eq "HASH" $data->{"type"} defined $data->{"error"} ref $data->{'content'} eq 'ARRAY' @{$data->{'content'};}
Truth table50%3/6
A and B or C and not(D && E)
A= ref $data eq "HASH"B= $data->{"type"}C= defined $data->{"error"}D= ref $data->{'content'} eq 'ARRAY'E= @{$data->{'content'};}
ABCDEresult
0XXXX0
100XX0
101110
11XXX1
1010X1
101101
384 && ( ( $data->{type} // '' ) eq 'error'
385 || ( defined $data->{error}
386 0 && !( ref $data->{content} eq 'ARRAY' && @{ $data->{content} } ) ) ) ) {
387 croak "".( ref $self )." response carried an error: "
388 11 ▶ .( $self->_body_error_text( $data->{error} ) // 'no error message' );
Condition100%2/2
$self->_body_error_text($data->{"error"}) // "no error message"
l!l
101
MC/DC100%1/1
$self->_body_error_text($data->{"error"}) // "no error message"
$self->_body_error_text($data->{"error"})
Truth table100%2/2
A
A= $self->_body_error_text($data->{"error"})
Aresult
11
00
389 }
390 # A malformed/error payload that still parses as a 200 JSON body (a shim
391 # error shape) can lack the `content` array; default it to empty so callers
392 # get graceful empty content rather than a raw deref crash on @{undef}. The
393 # OpenAI path is defensive at the equivalent spot. -- karr k171
394 84 ▶ my @blocks = @{ $data->{content} // [] };
Condition100%2/2
$data->{"content"} // []
l!l
831
MC/DC100%1/1
$data->{"content"} // []
$data->{"content"}
Truth table100%2/2
A
A= $data->{"content"}
Aresult
11
00
395 84 ▶ my $text = join('', map { $_->{text} // '' } grep { $_->{type} eq 'text' } @blocks);
Condition50%1/2
$_->{"text"} // ""
l!l
670
MC/DC0%0/1
$_->{"text"} // ""
$_->{"text"}
Truth table50%1/2
A
A= $_->{"text"}
Aresult
11
00
396 84 ▶ my @thinking = map { $_->{thinking} // '' } grep { $_->{type} eq 'thinking' } @blocks;
Condition50%1/2
$_->{"thinking"} // ""
l!l
90
MC/DC0%0/1
$_->{"thinking"} // ""
$_->{"thinking"}
Truth table50%1/2
A
A= $_->{"thinking"}
Aresult
11
00
397 84 ▶ my $thinking = @thinking ? join("\n", @thinking) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@thinking ? : 8 76 84
398 84 my @tcs = Langertha::ToolCall->extract( $self->tool_wire_format, $data );
399  
400 # If the caller asked for a response_format and we routed it through a
401 # synthesized tool, lift the tool_use input back into the content as
402 # JSON so callers can treat it like any other structured-output result.
403 # chat_request passes the synthesized tool name for both the per-request
404 # and the engine-attribute path; the attribute check stays as the
405 # fallback for callers invoking chat_response directly.
406 84 ▶ $rf_routed = $self->has_response_format unless defined $rf_routed;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rf_routed 57 27 84
407 84 ▶ if ( $rf_routed && @tcs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rf_routed and @tcs) 1 83 84
Condition66%2/3
$rf_routed and @tcs
!ll&&!rl&&r
8301
MC/DC50%1/2
$rf_routed and @tcs
$rf_routed @tcs
Truth table66%2/3
A and B
A= $rf_routedB= @tcs
ABresult
0X0
100
111
408 1 $text = $self->encode_json_text( $tcs[0]->arguments );
409 }
410 return Langertha::Response->new(
411 content => $text,
412 raw => $data,
413 $data->{id} ? ( id => $data->{id} ) : (),
414 $data->{model} ? ( model => $data->{model} ) : (),
415 defined $data->{stop_reason} ? ( finish_reason => $data->{stop_reason} ) : (),
416 84 ▶ $data->{usage} ? ( usage => $self->_wire_usage( $data->{usage} ) ) : (),
Branch: 6 branches
BranchTrueFalseTotal
$data->{'id'} ? : 79 5 84
$data->{'model'} ? : 59 25 84
defined $data->{'stop_reason'} ? : 78 6 84
$data->{'usage'} ? : 23 61 84
defined $thinking ? : 8 76 84
@tcs ? : 23 61 84
417 defined $thinking ? ( thinking => $thinking ) : (),
418 @tcs ? ( tool_calls => [ @tcs ] ) : (),
419 );
420 }
421  
422  
423 # Whether this endpoint counts the cache reads/writes inside usage.input_tokens.
424 # Langertha::Usage infers it from the spelling, and the flat Anthropic keys mean
425 # "beside" -- first-party Anthropic's truth, also documented by MiniMax and
426 # Moonshot. A shim that reuses the spelling but counts the cache inside
427 # input_tokens overrides this to 1 (ADR 0018 tier 3, ADR 0031, k265). undef
428 # keeps the inference.
429 29 ▶sub _usage_input_includes_cache { return }
Subroutine _usage_input_includes_cache: called CC=1 SCAR=0.0
430  
431 # The usage block as it goes onto the Response / the final stream chunk: a copy
432 # carrying the canonical input_includes_cache key when the engine sets one, so
433 # Usage->from_hash reads the same flag on the non-streaming and streaming path.
434 # The wire hash itself is never modified.
435 41 ▶sub _wire_usage {
Subroutine _wire_usage: called CC=4 SCAR=14.1
436 41 my ( $self, $usage ) = @_;
437 41 ▶ return $usage unless ref $usage eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 0 41 41
438 41 my $includes = $self->_usage_input_includes_cache;
439 41 ▶ return $usage unless defined $includes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $includes 29 12 41
440 12 ▶ return { %$usage, input_includes_cache => $includes ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$includes ? : 12 0 12
441 }
442  
443  
444 15 ▶sub stream_format { 'sse' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod documented
445  
446  
447 238 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=21 SCAR=35.5
Pod documented
448 238 my ( $self, $messages, %extra ) = @_;
449  
450 # Canonical per-request controls (chat_f, karr #46) beat the engine
451 # attributes on a per-key basis; the rest of %extra passes straight through.
452 238 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
19345
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
453  
454 # Structured output on the streaming path. Engines with native structured
455 # output (output_config.format) stream it as ordinary text deltas — the JSON
456 # is the content — so it needs no Response lift and streams fine. The legacy
457 # /anthropic shims have no native form; their synthesized-tool rewrite has no
458 # streaming counterpart to the chat_response tool_use lift (ADR 0005), so
459 # rather than silently streaming unstructured text (karr #52 Folge 1) or
460 # leaking response_format onto the wire (Folge 2) they consume the key and
461 # refuse loudly.
462 238 my $rf = $self->_take_response_format(\%extra, $controls);
463 238 my $output_config_format;
464 238 ▶ if ( $self->_native_structured_output_for_model ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_native_structured_output_for_model) { } 78 160 238
elsif (ref $rf eq 'HASH') { } 3 157 160
465 # A json_schema streams as native output_config.format (normalized closed).
466 # A bare json_object has no native free-form form and the synthesized-tool
467 # fallback has no streaming lift, so -- like the shims below -- consume the
468 # key and refuse loudly rather than 400 on the wire or stream unstructured
469 # text (k182, ADR 0005 paragraph 2).
470 78 ▶ if ( $self->_rf_is_native_schema($rf) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_rf_is_native_schema($rf)) { } 3 75 78
elsif (ref $rf eq 'HASH' and ($rf->{'type'} // '') eq 'json_object') { } 2 145 147
471 3 $output_config_format = $self->_response_format_to_output_config($rf);
472 }
473 ▶ elsif ( ref($rf) eq 'HASH' && ( $rf->{type} // '' ) eq 'json_object' ) {
Condition80%4/5
ref $rf eq "HASH" and ($rf->{"type"} // "") eq "json_object"
!ll&&!rl&&r
7212
$rf->{"type"} // ""
l!l
30
MC/DC50%1/2
ref $rf eq "HASH" and ($rf->{"type"} // "") eq "json_object"
ref $rf eq "HASH" $rf->{"type"}
Truth table66%2/3
A and B
A= ref $rf eq "HASH"B= $rf->{"type"}
ABresult
0X0
100
111
474 2 croak "".(ref $self)." cannot stream a json_object response_format: the "
475 . "Messages endpoint has no native free-form JSON output (only json_schema "
476 . "via output_config.format), and the synthesized-tool fallback has no streaming lift. Use "
477 . "chat_f/chat_request, or pass a json_schema response_format to stream "
478 . "native structured output.";
479 }
480 }
481 elsif ( ref($rf) eq 'HASH' ) {
482 3 ▶ my $type = $rf->{type} // '';
Condition50%1/2
$rf->{"type"} // ""
l!l
30
MC/DC0%0/1
$rf->{"type"} // ""
$rf->{"type"}
Truth table50%1/2
A
A= $rf->{"type"}
Aresult
11
00
483 my $honored = $type eq 'json_object'
484 || ( $type eq 'json_schema'
485 && ref( $rf->{json_schema} ) eq 'HASH'
486 3 ▶ && ref( $rf->{json_schema}{schema} ) eq 'HASH' );
Condition33%3/9
$type eq 'json_object' || $type eq 'json_schema' && ref $rf->{'json_schema'} eq 'HASH' && ref $rf->{'json_schema'}{'schema'} eq 'HASH'
l!l&&r!l&&!r
030
$type eq "json_schema" and ref $rf->{"json_schema"} eq "HASH" and ref $rf->{"json_schema"}{"schema"} eq "HASH"
!ll&&!rl&&r
003
$type eq "json_schema" and ref $rf->{"json_schema"} eq "HASH"
!ll&&!rl&&r
003
MC/DC0%0/4
$type eq 'json_object' || $type eq 'json_schema' && ref $rf->{'json_schema'} eq 'HASH' && ref $rf->{'json_schema'}{'schema'} eq 'HASH'
$type eq 'json_object' $type eq "json_schema" ref $rf->{"json_schema"} eq "HASH" ref $rf->{"json_schema"}{"schema"} eq "HASH"
Truth table20%1/5
A || B and C and D
A= $type eq 'json_object'B= $type eq "json_schema"C= ref $rf->{"json_schema"} eq "HASH"D= ref $rf->{"json_schema"}{"schema"} eq "HASH"
ABCDresult
1XXX1
01111
00XX0
010X0
01100
487 3 ▶ if ($honored) {
Branch: 1 branch
BranchTrueFalseTotal
if ($honored) 3 0 3
488 3 croak "".(ref $self)." cannot stream response_format: this Anthropic-shim engine "
489 . "routes structured output through a synthesized tool whose tool_use input "
490 . "is lifted into Response.content by chat_response, and the streaming path "
491 . "has no Response to lift from. Use chat_f/chat_request for structured output.";
492 }
493 }
494  
495 233 $self->_normalize_tool_params(\%extra, $controls);
496 233 my @msgs;
497 233 my $system = "";
498 233 for my $message (@{$messages}) {
499 233 ▶ if ($message->{role} eq 'system') {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{'role'} eq 'system') { } 0 233 233
500 0 ▶ $system .= "\n\n" if length $system;
Branch: 1 branch
BranchTrueFalseTotal
if length $system 0 0 0
501 0 $system .= $message->{content};
502 } else {
503 233 push @msgs, $message;
504 }
505 }
506 233 ▶ if ($system and scalar @msgs == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($system and scalar @msgs == 0) 0 233 233
Condition33%1/3
$system and scalar @msgs == 0
!ll&&!rl&&r
23300
MC/DC0%0/2
$system and scalar @msgs == 0
$system scalar @msgs == 0
Truth table33%1/3
A and B
A= $systemB= scalar @msgs == 0
ABresult
0X0
100
111
507 0 push @msgs, {
508 role => 'user',
509 content => $system,
510 };
511 0 $system = undef;
512 }
513  
514 233 my %generation = $self->generation_kwargs_for(%$controls);
515 211 $self->_merge_output_config_format( \%generation, $output_config_format );
516  
517 0 ▶ return $self->generate_http_request( POST => $self->url.'/v1/messages', sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
518 model => $self->chat_model,
519 messages => \@msgs,
520 exists $controls->{max_tokens}
521 ? ( max_tokens => $controls->{max_tokens} )
522 211 ▶ : ( max_tokens => $self->get_response_size ), # must be always set
Branch: 3 branches
BranchTrueFalseTotal
exists $controls->{'max_tokens'} ? : 0 211 211
$self->has_inference_geo ? : 0 211 211
$system ? : 0 211 211
523 $self->_temperature_kwargs($controls),
524 %generation,
525 $self->has_inference_geo ? ( inference_geo => $self->inference_geo ) : (),
526 $system ? ( system => $system ) : (),
527 stream => JSON->true,
528 %extra,
529 );
530 }
531  
532  
533 149 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=42 SCAR=38.1
Pod documented
534 149 my ( $self, $data, $event, $state ) = @_;
535  
536 149 require Langertha::Stream::Chunk;
537  
538 # Anthropic uses event types: content_block_delta, message_delta, message_stop
539 149 ▶ my $type = $data->{type} // '';
Condition50%1/2
$data->{"type"} // ""
l!l
1490
MC/DC0%0/1
$data->{"type"} // ""
$data->{"type"}
Truth table50%1/2
A
A= $data->{"type"}
Aresult
11
00
540  
541 # A mid-stream `event: error` ({"type":"error","error":{"type":
542 # "overloaded_error",...}}) is no content: skipping it ended the stream as a
543 # short, silent success. Fail the stream, as the non-streaming chat_response
544 # does for the same envelope (k338) -- karr k378
545 149 ▶ if ( $type eq 'error' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "error") 4 145 149
546 croak "".(ref $self)." stream carried an error: "
547 4 ▶ .( $self->_body_error_text( $data->{error} ) // 'no error message' );
Condition50%1/2
$self->_body_error_text($data->{"error"}) // "no error message"
l!l
40
MC/DC0%0/1
$self->_body_error_text($data->{"error"}) // "no error message"
$self->_body_error_text($data->{"error"})
Truth table50%1/2
A
A= $self->_body_error_text($data->{"error"})
Aresult
11
00
548 }
549  
550 # A streamed tool call is a tool_use content block: content_block_start
551 # names it (id, name, an empty input), input_json_delta events carry its
552 # input as partial_json fragments, content_block_stop closes it. Assemble the
553 # block per content-block index in this stream's state and deliver it on its
554 # content_block_stop, read by the same ToolCall->extract chat_response uses,
555 # so a streamed and a non-streamed reply of one response yield the same call.
556 # The block leaves the state as it is delivered, so it never arrives twice.
557 # -- karr k221
558 145 ▶ $state //= $self->_stream_parse_state;
Condition66%2/3
$state //= $self->_stream_parse_state
l!l&&r!l&&!r
105400
MC/DC0%0/2
$state //= $self->_stream_parse_state
$state $self->_stream_parse_state
Truth table66%2/3
A //= B
A= $stateB= $self->_stream_parse_state
ABresult
1X1
011
000
559 145 ▶ my $blocks = $state->{anthropic_tool_blocks} //= {};
Condition100%2/2
$state->{"anthropic_tool_blocks"} //= {}
l!l
12223
MC/DC100%1/1
$state->{"anthropic_tool_blocks"} //= {}
$state->{"anthropic_tool_blocks"}
Truth table100%2/2
A
A= $state->{"anthropic_tool_blocks"}
Aresult
11
00
560  
561 # Anthropic splits the terminal stream metadata across two SSE events:
562 # message_delta carries finish_reason (stop_reason) + usage but is not the
563 # final event, and message_stop is the final event but carries neither. The
564 # cross-dialect Stream::Chunk contract puts finish_reason + usage on the same
565 # chunk that is is_final -- which the documented
566 # `if ($chunk->is_final) { ...$chunk->finish_reason... }` consumer relies on --
567 # so the message_delta metadata is held in the stream state under
568 # anthropic_final_meta and replayed onto the message_stop chunk (karr k167).
569 # It lives in the per-stream state, not on the engine, so two concurrent
570 # streams on one engine cannot wipe or swap each other's (karr k221 review).
571  
572 # A new message begins the terminal-metadata carry fresh (karr k167): guards
573 # against a prior stream on the same state that aborted before message_stop.
574 # message_start also carries the input side of the usage (input_tokens,
575 # cache_read_input_tokens, cache_creation_input_tokens) and the model;
576 # message_delta's usage documents only output_tokens. Keep both in the
577 # stream state so the final chunk's usage is complete and names the model.
578 # -- karr k298
579 145 ▶ if ($type eq 'message_start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "message_start") 24 121 145
580 24 delete $state->{anthropic_final_meta};
581 24 %$blocks = ();
582 24 ▶ my $message = ref $data->{message} eq 'HASH' ? $data->{message} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{'message'} eq 'HASH' ? : 24 0 24
583 $state->{anthropic_start_usage} =
584 24 ▶ ref $message->{usage} eq 'HASH' ? { %{ $message->{usage} } } : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $message->{'usage'} eq 'HASH' ? : 14 10 24
585 24 ▶ $state->{anthropic_model} = length( $message->{model} // '' ) ? $message->{model} : undef;
Branch: 1 branch
BranchTrueFalseTotal
length($message->{'model'} // '') ? : 14 10 24
Condition100%2/2
$message->{"model"} // ""
l!l
1410
MC/DC100%1/1
$message->{"model"} // ""
$message->{"model"}
Truth table100%2/2
A
A= $message->{"model"}
Aresult
11
00
586 24 return undef;
587 }
588  
589 121 ▶ if ($type eq 'content_block_start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_start") 18 103 121
590 18 my $block = $data->{content_block};
591 18 ▶ if ( ref $block eq 'HASH' && ( $block->{type} // '' ) eq 'tool_use' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $block eq "HASH" and ($block->{"type"} // "") eq "tool_use") 4 14 18
Condition80%4/5
ref $block eq "HASH" and ($block->{"type"} // "") eq "tool_use"
!ll&&!rl&&r
1134
$block->{"type"} // ""
l!l
170
MC/DC50%1/2
ref $block eq "HASH" and ($block->{"type"} // "") eq "tool_use"
ref $block eq "HASH" $block->{"type"}
Truth table66%2/3
A and B
A= ref $block eq "HASH"B= $block->{"type"}
ABresult
0X0
100
111
592 4 ▶ $blocks->{ $data->{index} // 0 } = { block => { %$block }, json => '' };
Condition50%1/2
$data->{"index"} // 0
l!l
40
MC/DC0%0/1
$data->{"index"} // 0
$data->{"index"}
Truth table50%1/2
A
A= $data->{"index"}
Aresult
11
00
593 }
594 18 return undef;
595 }
596  
597 103 ▶ if ($type eq 'content_block_stop') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_stop") 17 86 103
598 17 ▶ my $open = delete $blocks->{ $data->{index} // 0 } or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $open = delete $$blocks{$data->{"index"} // 0} or return undef 4 13 17
Condition50%1/2
$data->{"index"} // 0
l!l
170
MC/DC0%0/1
$data->{"index"} // 0
$data->{"index"}
Truth table50%1/2
A
A= $data->{"index"}
Aresult
11
00
599 4 my $block = $open->{block};
600 4 ▶ $block->{input} = $open->{json} if length $open->{json};
Branch: 1 branch
BranchTrueFalseTotal
if length $open->{"json"} 3 1 4
601 4 my @tool_calls = Langertha::ToolCall->extract( $self->tool_wire_format,
602 { content => [ $block ] } );
603 4 ▶ return undef unless @tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless @tool_calls 0 4 4
604 4 return Langertha::Stream::Chunk->new(
605 content => '',
606 raw => $data,
607 is_final => 0,
608 tool_calls => \@tool_calls,
609 );
610 }
611  
612 86 ▶ if ($type eq 'content_block_delta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_delta") 42 44 86
613 42 ▶ my $delta = $data->{delta} || {};
Condition50%1/2
$data->{'delta'} || {}
l!l
420
MC/DC0%0/1
$data->{'delta'} || {}
$data->{'delta'}
Truth table50%1/2
A
A= $data->{'delta'}
Aresult
11
00
614 42 ▶ if ( ( $delta->{type} // '' ) eq 'input_json_delta'
Branch: 1 branch
BranchTrueFalseTotal
if (($delta->{"type"} // "") eq "input_json_delta" and my $open = $$blocks{$data->{"index"} // 0}) 9 33 42
Condition71%5/7
($delta->{"type"} // "") eq "input_json_delta" and my $open = $$blocks{$data->{"index"} // 0}
!ll&&!rl&&r
3309
$delta->{"type"} // ""
l!l
393
$data->{"index"} // 0
l!l
90
MC/DC50%1/2
($delta->{"type"} // "") eq "input_json_delta" and my $open = $$blocks{$data->{"index"} // 0}
$delta->{"type"} my $open = $$blocks{$data->{"index"} // 0}
MC/DC0%0/1
$data->{"index"} // 0
$data->{"index"}
Truth table66%2/3
A and B
A= $delta->{"type"}B= my $open = $$blocks{$data->{"index"} // 0}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $data->{"index"}
Aresult
11
00
615 && ( my $open = $blocks->{ $data->{index} // 0 } ) ) {
616 9 ▶ $open->{json} .= $delta->{partial_json} // '';
Condition50%1/2
$delta->{"partial_json"} // ""
l!l
90
MC/DC0%0/1
$delta->{"partial_json"} // ""
$delta->{"partial_json"}
Truth table50%1/2
A
A= $delta->{"partial_json"}
Aresult
11
00
617 }
618 # A content_block_delta is discriminated by delta.type: text_delta carries
619 # `text`, thinking_delta carries `thinking` (extended-thinking models), then
620 # exactly one signature_delta precedes content_block_stop. Surface the
621 # streamed thinking onto the chunk; content stays the text delta. -- karr k129
622 42 ▶ my $dtype = $delta->{type} // '';
Condition100%2/2
$delta->{"type"} // ""
l!l
393
MC/DC100%1/1
$delta->{"type"} // ""
$delta->{"type"}
Truth table100%2/2
A
A= $delta->{"type"}
Aresult
11
00
623 return Langertha::Stream::Chunk->new(
624 content => $delta->{text} // '',
625 raw => $data,
626 is_final => 0,
627 ( $dtype eq 'thinking_delta' && defined $delta->{thinking}
628 42 ▶ ? ( thinking => $delta->{thinking} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
$dtype eq 'thinking_delta' && defined $delta->{'thinking'} ? : 5 37 42
Condition80%4/5
$delta->{"text"} // ""
l!l
2418
$dtype eq "thinking_delta" and defined $delta->{"thinking"}
!ll&&!rl&&r
3705
MC/DC100%1/1
$delta->{"text"} // ""
$delta->{"text"}
MC/DC50%1/2
$dtype eq "thinking_delta" and defined $delta->{"thinking"}
$dtype eq "thinking_delta" defined $delta->{"thinking"}
Truth table100%2/2
A
A= $delta->{"text"}
Aresult
11
00
Truth table66%2/3
A and B
A= $dtype eq "thinking_delta"B= defined $delta->{"thinking"}
ABresult
0X0
100
111
629 );
630 }
631  
632 44 ▶ if ($type eq 'message_delta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "message_delta") 19 25 44
633 19 ▶ my $delta = $data->{delta} || {};
Condition50%1/2
$data->{'delta'} || {}
l!l
190
MC/DC0%0/1
$data->{'delta'} || {}
$data->{'delta'}
Truth table50%1/2
A
A= $data->{'delta'}
Aresult
11
00
634 # Remember the terminal metadata (finish_reason + usage) so it can be
635 # replayed onto the is_final message_stop chunk, matching the cross-dialect
636 # contract (see anthropic_final_meta above). It still rides this chunk too.
637 # -- k167
638 # The usage is message_start's merged with this event's, key by key with
639 # this event winning: it carries the final output_tokens, and newer API
640 # versions repeat cumulative input counts here too. -- karr k298
641 19 my $start = $state->{anthropic_start_usage};
642 my $usage = ref $data->{usage} eq 'HASH'
643 19 ▶ ? { ( ref $start eq 'HASH' ? %$start : () ), %{ $data->{usage} } }
Branch: 2 branches
BranchTrueFalseTotal
ref $data->{'usage'} eq 'HASH' ? : 18 1 19
ref $start eq 'HASH' ? : 10 8 18
644 : $start;
645 my %final = (
646 $delta->{stop_reason} ? (finish_reason => $delta->{stop_reason}) : (),
647 $usage ? (usage => $self->_wire_usage($usage)) : (),
648 19 ▶ defined $state->{anthropic_model} ? (model => $state->{anthropic_model}) : (),
Branch: 3 branches
BranchTrueFalseTotal
$delta->{'stop_reason'} ? : 19 0 19
$usage ? : 18 1 19
defined $state->{'anthropic_model'} ? : 10 9 19
649 );
650 19 ▶ $state->{anthropic_final_meta} = %final ? { %final } : undef;
Branch: 1 branch
BranchTrueFalseTotal
%final ? : 19 0 19
651 19 return Langertha::Stream::Chunk->new(
652 content => '',
653 raw => $data,
654 is_final => 0,
655 %final,
656 );
657 }
658  
659 25 ▶ if ($type eq 'message_stop') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "message_stop") 21 4 25
660 # Replay the finish_reason + usage that message_delta carried onto the
661 # is_final chunk, so is_final and the terminal metadata land together as
662 # every other dialect delivers them (karr k167).
663 21 my $final = delete $state->{anthropic_final_meta};
664 21 ▶ return Langertha::Stream::Chunk->new(
Branch: 1 branch
BranchTrueFalseTotal
ref $final eq 'HASH' ? : 19 2 21
665 content => '',
666 raw => $data,
667 is_final => 1,
668 ( ref $final eq 'HASH' ? %$final : () ),
669 );
670 }
671  
672 # Other event types (ping, ...) - skip
673 4 return undef;
674 }
675  
676  
677 # Dynamic model listing with cursor pagination
678 10 ▶sub list_models_request {
Subroutine list_models_request: called CC=2 SCAR=6.9
Pod documented
679 10 my ($self, %params) = @_;
680 10 my $url = $self->url.'/v1/models';
681  
682 # Add pagination params if provided
683 10 ▶ if (%params) {
Branch: 1 branch
BranchTrueFalseTotal
if (%params) 2 8 10
684 2 require URI;
685 2 my $uri = URI->new($url);
686 2 $uri->query_form(%params);
687 2 $url = $uri->as_string;
688 }
689  
690 return $self->generate_http_request(
691 GET => $url,
692 4 ▶ sub { $self->list_models_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
693 10 );
694 }
695  
696  
697 5 ▶sub list_models_response {
Subroutine list_models_response: called CC=1 SCAR=0.0
Pod documented
698 5 my ($self, $response) = @_;
699 5 my $data = $self->parse_response($response);
700 5 return $data;
701 }
702  
703  
704 3 ▶sub _fetch_all_models {
Subroutine _fetch_all_models: called CC=4 SCAR=13.9
705 3 my ($self) = @_;
706 3 my @all_models;
707 my $after_id;
708  
709 3 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$after_id and do { do { my $request = $self->list_models_request($after_id ? ("after_id", $after_id, "limit", 100) : ()); my $response = $self->user_agent->request($request); my $data = $request->response_call->($response); push @all_models, @{$data->{"data"};}; $after_id = $data->{"has_more"} ? $data->{"last_id"} : undef } } 1 3 4
710 4 ▶ my $request = $self->list_models_request(
Branch: 1 branch
BranchTrueFalseTotal
$after_id ? : 1 3 4
711 $after_id ? (after_id => $after_id, limit => 100) : ()
712 );
713 4 my $response = $self->user_agent->request($request);
714 4 my $data = $request->response_call->($response);
715  
716 4 push @all_models, @{$data->{data}};
717 4 ▶ $after_id = $data->{has_more} ? $data->{last_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$data->{'has_more'} ? : 1 3 4
718 } while ($after_id);
719  
720 3 return \@all_models;
721 }
722  
723 3 ▶sub list_models {
Subroutine list_models: called CC=6 SCAR=19.9
Pod documented
724 3 my ($self, %opts) = @_;
725  
726 # Check cache unless force_refresh requested
727 3 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 1 2 3
728 1 my $cache = $self->_models_cache;
729 1 ▶ if ($cache->{timestamp} && time - $cache->{timestamp} < $self->models_cache_ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{"timestamp"} and time - $cache->{"timestamp"} < $self->models_cache_ttl) 0 1 1
Condition33%1/3
$cache->{"timestamp"} and time - $cache->{"timestamp"} < $self->models_cache_ttl
!ll&&!rl&&r
100
MC/DC0%0/2
$cache->{"timestamp"} and time - $cache->{"timestamp"} < $self->models_cache_ttl
$cache->{"timestamp"} time - $cache->{"timestamp"} < $self->models_cache_ttl
Truth table33%1/3
A and B
A= $cache->{"timestamp"}B= time - $cache->{"timestamp"} < $self->models_cache_ttl
ABresult
0X0
100
111
730 0 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
731 }
732 }
733  
734 # Fetch all pages from API
735 3 my $models = $self->_fetch_all_models;
736  
737 # Extract IDs and update cache
738 3 my @model_ids = map { $_->{id} } @$models;
739 3 $self->_models_cache({
740 timestamp => time,
741 models => $models,
742 model_ids => \@model_ids,
743 });
744  
745 3 ▶ return $opts{full} ? $models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 3 3
746 }
747  
748  
749 # Tool calling support (MCP) is the tag-driven default in Langertha::Role::Tools.
750 586 ▶sub _build_tool_wire_format { 'anthropic' }
Subroutine _build_tool_wire_format: called CC=1 SCAR=0.0
751  
752 130 ▶sub _parse_rate_limit_headers {
Subroutine _parse_rate_limit_headers: called CC=12 SCAR=24.8
753 130 my ( $self, $http_response ) = @_;
754 130 require Langertha::RateLimit;
755 130 require Langertha::Moment;
756 130 my %raw = Langertha::RateLimit::_collect_headers($http_response);
757 130 ▶ return undef unless %raw;
Branch: 1 branch
BranchTrueFalseTotal
unless %raw 126 4 130
758 4 my $req_reset = $raw{'anthropic-ratelimit-requests-reset'};
759 4 my $tok_reset = $raw{'anthropic-ratelimit-tokens-reset'};
760 # Anthropic reset headers are RFC 3339 instants — a "when", so they populate
761 # *_reset_at via the lenient inbound door (ADR 0017); the matching
762 # *_reset_after is derived lazily against `received`. from_wire returns undef
763 # for anything it cannot read, and then neither half is set (raw keeps it).
764 4 ▶ my $req_at = defined $req_reset ? Langertha::Moment->from_wire($req_reset) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $req_reset ? : 2 2 4
765 4 ▶ my $tok_at = defined $tok_reset ? Langertha::Moment->from_wire($tok_reset) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $tok_reset ? : 2 2 4
766 return Langertha::RateLimit->new(
767 received => Langertha::Moment->now_utc,
768 ( defined $raw{'anthropic-ratelimit-requests-limit'} ? ( requests_limit => $raw{'anthropic-ratelimit-requests-limit'} + 0 ) : () ),
769 ( defined $raw{'anthropic-ratelimit-requests-remaining'} ? ( requests_remaining => $raw{'anthropic-ratelimit-requests-remaining'} + 0 ) : () ),
770 ( defined $req_reset ? ( requests_reset => $req_reset ) : () ),
771 ( defined $req_at ? ( requests_reset_at => $req_at ) : () ),
772 ( defined $raw{'anthropic-ratelimit-tokens-limit'} ? ( tokens_limit => $raw{'anthropic-ratelimit-tokens-limit'} + 0 ) : () ),
773 4 ▶ ( defined $raw{'anthropic-ratelimit-tokens-remaining'} ? ( tokens_remaining => $raw{'anthropic-ratelimit-tokens-remaining'} + 0 ) : () ),
Branch: 8 branches
BranchTrueFalseTotal
defined $raw{'anthropic-ratelimit-requests-limit'} ? : 2 2 4
defined $raw{'anthropic-ratelimit-requests-remaining'} ? : 3 1 4
defined $req_reset ? : 2 2 4
defined $req_at ? : 2 2 4
defined $raw{'anthropic-ratelimit-tokens-limit'} ? : 2 2 4
defined $raw{'anthropic-ratelimit-tokens-remaining'} ? : 2 2 4
defined $tok_reset ? : 2 2 4
defined $tok_at ? : 2 2 4
774 ( defined $tok_reset ? ( tokens_reset => $tok_reset ) : () ),
775 ( defined $tok_at ? ( tokens_reset_at => $tok_at ) : () ),
776 raw => \%raw,
777 );
778 }
779  
780  
781  
782 68 1;
783  
784 __END__
« blib/lib/Langertha/Role/Langfuse.pm ↑ Summary blib/lib/Langertha/HTTP/Redirect.pm »