blib/lib/Langertha/Role/AnthropicCompatible.pm

filter: Statementstmt 94.8% 274 / 289 Branchbran 85.5% 195 / 228 Conditioncond 64.5% 80 / 124 MC/DCmcdc 31.7% 20 / 63 Subroutinesub 95.1% 39 / 41 Podpod 81.8% 9 / 11 totaltotal 81.6% 617 / 756 CC 170 SCAR 29.5
CC
170
Cov
86%
parse_stream_chunk
42.8
chat_stream_request
34.7
chat_response
21.9
CRAP 19.2
« blib/lib/Langertha/Engine/Ollama.pm ↑ Summary blib/lib/Langertha/Role/ResponsesCompatible.pm »
1 package Langertha::Role::AnthropicCompatible;
2 # ABSTRACT: Role for Anthropic-compatible API format
3 62 our $VERSION = '0.503';
4 62 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 62 ▶use Carp qw( croak carp );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 62 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 62 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 62 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 62 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 62 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12  
13 242 ▶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 187 ▶sub default_response_size { 1024 }
Subroutine default_response_size: called CC=1 SCAR=0.0
Pod undocumented
17  
18 48 ▶sub content_format { 'anthropic' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod undocumented
19  
20 62 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 62 has api_version => (
31 is => 'ro',
32 lazy_build => 1,
33 );
34 432 ▶sub _build_api_version { '2023-06-01' }
Subroutine _build_api_version: called CC=1 SCAR=0.0
35  
36  
37 62 has effort => (
38 is => 'ro',
39 isa => 'Str',
40 predicate => 'has_effort',
41 );
42  
43  
44 62 has inference_geo => (
45 is => 'ro',
46 isa => 'Str',
47 predicate => 'has_inference_geo',
48 );
49  
50  
51 592 ▶sub update_request {
Subroutine update_request: called CC=1 SCAR=0.0
Pod documented
52 592 my ( $self, $request ) = @_;
53 592 $request->header('x-api-key', $self->api_key);
54 592 $request->header('content-type', 'application/json');
55 592 $request->header('anthropic-version', $self->api_version);
56 }
57  
58  
59 388 ▶sub chat_request {
Subroutine chat_request: called CC=13 SCAR=25.8
Pod documented
60 388 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 388 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
249139
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 388 my $rf_routed = 0;
73 388 my $output_config_format;
74 388 ▶ if ( $self->_native_structured_output_for_model ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_native_structured_output_for_model) { } 187 201 388
75 187 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 187 ▶ if ( $self->_rf_is_native_schema($rf) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_rf_is_native_schema($rf)) { } 11 176 187
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 176 ▶ $rf_routed = $self->_response_format_via_tool($rf, \%extra) // 0;
Condition100%2/2
$self->_response_format_via_tool($rf, \%extra) // 0
l!l
4172
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 388 $self->_normalize_tool_params(\%extra, $controls);
97 388 my @msgs;
98 388 my $system = "";
99 388 for my $message (@{$messages}) {
100 421 ▶ if ($message->{role} eq 'system') {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{'role'} eq 'system') { } 9 412 421
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 412 push @msgs, $message;
105 }
106 }
107 388 ▶ if ($system and scalar @msgs == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($system and scalar @msgs == 0) 0 388 388
Condition66%2/3
$system and scalar @msgs == 0
!ll&&!rl&&r
37990
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 388 my %generation = $self->generation_kwargs_for(%$controls);
116 366 $self->_merge_output_config_format( \%generation, $output_config_format );
117  
118 25 ▶ 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 366 ▶ : ( max_tokens => $self->get_response_size ), # must be always set
Branch: 3 branches
BranchTrueFalseTotal
exists $controls->{'max_tokens'} ? : 5 361 366
$self->has_inference_geo ? : 1 365 366
$system ? : 9 357 366
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 414 ▶sub _native_structured_output_for_model {
Subroutine _native_structured_output_for_model: called CC=1 SCAR=0.0
145 414 my ( $self ) = @_;
146 414 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 626 ▶sub _take_response_format {
Subroutine _take_response_format: called CC=4 SCAR=13.9
155 626 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 626 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $controls->{'response_format'} ? : 2 624 626
exists $extra->{'response_format'} ? : 13 611 624
$self->has_response_format ? : 11 600 611
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 279 ▶sub _rf_is_native_schema {
Subroutine _rf_is_native_schema: called CC=6 SCAR=18.4
168 279 my ( $self, $rf ) = @_;
169 279 ▶ return 0 unless ref($rf) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rf eq "HASH" 244 35 279
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 577 ▶sub _merge_output_config_format {
Subroutine _merge_output_config_format: called CC=3 SCAR=11.0
241 577 my ( $self, $generation, $format ) = @_;
242 577 ▶ return unless $format;
Branch: 1 branch
BranchTrueFalseTotal
unless $format 563 14 577
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 577 ▶sub _temperature_kwargs {
Subroutine _temperature_kwargs: called CC=11 SCAR=24.1
262 577 my ( $self, $controls ) = @_;
263 my $temp = exists $controls->{temperature} ? $controls->{temperature}
264 577 ▶ : $self->has_temperature ? $self->temperature
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'temperature'} ? : 15 562 577
$self->has_temperature ? : 43 519 562
265 : undef;
266 577 ▶ return () unless defined $temp;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $temp 519 58 577
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 62 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 377 ▶sub _response_format_via_tool {
Subroutine _response_format_via_tool: called CC=11 SCAR=25.1
308 377 my ( $self, $rf, $extra ) = @_;
309 377 ▶ return unless ref($rf) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rf eq "HASH" 371 6 377
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 621 ▶sub _normalize_tool_params {
Subroutine _normalize_tool_params: called CC=12 SCAR=25.0
348 621 my ( $self, $extra, $controls ) = @_;
349  
350 621 ▶ if ( exists $extra->{tool_choice} && defined $extra->{tool_choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $extra->{"tool_choice"} and defined $extra->{"tool_choice"}) 16 605 621
Condition66%2/3
exists $extra->{"tool_choice"} and defined $extra->{"tool_choice"}
!ll&&!rl&&r
605016
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 621 ▶ return unless exists $extra->{tools};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $extra->{"tools"} 550 71 621
357  
358 71 my $ptu;
359 71 ▶ if ( exists $controls->{parallel_tool_use} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $controls->{'parallel_tool_use'}) { } 10 61 71
elsif ($self->can('has_parallel_tool_use') and $self->has_parallel_tool_use) { } 2 59 61
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
0592
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 71 ▶ return unless defined $ptu;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ptu 59 12 71
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 93 ▶sub chat_response {
Subroutine chat_response: called CC=21 SCAR=30.8
Pod documented
377 93 my ( $self, $response, $rf_routed ) = @_;
378 93 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 90 ▶ 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 79 90
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
07911
($data->{"type"} // "") eq "error" or defined $data->{"error"} and not ref $data->{"content"} eq "ARRAY" && @{$data->{"content"};}
l!l&&r!l&&!r
10179
$data->{"type"} // ""
l!l
7416
defined $data->{"error"} and not ref $data->{"content"} eq "ARRAY" && @{$data->{"content"};}
!ll&&!rl&&r
7901
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 79 ▶ my @blocks = @{ $data->{content} // [] };
Condition100%2/2
$data->{"content"} // []
l!l
781
MC/DC100%1/1
$data->{"content"} // []
$data->{"content"}
Truth table100%2/2
A
A= $data->{"content"}
Aresult
11
00
395 79 ▶ my $text = join('', map { $_->{text} // '' } grep { $_->{type} eq 'text' } @blocks);
Condition50%1/2
$_->{"text"} // ""
l!l
620
MC/DC0%0/1
$_->{"text"} // ""
$_->{"text"}
Truth table50%1/2
A
A= $_->{"text"}
Aresult
11
00
396 79 ▶ 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 79 ▶ my $thinking = @thinking ? join("\n", @thinking) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@thinking ? : 8 71 79
398 79 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 79 ▶ $rf_routed = $self->has_response_format unless defined $rf_routed;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rf_routed 55 24 79
407 79 ▶ if ( $rf_routed && @tcs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rf_routed and @tcs) 1 78 79
Condition66%2/3
$rf_routed and @tcs
!ll&&!rl&&r
7801
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 79 ▶ $data->{usage} ? ( usage => $self->_wire_usage( $data->{usage} ) ) : (),
Branch: 6 branches
BranchTrueFalseTotal
$data->{'id'} ? : 74 5 79
$data->{'model'} ? : 56 23 79
defined $data->{'stop_reason'} ? : 73 6 79
$data->{'usage'} ? : 20 59 79
defined $thinking ? : 8 71 79
@tcs ? : 20 59 79
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 26 ▶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 38 ▶sub _wire_usage {
Subroutine _wire_usage: called CC=4 SCAR=14.1
436 38 my ( $self, $usage ) = @_;
437 38 ▶ return $usage unless ref $usage eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 0 38 38
438 38 my $includes = $self->_usage_input_includes_cache;
439 38 ▶ return $usage unless defined $includes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $includes 26 12 38
440 12 ▶ return { %$usage, input_includes_cache => $includes ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$includes ? : 12 0 12
441 }
442  
443  
444 13 ▶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 137 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=40 SCAR=37.6
Pod documented
534 137 my ( $self, $data, $event, $state ) = @_;
535  
536 137 require Langertha::Stream::Chunk;
537  
538 # Anthropic uses event types: content_block_delta, message_delta, message_stop
539 137 ▶ my $type = $data->{type} // '';
Condition50%1/2
$data->{"type"} // ""
l!l
1370
MC/DC0%0/1
$data->{"type"} // ""
$data->{"type"}
Truth table50%1/2
A
A= $data->{"type"}
Aresult
11
00
540  
541 # A streamed tool call is a tool_use content block: content_block_start
542 # names it (id, name, an empty input), input_json_delta events carry its
543 # input as partial_json fragments, content_block_stop closes it. Assemble the
544 # block per content-block index in this stream's state and deliver it on its
545 # content_block_stop, read by the same ToolCall->extract chat_response uses,
546 # so a streamed and a non-streamed reply of one response yield the same call.
547 # The block leaves the state as it is delivered, so it never arrives twice.
548 # -- karr k221
549 137 ▶ $state //= $self->_stream_parse_state;
Condition66%2/3
$state //= $self->_stream_parse_state
l!l&&r!l&&!r
97400
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
550 137 ▶ my $blocks = $state->{anthropic_tool_blocks} //= {};
Condition100%2/2
$state->{"anthropic_tool_blocks"} //= {}
l!l
11819
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
551  
552 # Anthropic splits the terminal stream metadata across two SSE events:
553 # message_delta carries finish_reason (stop_reason) + usage but is not the
554 # final event, and message_stop is the final event but carries neither. The
555 # cross-dialect Stream::Chunk contract puts finish_reason + usage on the same
556 # chunk that is is_final -- which the documented
557 # `if ($chunk->is_final) { ...$chunk->finish_reason... }` consumer relies on --
558 # so the message_delta metadata is held in the stream state under
559 # anthropic_final_meta and replayed onto the message_stop chunk (karr k167).
560 # It lives in the per-stream state, not on the engine, so two concurrent
561 # streams on one engine cannot wipe or swap each other's (karr k221 review).
562  
563 # A new message begins the terminal-metadata carry fresh (karr k167): guards
564 # against a prior stream on the same state that aborted before message_stop.
565 # message_start also carries the input side of the usage (input_tokens,
566 # cache_read_input_tokens, cache_creation_input_tokens) and the model;
567 # message_delta's usage documents only output_tokens. Keep both in the
568 # stream state so the final chunk's usage is complete and names the model.
569 # -- karr k298
570 137 ▶ if ($type eq 'message_start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "message_start") 20 117 137
571 20 delete $state->{anthropic_final_meta};
572 20 %$blocks = ();
573 20 ▶ my $message = ref $data->{message} eq 'HASH' ? $data->{message} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{'message'} eq 'HASH' ? : 20 0 20
574 $state->{anthropic_start_usage} =
575 20 ▶ ref $message->{usage} eq 'HASH' ? { %{ $message->{usage} } } : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $message->{'usage'} eq 'HASH' ? : 10 10 20
576 20 ▶ $state->{anthropic_model} = length( $message->{model} // '' ) ? $message->{model} : undef;
Branch: 1 branch
BranchTrueFalseTotal
length($message->{'model'} // '') ? : 10 10 20
Condition100%2/2
$message->{"model"} // ""
l!l
1010
MC/DC100%1/1
$message->{"model"} // ""
$message->{"model"}
Truth table100%2/2
A
A= $message->{"model"}
Aresult
11
00
577 20 return undef;
578 }
579  
580 117 ▶ if ($type eq 'content_block_start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_start") 18 99 117
581 18 my $block = $data->{content_block};
582 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
583 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
584 }
585 18 return undef;
586 }
587  
588 99 ▶ if ($type eq 'content_block_stop') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_stop") 17 82 99
589 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
590 4 my $block = $open->{block};
591 4 ▶ $block->{input} = $open->{json} if length $open->{json};
Branch: 1 branch
BranchTrueFalseTotal
if length $open->{"json"} 3 1 4
592 4 my @tool_calls = Langertha::ToolCall->extract( $self->tool_wire_format,
593 { content => [ $block ] } );
594 4 ▶ return undef unless @tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless @tool_calls 0 4 4
595 4 return Langertha::Stream::Chunk->new(
596 content => '',
597 raw => $data,
598 is_final => 0,
599 tool_calls => \@tool_calls,
600 );
601 }
602  
603 82 ▶ if ($type eq 'content_block_delta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_delta") 38 44 82
604 38 ▶ my $delta = $data->{delta} || {};
Condition50%1/2
$data->{'delta'} || {}
l!l
380
MC/DC0%0/1
$data->{'delta'} || {}
$data->{'delta'}
Truth table50%1/2
A
A= $data->{'delta'}
Aresult
11
00
605 38 ▶ 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 29 38
Condition71%5/7
($delta->{"type"} // "") eq "input_json_delta" and my $open = $$blocks{$data->{"index"} // 0}
!ll&&!rl&&r
2909
$delta->{"type"} // ""
l!l
353
$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
606 && ( my $open = $blocks->{ $data->{index} // 0 } ) ) {
607 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
608 }
609 # A content_block_delta is discriminated by delta.type: text_delta carries
610 # `text`, thinking_delta carries `thinking` (extended-thinking models), then
611 # exactly one signature_delta precedes content_block_stop. Surface the
612 # streamed thinking onto the chunk; content stays the text delta. -- karr k129
613 38 ▶ my $dtype = $delta->{type} // '';
Condition100%2/2
$delta->{"type"} // ""
l!l
353
MC/DC100%1/1
$delta->{"type"} // ""
$delta->{"type"}
Truth table100%2/2
A
A= $delta->{"type"}
Aresult
11
00
614 return Langertha::Stream::Chunk->new(
615 content => $delta->{text} // '',
616 raw => $data,
617 is_final => 0,
618 ( $dtype eq 'thinking_delta' && defined $delta->{thinking}
619 38 ▶ ? ( thinking => $delta->{thinking} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
$dtype eq 'thinking_delta' && defined $delta->{'thinking'} ? : 5 33 38
Condition80%4/5
$delta->{"text"} // ""
l!l
2018
$dtype eq "thinking_delta" and defined $delta->{"thinking"}
!ll&&!rl&&r
3305
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
620 );
621 }
622  
623 44 ▶ if ($type eq 'message_delta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "message_delta") 19 25 44
624 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
625 # Remember the terminal metadata (finish_reason + usage) so it can be
626 # replayed onto the is_final message_stop chunk, matching the cross-dialect
627 # contract (see anthropic_final_meta above). It still rides this chunk too.
628 # -- k167
629 # The usage is message_start's merged with this event's, key by key with
630 # this event winning: it carries the final output_tokens, and newer API
631 # versions repeat cumulative input counts here too. -- karr k298
632 19 my $start = $state->{anthropic_start_usage};
633 my $usage = ref $data->{usage} eq 'HASH'
634 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
635 : $start;
636 my %final = (
637 $delta->{stop_reason} ? (finish_reason => $delta->{stop_reason}) : (),
638 $usage ? (usage => $self->_wire_usage($usage)) : (),
639 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
640 );
641 19 ▶ $state->{anthropic_final_meta} = %final ? { %final } : undef;
Branch: 1 branch
BranchTrueFalseTotal
%final ? : 19 0 19
642 19 return Langertha::Stream::Chunk->new(
643 content => '',
644 raw => $data,
645 is_final => 0,
646 %final,
647 );
648 }
649  
650 25 ▶ if ($type eq 'message_stop') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "message_stop") 21 4 25
651 # Replay the finish_reason + usage that message_delta carried onto the
652 # is_final chunk, so is_final and the terminal metadata land together as
653 # every other dialect delivers them (karr k167).
654 21 my $final = delete $state->{anthropic_final_meta};
655 21 ▶ return Langertha::Stream::Chunk->new(
Branch: 1 branch
BranchTrueFalseTotal
ref $final eq 'HASH' ? : 19 2 21
656 content => '',
657 raw => $data,
658 is_final => 1,
659 ( ref $final eq 'HASH' ? %$final : () ),
660 );
661 }
662  
663 # Other event types (ping, ...) - skip
664 4 return undef;
665 }
666  
667  
668 # Dynamic model listing with cursor pagination
669 10 ▶sub list_models_request {
Subroutine list_models_request: called CC=2 SCAR=6.9
Pod documented
670 10 my ($self, %params) = @_;
671 10 my $url = $self->url.'/v1/models';
672  
673 # Add pagination params if provided
674 10 ▶ if (%params) {
Branch: 1 branch
BranchTrueFalseTotal
if (%params) 2 8 10
675 2 require URI;
676 2 my $uri = URI->new($url);
677 2 $uri->query_form(%params);
678 2 $url = $uri->as_string;
679 }
680  
681 return $self->generate_http_request(
682 GET => $url,
683 4 ▶ sub { $self->list_models_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
684 10 );
685 }
686  
687  
688 5 ▶sub list_models_response {
Subroutine list_models_response: called CC=1 SCAR=0.0
Pod documented
689 5 my ($self, $response) = @_;
690 5 my $data = $self->parse_response($response);
691 5 return $data;
692 }
693  
694  
695 3 ▶sub _fetch_all_models {
Subroutine _fetch_all_models: called CC=4 SCAR=13.9
696 3 my ($self) = @_;
697 3 my @all_models;
698 my $after_id;
699  
700 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
701 4 ▶ my $request = $self->list_models_request(
Branch: 1 branch
BranchTrueFalseTotal
$after_id ? : 1 3 4
702 $after_id ? (after_id => $after_id, limit => 100) : ()
703 );
704 4 my $response = $self->user_agent->request($request);
705 4 my $data = $request->response_call->($response);
706  
707 4 push @all_models, @{$data->{data}};
708 4 ▶ $after_id = $data->{has_more} ? $data->{last_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$data->{'has_more'} ? : 1 3 4
709 } while ($after_id);
710  
711 3 return \@all_models;
712 }
713  
714 3 ▶sub list_models {
Subroutine list_models: called CC=6 SCAR=19.9
Pod documented
715 3 my ($self, %opts) = @_;
716  
717 # Check cache unless force_refresh requested
718 3 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 1 2 3
719 1 my $cache = $self->_models_cache;
720 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
721 0 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
722 }
723 }
724  
725 # Fetch all pages from API
726 3 my $models = $self->_fetch_all_models;
727  
728 # Extract IDs and update cache
729 3 my @model_ids = map { $_->{id} } @$models;
730 3 $self->_models_cache({
731 timestamp => time,
732 models => $models,
733 model_ids => \@model_ids,
734 });
735  
736 3 ▶ return $opts{full} ? $models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 3 3
737 }
738  
739  
740 # Tool calling support (MCP) is the tag-driven default in Langertha::Role::Tools.
741 112 ▶sub _build_tool_wire_format { 'anthropic' }
Subroutine _build_tool_wire_format: called CC=1 SCAR=0.0
742  
743 125 ▶sub _parse_rate_limit_headers {
Subroutine _parse_rate_limit_headers: called CC=12 SCAR=24.8
744 125 my ( $self, $http_response ) = @_;
745 125 require Langertha::RateLimit;
746 125 require Langertha::Moment;
747 125 my %raw = Langertha::RateLimit::_collect_headers($http_response);
748 125 ▶ return undef unless %raw;
Branch: 1 branch
BranchTrueFalseTotal
unless %raw 121 4 125
749 4 my $req_reset = $raw{'anthropic-ratelimit-requests-reset'};
750 4 my $tok_reset = $raw{'anthropic-ratelimit-tokens-reset'};
751 # Anthropic reset headers are RFC 3339 instants — a "when", so they populate
752 # *_reset_at via the lenient inbound door (ADR 0017); the matching
753 # *_reset_after is derived lazily against `received`. from_wire returns undef
754 # for anything it cannot read, and then neither half is set (raw keeps it).
755 4 ▶ my $req_at = defined $req_reset ? Langertha::Moment->from_wire($req_reset) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $req_reset ? : 2 2 4
756 4 ▶ my $tok_at = defined $tok_reset ? Langertha::Moment->from_wire($tok_reset) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $tok_reset ? : 2 2 4
757 return Langertha::RateLimit->new(
758 received => Langertha::Moment->now_utc,
759 ( defined $raw{'anthropic-ratelimit-requests-limit'} ? ( requests_limit => $raw{'anthropic-ratelimit-requests-limit'} + 0 ) : () ),
760 ( defined $raw{'anthropic-ratelimit-requests-remaining'} ? ( requests_remaining => $raw{'anthropic-ratelimit-requests-remaining'} + 0 ) : () ),
761 ( defined $req_reset ? ( requests_reset => $req_reset ) : () ),
762 ( defined $req_at ? ( requests_reset_at => $req_at ) : () ),
763 ( defined $raw{'anthropic-ratelimit-tokens-limit'} ? ( tokens_limit => $raw{'anthropic-ratelimit-tokens-limit'} + 0 ) : () ),
764 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
765 ( defined $tok_reset ? ( tokens_reset => $tok_reset ) : () ),
766 ( defined $tok_at ? ( tokens_reset_at => $tok_at ) : () ),
767 raw => \%raw,
768 );
769 }
770  
771  
772  
773 62 1;
774  
775 __END__
776  
777 =pod
778  
779 =encoding UTF-8
780  
781 =head1 NAME
782  
783 Langertha::Role::AnthropicCompatible - Role for Anthropic-compatible API format
784  
785 =head1 VERSION
786  
787 version 0.503
788  
789 =head1 SYNOPSIS
790  
791 # This role is not used directly - it's composed by engines
792 # that implement the Anthropic-compatible /v1/messages API format.
793  
794 package My::Engine;
795 use Moose;
796  
797 extends 'Langertha::Engine::AnthropicBase';
798  
799 sub _build_api_key { $ENV{MY_API_KEY} || die "needs api_key" }
800 sub default_model { 'my-model' }
801  
802 __PACKAGE__->meta->make_immutable;
803  
804 =head1 DESCRIPTION
805  
806 This role provides the Anthropic C</v1/messages> wire-envelope methods for
807 chat, streaming, tool calling, structured-output emulation, model listing,
808 and rate-limit parsing. Engines that speak the Anthropic-compatible API format
809 (Anthropic itself, MiniMax's legacy shim, Moonshot Kimi, LM Studio's
810 Anthropic-compatible endpoint) compose this role via
811 L<Langertha::Engine::AnthropicBase>, which supplies the C<url> / HTTP / JSON
812 infrastructure from L<Langertha::Engine::Remote>.
813  
814 As with L<Langertha::Role::OpenAICompatible>, this role is only
815 self-contained in isolation: it assumes the composer brings the
816 L<Langertha::Engine::Remote> infrastructure (C<url>, C<generate_http_request>,
817 C<parse_response>, C<json>, C<user_agent>, C<chat_model>,
818 C<get_response_size>, C<has_temperature>, C<reasoning_kwargs_for>,
819 C<prompt_cache_kwargs_for>, C<tool_wire_format>, C<has_parallel_tool_use> /
820 C<parallel_tool_use>, C<has_response_format> / C<response_format>) — normally
821 provided by extending L<Langertha::Engine::Remote> plus the universal roles
822 composed in L<Langertha::Engine::AnthropicBase>.
823  
824 The wire envelope mirrors L<Langertha::Role::OpenAICompatible>: this role owns
825 the Anthropic request/response/stream/auth/rate-limit envelope, and the base
826 class stays a thin composition shell.
827  
828 =head2 api_key
829  
830 Anthropic-compatible API key sent as C<x-api-key>. Subclasses typically
831 override C<_build_api_key> to read a provider-specific environment variable.
832  
833 =head2 api_version
834  
835 The Anthropic API version header sent with every request. Defaults to
836 C<2023-06-01>.
837  
838 =head2 effort
839  
840 Back-compat alias of L<Langertha::Role::ReasoningEffort/reasoning_effort>.
841 Controls the depth of thinking for reasoning models. When set (and
842 C<reasoning_effort> is not), it seeds C<reasoning_effort>, which is serialized
843 via L<Langertha::Reasoning> to C<output_config.effort> plus
844 C<thinking: { type =E<gt> 'adaptive' }> (the current Messages-API shape) rather
845 than the legacy top-level C<effort> key.
846  
847 my $claude = Langertha::Engine::Anthropic->new(
848 api_key => $ENV{ANTHROPIC_API_KEY},
849 model => 'claude-opus-4-8',
850 effort => 'high', # same as reasoning_effort => 'high'
851 );
852  
853 =head2 inference_geo
854  
855 Controls data residency for inference on the first-party Claude API. The API
856 accepts exactly two values: C<global> (the default) and C<us>. There is B<no>
857 EU inference-geo on the first-party API; a value such as C<eu> is not part of
858 the enum and is rejected. It is only honoured on Claude 4.6+ models; older
859 models return a 400 regardless of the value.
860  
861 my $claude = Langertha::Engine::Anthropic->new(
862 api_key => $ENV{ANTHROPIC_API_KEY},
863 inference_geo => 'us',
864 );
865  
866 The response reports where the request actually ran via
867 C<usage.inference_geo>, and C<us> residency is billed at 1.1x the base rate.
868  
869 EU data residency is not available this way. For EU-hosted inference use one of
870 the EU engines Langertha already ships — L<Langertha::Engine::AKI>,
871 L<Langertha::Engine::Mistral>, L<Langertha::Engine::Scaleway>,
872 L<Langertha::Engine::TSystems> or L<Langertha::Engine::Hetzner> — or reach
873 Claude through the regional endpoints of Amazon Bedrock or Google Vertex AI,
874 where C<inference_geo> does not apply.
875  
876 =head2 update_request
877  
878 $self->update_request($http_request);
879  
880 Adds the C<x-api-key>, C<content-type: application/json>, and
881 C<anthropic-version> headers to outgoing requests.
882  
883 =head2 chat_request
884  
885 my $request = $engine->chat_request($messages, %extra);
886  
887 Generates an Anthropic-format message request (C<POST /v1/messages>).
888 Includes model, messages, max_tokens, temperature, reasoning-effort and
889 prompt-cache controls, and optional C<system>. Returns an HTTP request
890 object.
891  
892 =head2 _native_structured_output
893  
894 Internal predicate. True when the engine's wire supports native structured
895 output via C<output_config.format> (the first-party Claude Messages API); false
896 (the default) for the legacy C</anthropic> shim engines, which fall back to the
897 ADR 0005 synthesized-tool rewrite. L<Langertha::Engine::Anthropic> overrides it
898 to a true value. It describes the B<endpoint> and so decides the manifest
899 dialect (C<anthropic> vs C<anthropic-compat>, L<Langertha::Manifest::Builder>);
900 the request builders ask L</_native_structured_output_for_model> instead.
901  
902 =head2 _native_structured_output_for_model
903  
904 Internal predicate the request builders use to pick the structured-output path
905 for the current C<chat_model>: native C<output_config.format> when true, the
906 ADR 0005 synthesized-tool rewrite when false. Defaults to
907 L</_native_structured_output>; L<Langertha::Engine::MoonshotAnthropic>
908 overrides it to be true on C<kimi-k3> only.
909  
910 =head2 _translate_response_format
911  
912 Internal: turns a C<response_format> hash into a synthesized tool plus a
913 C<tool_choice>, returning the synthetic tool name. Returns C<undef> when no
914 usable structure is present. Used by the legacy C</anthropic> shim engines and,
915 for a bare C<json_object>, by first-party L<Langertha::Engine::Anthropic> (which
916 routes a C<json_schema> natively via C<output_config.format> instead). The
917 synthesized tool is forced via a named C<tool_choice> where the model supports
918 forced tool use, and degraded to C<tool_choice> C<auto> where it does not
919 (C<claude-fable-5-1> / C<claude-mythos-5-1>).
920  
921 =head2 _normalize_tool_params
922  
923 Internal: normalizes C<tool_choice> to Anthropic's native format and folds
924 C<parallel_tool_use> into the C<tool_choice> block as C<disable_parallel_tool_use>.
925  
926 =head2 chat_response
927  
928 my $response = $role->chat_response($http_response, $rf_routed);
929  
930 Parses an Anthropic-format message response into a L<Langertha::Response>
931 object. When C<$rf_routed> (a synthetic tool name, or truthy for the
932 attribute path) and tool calls are present, lifts the first tool_use
933 arguments back into C<content> as JSON.
934  
935 A 200 body that is an error envelope (C<{"type":"error","error":{...}}>), or
936 carries an C<error> object and no content, croaks with
937 C<< <engine class> response carried an error: MESSAGE >>, as the
938 OpenAI-compatible parser does.
939  
940 =head2 _usage_input_includes_cache
941  
942 Internal hook. Returns whether this endpoint counts the prompt-cache reads and
943 writes it reports (C<cache_read_input_tokens> / C<cache_creation_input_tokens>)
944 inside C<usage.input_tokens>. The default returns C<undef>, which keeps the
945 inference of L<Langertha::Usage/from_hash>: the flat Anthropic keys are counted
946 beside C<input_tokens>, as first-party Anthropic reports them. An
947 Anthropic-compatible shim that counts them inside overrides it with
948 C<sub _usage_input_includes_cache { 1 }>, as L<Langertha::Engine::AKIAnthropic>
949 does. The answer reaches L<Langertha::Usage/input_includes_cache> on both the
950 L</chat_response> path and the streamed final chunk, as an
951 C<input_includes_cache> key in a copy of the usage block.
952  
953 =head2 stream_format
954  
955 my $format = $engine->stream_format;
956  
957 Returns C<'sse'> (Server-Sent Events), the streaming format used by
958 Anthropic-compatible APIs.
959  
960 =head2 chat_stream_request
961  
962 my $request = $engine->chat_stream_request($messages, %extra);
963  
964 Generates an Anthropic-format streaming request (SSE, C<stream =E<gt> true>).
965 Returns an HTTP request object for use with streaming execution.
966  
967 =head2 parse_stream_chunk
968  
969 my $chunk = $engine->parse_stream_chunk($data, $event, \%state);
970  
971 Parses a single SSE data payload from an Anthropic-format stream by event
972 type. A C<content_block_delta> of type C<thinking_delta> surfaces its
973 C<thinking> text onto the chunk's C<thinking> attribute. Anthropic splits the
974 terminal metadata across two events — C<message_delta> carries C<finish_reason>
975 (C<stop_reason>) and C<usage> while C<message_stop> is the C<is_final> event — so
976 the C<message_delta> metadata is held in C<\%state> and replayed onto the
977 C<is_final> C<message_stop> chunk, matching the cross-dialect contract where C<finish_reason> and C<usage>
978 land on the same chunk that is C<is_final>. That C<usage> is complete: the
979 input side C<message_start> reports (C<input_tokens>,
980 C<cache_read_input_tokens>, C<cache_creation_input_tokens>) merged with the
981 C<message_delta> usage, whose keys win; both chunks also carry the C<model>
982 from C<message_start>. Returns a
983 L<Langertha::Stream::Chunk>, or C<undef> for event types that carry no content.
984  
985 A C<tool_use> content block is assembled from its C<content_block_start> and
986 C<input_json_delta> fragments in C<\%state> (one HashRef per stream, reset on
987 C<message_start>; the stream paths pass it, a direct caller may omit it and
988 share the engine's fallback; C<$event> is set only on the
989 L<Langertha::Role::Streaming/process_stream_data> path) and
990 lands as a L<Langertha::ToolCall> on the chunk for its C<content_block_stop>,
991 read by the same L<Langertha::ToolCall/extract> as L</chat_response>. Collect
992 the calls with L<Langertha::Role::Chat/aggregate_tool_calls>. The
993 C<content_block_stop> of any other block still returns C<undef>.
994  
995 =head2 list_models_request
996  
997 my $request = $engine->list_models_request;
998 my $request = $engine->list_models_request(after_id => $last_id);
999  
1000 Generates an HTTP GET request for the Anthropic C</v1/models> endpoint,
1001 optionally with pagination params. Returns an HTTP request object.
1002  
1003 =head2 list_models_response
1004  
1005 my $data = $engine->list_models_response($http_response);
1006  
1007 Parses the Anthropic C</v1/models> response. Returns the full response
1008 hashref.
1009  
1010 =head2 list_models
1011  
1012 my $model_ids = $engine->list_models;
1013 my $models = $engine->list_models(full => 1);
1014 my $models = $engine->list_models(force_refresh => 1);
1015  
1016 Fetches available models from the Anthropic API using cursor pagination.
1017 Returns an ArrayRef of model ID strings by default, or full model objects
1018 when C<full => 1> is passed. Results are cached for C<models_cache_ttl>
1019 seconds (default: 3600). Pass C<force_refresh => 1> to bypass the cache.
1020  
1021 =head2 _parse_rate_limit_headers
1022  
1023 Parses C<anthropic-ratelimit-*> headers from the HTTP response into a
1024 L<Langertha::RateLimit> object. Collects the full C<raw> superset via
1025 L<Langertha::RateLimit/_collect_headers> — capturing extras like
1026 C<input-tokens-limit>, C<output-tokens-limit> and the C<anthropic-priority-*>
1027 / C<anthropic-fast-*> families — then normalizes the RFC 3339 reset instants
1028 into L<Langertha::RateLimit/requests_reset_at> / L<Langertha::RateLimit/tokens_reset_at>;
1029 the C<*_reset_after> durations are derived lazily against
1030 L<Langertha::RateLimit/received>.
1031  
1032 =head1 SEE ALSO
1033  
1034 =over
1035  
1036 =item * L<Langertha::Engine::AnthropicBase> - Composes this role as a thin shell
1037  
1038 =item * L<Langertha::Role::OpenAICompatible> - The parallel OpenAI wire-envelope role
1039  
1040 =item * L<https://status.anthropic.com/> - Anthropic service status
1041  
1042 =item * L<https://docs.anthropic.com/> - Official Anthropic documentation
1043  
1044 =item * L<Langertha::Role::Chat> - Chat interface methods
1045  
1046 =item * L<Langertha::Role::Tools> - MCP tool calling interface
1047  
1048 =item * L<Langertha::Role::Streaming> - Streaming support (SSE format)
1049  
1050 =item * L<Langertha::Engine::Gemini> - Another non-OpenAI-compatible engine
1051  
1052 =back
1053  
1054 =head1 SUPPORT
1055  
1056 =head2 Issues
1057  
1058 Please report bugs and feature requests on GitHub at
1059 L<https://github.com/Getty/langertha/issues>.
1060  
1061 =head2 IRC
1062  
1063 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
1064  
1065 =head1 CONTRIBUTING
1066  
1067 Contributions are welcome! Please fork the repository and submit a pull request.
1068  
1069 =head1 AUTHOR
1070  
1071 Torsten Raudssus <getty@cpan.org>
1072  
1073 =head1 COPYRIGHT AND LICENSE
1074  
1075 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
1076  
1077 This is free software; you can redistribute it and/or modify it under
1078 the same terms as the Perl 5 programming language system itself.
1079  
1080 =cut
« blib/lib/Langertha/Engine/Ollama.pm ↑ Summary blib/lib/Langertha/Role/ResponsesCompatible.pm »