blib/lib/Langertha/Role/OpenAICompatible.pm

filter: Statementstmt 97.3% 292 / 300 Branchbran 87.5% 247 / 282 Conditioncond 78.3% 166 / 212 MC/DCmcdc 59.2% 67 / 113 Subroutinesub 94.7% 54 / 57 Podpod 74.0% 20 / 27 totaltotal 85.3% 846 / 991 CC 449 SCAR 31.5
CC
449
Cov
89%
parse_stream_chunk
65.1
parse_stream_chunk
65.1
chat_response
26.2
CRAP 23.4
« blib/lib/Langertha/ServerToolCall.pm ↑ Summary blib/lib/Langertha/Role/Langfuse.pm »
1 package Langertha::Role::OpenAICompatible;
2 # ABSTRACT: Role for OpenAI-compatible API format
3 168 our $VERSION = '0.505';
4 168 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 168 ▶use File::ShareDir::ProjectDistDir qw( :all );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 168 ▶use Carp qw( croak carp );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 168 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 168 ▶use MIME::Base64 qw( decode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 168 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 168 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 168 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 168 has api_key => (
15 is => 'ro',
16 lazy_build => 1,
17 );
18 41 ▶sub _build_api_key { undef }
Subroutine _build_api_key: called CC=1 SCAR=0.0
19  
20  
21 2396 ▶sub update_request {
Subroutine update_request: called CC=2 SCAR=9.2
Pod documented
22 0 ▶ my ( $self, $request ) = @_;
Subroutine update_request: not called CC=2 SCAR=9.2
Pod documented
23 0 my $key = $self->api_key;
24 0 ▶ $request->header('Authorization', 'Bearer '.$key) if defined $key;
Branch: 2 branches
BranchTrueFalseTotal
if defined $key 2114 282 2396
if defined $key 0 0 0
25 }
26  
27  
28 0 ▶sub openapi_file { yaml => dist_file('Langertha','openai.yaml') };
Subroutine openapi_file: not called CC=1 SCAR=6.9
Pod documented
29  
30  
31 31 ▶sub default_embedding_model { 'text-embedding-3-large' }
Subroutine default_embedding_model: called CC=1 SCAR=0.0
Pod undocumented
32 # gpt-image-1 is removed by OpenAI on 2026-10-23 (gpt-image-1-mini, -1.5 and
33 # chatgpt-image-latest on 2026-12-01); gpt-image-2 is the default (k308, k313).
34 # whisper-1 is the transcription alias OpenAI-compatible servers accept;
35 # Engine::OpenAI overrides it with the OpenAI-only gpt-transcribe (k313).
36 2 ▶sub default_transcription_model { 'whisper-1' }
Subroutine default_transcription_model: called CC=1 SCAR=0.0
Pod undocumented
37 21 ▶sub default_image_model { 'gpt-image-2' }
Subroutine default_image_model: called CC=1 SCAR=0.0
Pod undocumented
38  
39 # Dynamic model listing
40  
41 88 ▶sub list_models_path { '/models' }
Subroutine list_models_path: called CC=1 SCAR=0.0
Pod documented
42  
43  
44 62 ▶sub list_models_request {
Subroutine list_models_request: called CC=2 SCAR=7.2
Pod documented
45 62 my ($self, %params) = @_;
46 62 my $url = $self->url.$self->list_models_path;
47 62 ▶ if ($params{after}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{"after"}) 0 62 62
48 0 $url .= '?after='.$params{after};
49 }
50 return $self->generate_http_request(
51 GET => $url,
52 10 ▶ sub { $self->list_models_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
53 62 );
54 }
55  
56  
57 14 ▶sub list_models_response {
Subroutine list_models_response: called CC=1 SCAR=0.0
Pod documented
58 14 my ($self, $response) = @_;
59 14 my $data = $self->parse_response($response);
60 11 return $data;
61 }
62  
63  
64 12 ▶sub list_models {
Subroutine list_models: called CC=14 SCAR=29.0
Pod documented
65 12 my ($self, %opts) = @_;
66  
67 # Guard: if supported_operations excludes listModels, fall back to current model
68 12 ▶ unless ($self->can_operation('listModels')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->can_operation("listModels")) 0 12 12
69 0 return [$self->model];
70 }
71  
72 # Check cache unless force_refresh requested
73 12 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 6 6 12
74 6 my $cache = $self->_models_cache;
75 6 ▶ 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) 2 4 6
Condition66%2/3
$cache->{"timestamp"} and time - $cache->{"timestamp"} < $self->models_cache_ttl
!ll&&!rl&&r
402
MC/DC50%1/2
$cache->{"timestamp"} and time - $cache->{"timestamp"} < $self->models_cache_ttl
$cache->{"timestamp"} time - $cache->{"timestamp"} < $self->models_cache_ttl
Truth table66%2/3
A and B
A= $cache->{"timestamp"}B= time - $cache->{"timestamp"} < $self->models_cache_ttl
ABresult
0X0
100
111
76 2 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 1 1 2
77 }
78 }
79  
80 # Fetch all pages
81 10 my @all_models;
82 my $after;
83 10 for my $page (1..100) {
84 10 ▶ my $request = $self->list_models_request($after ? (after => $after) : ());
Branch: 1 branch
BranchTrueFalseTotal
$after ? : 0 10 10
85 10 my $response = $self->user_agent->request($request);
86 10 my $data = $request->response_call->($response);
87 7 ▶ my $models = ref $data eq 'HASH' ? ($data->{data} // []) : $data;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 7 0 7
Condition50%1/2
$data->{"data"} // []
l!l
70
MC/DC0%0/1
$data->{"data"} // []
$data->{"data"}
Truth table50%1/2
A
A= $data->{"data"}
Aresult
11
00
88 7 push @all_models, @$models;
89 7 ▶ last unless ref $data eq 'HASH' && $data->{has_more} && $data->{last_id};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" and $data->{"has_more"} and $data->{"last_id"} 7 0 7
Condition33%2/6
ref $data eq "HASH" and $data->{"has_more"} and $data->{"last_id"}
!ll&&!rl&&r
700
ref $data eq "HASH" and $data->{"has_more"}
!ll&&!rl&&r
070
MC/DC0%0/3
ref $data eq "HASH" and $data->{"has_more"} and $data->{"last_id"}
ref $data eq "HASH" $data->{"has_more"} $data->{"last_id"}
Truth table25%1/4
A and B and C
A= ref $data eq "HASH"B= $data->{"has_more"}C= $data->{"last_id"}
ABCresult
0XX0
10X0
1100
1111
90 0 $after = $data->{last_id};
91 }
92  
93 # Extract IDs and update cache
94 7 my @model_ids = map { $_->{id} } @all_models;
95 7 $self->_models_cache({
96 timestamp => time,
97 models => \@all_models,
98 model_ids => \@model_ids,
99 });
100  
101 7 ▶ return $opts{full} ? \@all_models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 7 7
102 }
103  
104  
105 # Embedding
106  
107 89 ▶sub embedding_operation_id { 'createEmbedding' }
Subroutine embedding_operation_id: called CC=1 SCAR=0.0
Pod undocumented
108  
109 # The body field embedding_dimensions goes out as, or undef when the engine
110 # documents none for its embedding_model: then the attribute is not sent and
111 # carps once per instance (k319). Engines override it.
112 8 ▶sub _embedding_dimensions_field { 'dimensions' }
Subroutine _embedding_dimensions_field: called CC=1 SCAR=0.0
113  
114 94 ▶sub embedding_request {
Subroutine embedding_request: called CC=7 SCAR=19.5
Pod documented
115 94 my ( $self, $input, %extra ) = @_;
116 94 my @dimensions;
117 94 my $size = $self->embedding_dimensions;
118 94 ▶ if ( defined $size && !exists $extra{dimensions} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $size and not exists $extra{"dimensions"}) 20 74 94
Condition100%3/3
defined $size and not exists $extra{"dimensions"}
!ll&&!rl&&r
69520
MC/DC100%2/2
defined $size and not exists $extra{"dimensions"}
defined $size not exists $extra{"dimensions"}
Truth table100%3/3
A and not(B)
A= defined $sizeB= not exists $extra{"dimensions"}
ABresult
0X0
100
111
119 20 my $field = $self->_embedding_dimensions_field;
120 20 ▶ if ( !defined $field ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $field) { } 10 10 20
elsif (not exists $extra{$field}) { } 9 1 10
121 10 ▶ $self->_langertha_carp( "".( ref $self ).": not sending embedding_dimensions=$size -- no "
Condition100%2/2
$self->embedding_model // "served by the server"
l!l
64
MC/DC100%1/1
$self->embedding_model // "served by the server"
$self->embedding_model
Truth table100%2/2
A
A= $self->embedding_model
Aresult
11
00
122 . "documented dimensions field for embedding model '"
123 . ( $self->embedding_model // 'served by the server' ) . "'", 'embedding_dimensions' );
124 }
125 elsif ( !exists $extra{$field} ) {
126 9 @dimensions = ( $field => $size );
127 }
128 }
129 38 ▶ return $self->generate_request( $self->embedding_operation_id, sub { $self->embedding_response(shift, $input) },
Subroutine __ANON__: called CC=1 SCAR=0.0
130 94 ▶ defined $self->embedding_model ? ( model => $self->embedding_model ) : (),
Branch: 1 branch
BranchTrueFalseTotal
defined $self->embedding_model ? : 71 23 94
131 input => $input,
132 @dimensions,
133 %extra,
134 );
135 }
136  
137  
138 45 ▶sub embedding_response {
Subroutine embedding_response: called CC=10 SCAR=23.1
Pod documented
139 45 my ( $self, $response, $input ) = @_;
140 45 my $data = $self->parse_response($response);
141 # tracing
142 # A malformed/error payload that still parses as a 200 JSON body can lack the
143 # `data` array; croak with a readable message instead of a raw deref crash on
144 # @{undef} ("Can't use an undefined value as an ARRAY reference"). Embeddings
145 # must return a vector, so there is no graceful-empty fallback here. -- karr k171
146 36 ▶ unless ( ref $data eq 'HASH' && ref $data->{data} eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $data eq "HASH" and ref $data->{"data"} eq "ARRAY") 2 34 36
Condition66%2/3
ref $data eq "HASH" and ref $data->{"data"} eq "ARRAY"
!ll&&!rl&&r
0234
MC/DC50%1/2
ref $data eq "HASH" and ref $data->{"data"} eq "ARRAY"
ref $data eq "HASH" ref $data->{"data"} eq "ARRAY"
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= ref $data->{"data"} eq "ARRAY"
ABresult
0X0
100
111
147 2 croak "".(ref $self)." embedding response missing 'data' array"
148 . $self->_payload_error_suffix($data);
149 }
150 34 my @objects = @{$data->{data}};
151 # data[].index is the input position and the wire does not promise the array
152 # comes in input order, so sort by it whenever every entry carries one (k289).
153 34 ▶ unless ( grep { ref $_ ne 'HASH' || !defined $_->{index} } @objects ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {ref $_ ne "HASH" or not defined $_->{"index"};} @objects) 33 1 34
Condition66%2/3
ref $_ ne 'HASH' || !defined($_->{'index'})
l!l&&r!l&&!r
0144
MC/DC50%1/2
ref $_ ne 'HASH' || !defined($_->{'index'})
ref $_ ne 'HASH' !defined($_->{'index'})
Truth table66%2/3
A || not(B)
A= ref $_ ne 'HASH'B= !defined($_->{'index'})
ABresult
1X1
011
000
154 33 @objects = sort { $a->{index} <=> $b->{index} } @objects;
155 }
156 34 my @vectors = map { $self->_embedding_vector($_) } @objects;
157 # An empty data array or an entry without a vector is not a result: undef
158 # would be stored as if it were one (Raider's session search did) (k290).
159 34 ▶ if ( !@vectors || grep { ref $_ ne 'ARRAY' || !@{$_} } @vectors ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @vectors or grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors) 2 32 34
Condition83%5/6
not @vectors or grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
l!l&&r!l&&!r
1132
ref $_ ne 'ARRAY' || !@{$_;}
l!l&&r!l&&!r
1044
MC/DC100%2/2
not @vectors or grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
not @vectors grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
MC/DC50%1/2
ref $_ ne 'ARRAY' || !@{$_;}
ref $_ ne 'ARRAY' !@{$_;}
Truth table100%3/3
not(A) or B
A= not @vectorsB= grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
ABresult
1X1
011
000
Truth table66%2/3
A || not(B)
A= ref $_ ne 'ARRAY'B= !@{$_;}
ABresult
1X1
011
000
160 2 croak "".(ref $self)." embedding response contained no vector"
161 . $self->_payload_error_suffix($data);
162 }
163 32 ▶ if ( ref $input eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input eq "ARRAY") 10 22 32
164 croak "".(ref $self)." embedding response returned ".scalar(@vectors)
165 1 ." vectors for ".scalar(@{$input})." inputs"
166 10 ▶ unless @vectors == @{$input};
Branch: 1 branch
BranchTrueFalseTotal
unless @vectors == @{$input;} 1 9 10
167 9 return \@vectors;
168 }
169 22 return $vectors[0];
170 }
171  
172 # One data[] entry's vector. encoding_format => 'base64' answers with a string
173 # of little-endian float32 instead of a float array; decode it, so the caller
174 # gets the same ArrayRef of floats either way (k289).
175 45 ▶sub _embedding_vector {
Subroutine _embedding_vector: called CC=4 SCAR=13.9
176 45 my ( $self, $object ) = @_;
177 45 ▶ my $embedding = ref $object eq 'HASH' ? $object->{embedding} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $object eq 'HASH' ? : 45 0 45
178 45 ▶ return [ unpack 'f<*', decode_base64($embedding) ]
Branch: 1 branch
BranchTrueFalseTotal
if defined $embedding and not ref $embedding 4 41 45
Condition100%3/3
defined $embedding and not ref $embedding
!ll&&!rl&&r
1404
MC/DC100%2/2
defined $embedding and not ref $embedding
defined $embedding not ref $embedding
Truth table100%3/3
A and not(B)
A= defined $embeddingB= not ref $embedding
ABresult
0X0
100
111
179 if defined $embedding && !ref $embedding;
180 41 return $embedding;
181 }
182  
183 # " (error: <message>)" when a 200 body carries a provider error, else ''.
184 8 ▶sub _payload_error_suffix {
Subroutine _payload_error_suffix: called CC=5 SCAR=16.3
185 8 my ( $self, $data ) = @_;
186 my $err = ref $data eq 'HASH' && $data->{error}
187 ? ( ref $data->{error} eq 'HASH' ? $data->{error}{message} : $data->{error} )
188 8 ▶ : undef;
Branch: 2 branches
BranchTrueFalseTotal
ref $data eq 'HASH' && $data->{'error'} ? : 2 6 8
ref $data->{'error'} eq 'HASH' ? : 2 0 2
Condition66%2/3
ref $data eq "HASH" and $data->{"error"}
!ll&&!rl&&r
062
MC/DC50%1/2
ref $data eq "HASH" and $data->{"error"}
ref $data eq "HASH" $data->{"error"}
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= $data->{"error"}
ABresult
0X0
100
111
189 8 ▶ return defined $err ? " (error: $err)" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $err ? : 2 6 8
190 }
191  
192  
193 # Chat
194  
195 1980 ▶sub chat_operation_id { 'createChatCompletion' }
Subroutine chat_operation_id: called CC=1 SCAR=0.0
Pod undocumented
196  
197 # The completion-length body key is engine-overridable. OpenAI's gpt-5.x line
198 # only accepts max_completion_tokens (max_tokens is an HTTP 400 on those
199 # models), so Langertha::Engine::OpenAI overrides this for the gpt-5* family;
200 # every other OpenAI-compatible engine keeps max_tokens.
201 309 ▶sub _max_tokens_key { 'max_tokens' }
Subroutine _max_tokens_key: called CC=1 SCAR=0.0
202  
203 # OpenAI reasoning models (gpt-5.x / gpt-6 / o-series) 400 on a non-default
204 # temperature whenever reasoning is active -- only the wire default (1) is
205 # accepted (karr k155, live-verified 2026-09-17 against /v1/chat/completions).
206 # This gate mirrors AnthropicCompatible::_temperature_kwargs (the
207 # supports('temperature') check + control-beats-attribute resolution) and adds
208 # the OpenAI EFFORT-AWARE drop. The per-model, resolved-effort predicate lives on
209 # the engine (Engine::OpenAI::_temperature_rejected_by_reasoning, inherited by
210 # OpenAIResponses); every other OpenAI-compatible engine never defines it, so the
211 # can() guard leaves their temperature untouched. The drop fires only for a
212 # non-default value under active reasoning: temperature=1 passes through silently
213 # (dropping the wire default would be a pure-noise warning), and a caller who
214 # disables reasoning (reasoning_effort => 'none', where the model accepts it)
215 # keeps its temperature.
216 #
217 # A model that does not take temperature at all (supports('temperature') false:
218 # every current Kimi id fixes it server-side, karr k214) never gets the field,
219 # not even 1. A caller-set non-default value is dropped with a carp rather than
220 # silently (ADR 0025 k214 Update); 1 is dropped quietly.
221 2015 ▶sub _temperature_kwargs {
Subroutine _temperature_kwargs: called CC=17 SCAR=28.4
222 2015 my ( $self, $controls ) = @_;
223 my $temp = exists $controls->{temperature} ? $controls->{temperature}
224 2015 ▶ : $self->can('has_temperature') && $self->has_temperature ? $self->temperature
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'temperature'} ? : 21 1994 2015
$self->can('has_temperature') && $self->has_temperature ? : 89 1905 1994
Condition100%3/3
$self->can("has_temperature") and $self->has_temperature
!ll&&!rl&&r
113179289
MC/DC100%2/2
$self->can("has_temperature") and $self->has_temperature
$self->can("has_temperature") $self->has_temperature
Truth table100%3/3
A and B
A= $self->can("has_temperature")B= $self->has_temperature
ABresult
0X0
100
111
225 : undef;
226 2015 ▶ return () unless defined $temp;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $temp 1905 110 2015
227 # An engine attribute is the same on every request: warn once per engine
228 # instance (karr k247); a per-request control warns every time.
229 my $once = exists $controls->{temperature} ? undef
230 110 ▶ : 'temperature=' . $temp . ' model=' . ( $self->can('chat_model') ? $self->chat_model // '' : '' );
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'temperature'} ? : 21 89 110
$self->can('chat_model') ? : 89 0 89
Condition50%1/2
$self->chat_model // ""
l!l
890
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
231 110 ▶ unless ( $self->supports('temperature') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->supports("temperature")) 55 55 110
232 55 ▶ $self->_langertha_carp( "".( ref $self ).": dropping temperature=$temp -- model '"
Branch: 3 branches
BranchTrueFalseTotal
if $temp != 1 45 10 55
$self->can('chat_model') ? : 45 0 45
defined $once ? : 35 10 45
Condition50%1/2
$self->chat_model // ""
l!l
450
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
233 . ( $self->can('chat_model') ? $self->chat_model // '' : '' )
234 . "' does not take a temperature (rejected or fixed server-side); "
235 . "unset temperature to silence this",
236 defined $once ? "$once unsupported" : undef )
237 if $temp != 1;
238 55 return ();
239 }
240 55 ▶ if ( $temp != 1
Branch: 1 branch
BranchTrueFalseTotal
if ($temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)) 25 30 55
Condition100%6/6
$temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)
!ll&&!rl&&r
82225
$temp != 1 and $self->can("_temperature_rejected_by_reasoning")
!ll&&!rl&&r
1747
MC/DC100%3/3
$temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)
$temp != 1 $self->can("_temperature_rejected_by_reasoning") $self->_temperature_rejected_by_reasoning($controls)
Truth table100%4/4
A and B and C
A= $temp != 1B= $self->can("_temperature_rejected_by_reasoning")C= $self->_temperature_rejected_by_reasoning($controls)
ABCresult
0XX0
10X0
1100
1111
241 && $self->can('_temperature_rejected_by_reasoning')
242 && $self->_temperature_rejected_by_reasoning($controls) ) {
243 25 ▶ $self->_langertha_carp( "".( ref $self ).": dropping temperature=$temp -- this reasoning model "
Branch: 1 branch
BranchTrueFalseTotal
defined $once ? : 20 5 25
244 . "rejects a non-default temperature while reasoning is active (only the "
245 . "wire default 1 is accepted); pass reasoning_effort => 'none' to keep it",
246 defined $once ? "$once reasoning" : undef );
247 25 return ();
248 }
249 30 return ( temperature => $temp );
250 }
251  
252 # Normalize tool_choice to OpenAI native format (accepts Anthropic-style,
253 # OpenAI-style, string shorthands and a Langertha::ToolChoice object), in place,
254 # for both request builders (the streaming one too, karr k235). The wire is
255 # always OpenAI-shaped here (see chat_response), so pin to 'openai' rather than
256 # $self->tool_wire_format (hermes engines / Perplexity). A kind the engine does
257 # not support('tool_choice_*') is not sent (Role::Chat::_gate_tool_choice,
258 # karr k239): Ollama's /v1 has no tool_choice field and ignores one.
259 2015 ▶sub _openai_tool_choice_kwarg {
Subroutine _openai_tool_choice_kwarg: called CC=2 SCAR=6.9
260 2015 my ( $self, $extra ) = @_;
261 2015 ▶ my $tc = $self->_gate_tool_choice($extra) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $tc = $self->_gate_tool_choice($extra) or return 25 1990 2015
262 25 $extra->{tool_choice} = $tc->to('openai');
263 25 return;
264 }
265  
266 # parallel_tool_use -> OpenAI's parallel_tool_calls, gated on
267 # supports('parallel_tool_use') (karr k241); see
268 # Role::Chat::_parallel_tool_calls_kwarg.
269 2015 ▶sub _openai_parallel_tool_calls_kwarg {
Subroutine _openai_parallel_tool_calls_kwarg: called CC=1 SCAR=0.0
270 2015 my ( $self, $extra, $controls ) = @_;
271 2015 return $self->_parallel_tool_calls_kwarg( $extra, $controls );
272 }
273  
274 # The generation block (reasoning + prompt cache) for both request builders,
275 # with chat_template_kwargs merged one level deep (karr k382): the reasoning
276 # serializer's keys (enable_thinking, Langertha::Reasoning::to_chat_template_kwargs)
277 # go first and the caller's chat_template_kwargs from %extra win key by key, so
278 # a caller's other template switches (e.g. thinking => false for DeepSeek-V3.x /
279 # Kimi templates) survive next to ours. The merged hash is written back into
280 # %extra, which the builders spread last. This deliberately differs from
281 # stream_options, where a caller value in %extra replaces ours whole (ADR 0038):
282 # chat_template_kwargs is a bag of independent template switches, not one
283 # setting. Without a caller value ours goes out as-is; without ours the
284 # caller's passes through untouched. An undef caller value is no value (it is
285 # not sent as null); any other non-hash caller value replaces ours whole.
286 2015 ▶sub _openai_generation_kwargs {
Subroutine _openai_generation_kwargs: called CC=5 SCAR=16.1
287 2015 my ( $self, $extra, $controls ) = @_;
288 delete $extra->{chat_template_kwargs}
289 2015 ▶ if exists $extra->{chat_template_kwargs} && !defined $extra->{chat_template_kwargs};
Branch: 1 branch
BranchTrueFalseTotal
if exists $extra->{"chat_template_kwargs"} and not defined $extra->{"chat_template_kwargs"} 1 2014 2015
Condition100%3/3
exists $extra->{"chat_template_kwargs"} and not defined $extra->{"chat_template_kwargs"}
!ll&&!rl&&r
200771
MC/DC100%2/2
exists $extra->{"chat_template_kwargs"} and not defined $extra->{"chat_template_kwargs"}
exists $extra->{"chat_template_kwargs"} not defined $extra->{"chat_template_kwargs"}
Truth table100%3/3
A and not(B)
A= exists $extra->{"chat_template_kwargs"}B= not defined $extra->{"chat_template_kwargs"}
ABresult
0X0
100
111
290 2015 my %generation = $self->generation_kwargs_for(%$controls);
291 1903 ▶ if ( ref $generation{chat_template_kwargs} eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $generation{"chat_template_kwargs"} eq "HASH" and ref $extra->{"chat_template_kwargs"} eq "HASH") 4 1899 1903
Condition100%3/3
ref $generation{"chat_template_kwargs"} eq "HASH" and ref $extra->{"chat_template_kwargs"} eq "HASH"
!ll&&!rl&&r
1818814
MC/DC100%2/2
ref $generation{"chat_template_kwargs"} eq "HASH" and ref $extra->{"chat_template_kwargs"} eq "HASH"
ref $generation{"chat_template_kwargs"} eq "HASH" ref $extra->{"chat_template_kwargs"} eq "HASH"
Truth table100%3/3
A and B
A= ref $generation{"chat_template_kwargs"} eq "HASH"B= ref $extra->{"chat_template_kwargs"} eq "HASH"
ABresult
0X0
100
111
292 && ref $extra->{chat_template_kwargs} eq 'HASH' ) {
293 $extra->{chat_template_kwargs} = {
294 4 %{ delete $generation{chat_template_kwargs} },
295 4 %{ $extra->{chat_template_kwargs} },
296 };
297 }
298 1903 return %generation;
299 }
300  
301 1220 ▶sub chat_request {
Subroutine chat_request: called CC=10 SCAR=23.0
Pod documented
302 1220 my ( $self, $messages, %extra ) = @_;
303  
304 # Canonical per-request controls (chat_f, karr #46) beat the engine
305 # attributes on a per-key basis; the rest of %extra passes straight through.
306 1220 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
574646
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
307  
308 1220 $self->_openai_tool_choice_kwarg(\%extra);
309 1220 $self->_openai_parallel_tool_calls_kwarg(\%extra, $controls);
310  
311 275 ▶ return $self->generate_request( $self->chat_operation_id, sub { $self->chat_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
312 defined $self->chat_model ? ( model => $self->chat_model ) : (),
313 messages => $messages,
314 exists $controls->{max_tokens}
315 ? ( $self->_max_tokens_key => $controls->{max_tokens} )
316 : ( $self->get_response_size ? ( $self->_max_tokens_key => $self->get_response_size ) : () ),
317 exists $controls->{response_format}
318 ? ( response_format => $controls->{response_format} )
319 : ( ($self->can('has_response_format') && $self->has_response_format) ? ( response_format => $self->response_format ) : () ),
320 $self->_temperature_kwargs($controls),
321 1220 ▶ exists $controls->{seed} ? ( seed => $controls->{seed} ) : (),
Branch: 7 branches
BranchTrueFalseTotal
defined $self->chat_model ? : 1220 0 1220
exists $controls->{'max_tokens'} ? : 14 1206 1220
$self->get_response_size ? : 174 1032 1206
exists $controls->{'response_format'} ? : 36 1184 1220
$self->can('has_response_format') && $self->has_response_format ? : 3 1181 1184
exists $controls->{'seed'} ? : 2 1218 1220
$self->can('knobs_kwargs_for') ? : 157 1005 1162
Condition100%3/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
9410873
MC/DC100%2/2
$self->can("has_response_format") and $self->has_response_format
$self->can("has_response_format") $self->has_response_format
Truth table100%3/3
A and B
A= $self->can("has_response_format")B= $self->has_response_format
ABresult
0X0
100
111
322 $self->_openai_generation_kwargs(\%extra, $controls),
323 ( $self->can('knobs_kwargs_for') ? $self->knobs_kwargs_for(%$controls) : () ),
324 stream => JSON->false,
325 %extra,
326 );
327 }
328  
329  
330 # A reply that carries tool calls finishes with 'tool_calls' in the
331 # Chat-Completions convention, but gpt-oss served by vLLM-style stacks (seen
332 # live on AKI.IO, gpt-oss-120b and llama3-chat-8b) answers a non-streaming tool
333 # call with 'stop'. Response.tool_calls is the one tool-call shape (ADR 0003),
334 # so the finish reported alongside it says 'tool_calls' too -- the rule
335 # ResponsesCompatible applies (k171). Only 'stop' is rewritten: 'length' and
336 # the other values carry information ('length' = cut off) and pass through; a
337 # missing finish stays missing. The wire value remains on ->raw.
338 # Shared by chat_response and parse_stream_chunk. -- karr k248, ADR 0018
339 650 ▶sub _openai_finish_reason {
Subroutine _openai_finish_reason: called CC=4 SCAR=13.9
340 650 my ( $self, $finish_reason, $has_tool_calls ) = @_;
341 650 ▶ return 'tool_calls'
Branch: 1 branch
BranchTrueFalseTotal
if $has_tool_calls and defined $finish_reason and $finish_reason eq "stop" 16 634 650
Condition83%5/6
$has_tool_calls and defined $finish_reason and $finish_reason eq "stop"
!ll&&!rl&&r
5508416
$has_tool_calls and defined $finish_reason
!ll&&!rl&&r
5500100
MC/DC66%2/3
$has_tool_calls and defined $finish_reason and $finish_reason eq "stop"
$has_tool_calls defined $finish_reason $finish_reason eq "stop"
Truth table75%3/4
A and B and C
A= $has_tool_callsB= defined $finish_reasonC= $finish_reason eq "stop"
ABCresult
0XX0
10X0
1100
1111
342 if $has_tool_calls && defined $finish_reason && $finish_reason eq 'stop';
343 634 return $finish_reason;
344 }
345  
346 # message.content / delta.content is a string on most OpenAI-compatible
347 # servers, but Mistral's reasoning models (Magistral, or any model called with
348 # reasoning_effort) send a list of content chunks instead:
349 # [ { type => 'thinking', thinking => [ { type => 'text', text => ... } ] },
350 # { type => 'text', text => ... } ]
351 # and a stream switches from the list to plain strings mid-answer.
352 # Response.content and Stream::Chunk.content are Str, so the list is read here,
353 # in the dialect role (ADR 0018 tier 2): text chunks and bare strings join into
354 # content, the text of thinking chunks (a list of text chunks, or a string)
355 # joins into thinking, and any other chunk type (image_url, reference, ...)
356 # carries no answer text and is skipped. Returns ($content, $thinking);
357 # $thinking is undef when no thinking chunk carried text. -- karr k296
358 2416 ▶sub _openai_content_parts {
Subroutine _openai_content_parts: called CC=20 SCAR=31.2
359 2416 my ( $self, $content ) = @_;
360 2416 ▶ return ( $content // '', undef ) unless ref $content;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content 2404 12 2416
Condition100%2/2
$content // ""
l!l
2040364
MC/DC100%1/1
$content // ""
$content
Truth table100%2/2
A
A= $content
Aresult
11
00
361 12 ▶ return ( '', undef ) unless ref $content eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content eq "ARRAY" 0 12 12
362 12 my ( $text, $thinking ) = ( '', undef );
363 12 for my $part (@$content) {
364 32 ▶ if ( !ref $part ) { $text .= $part if defined $part; next }
Branch: 2 branches
BranchTrueFalseTotal
unless (ref $part) 2 30 32
if defined $part 1 1 2
365 30 ▶ next unless ref $part eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $part eq "HASH" 1 29 30
366 29 ▶ my $type = $part->{type} // '';
Condition50%1/2
$part->{"type"} // ""
l!l
290
MC/DC0%0/1
$part->{"type"} // ""
$part->{"type"}
Truth table50%1/2
A
A= $part->{"type"}
Aresult
11
00
367 29 ▶ if ( $type eq 'text' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'text') { } 10 19 29
elsif ($type eq 'thinking') { } 10 9 19
368 10 ▶ $text .= $part->{text} if defined $part->{text} && !ref $part->{text};
Branch: 1 branch
BranchTrueFalseTotal
if defined $part->{"text"} and not ref $part->{"text"} 10 0 10
Condition33%1/3
defined $part->{"text"} and not ref $part->{"text"}
!ll&&!rl&&r
0010
MC/DC0%0/2
defined $part->{"text"} and not ref $part->{"text"}
defined $part->{"text"} not ref $part->{"text"}
Truth table33%1/3
A and not(B)
A= defined $part->{"text"}B= not ref $part->{"text"}
ABresult
0X0
100
111
369 }
370 elsif ( $type eq 'thinking' ) {
371 10 my $inner = $part->{thinking};
372 my @texts = ref $inner eq 'ARRAY'
373 10 ▶ ? map { !ref $_ ? $_ : ref $_ eq 'HASH' && !ref $_->{text} ? $_->{text} : undef } @$inner
Branch: 4 branches
BranchTrueFalseTotal
ref $inner eq 'ARRAY' ? : 9 1 10
!ref($_) ? : 0 15 15
ref $_ eq 'HASH' && !ref($_->{'text'}) ? : 15 0 15
!ref($inner) ? : 1 0 1
Condition33%1/3
ref $_ eq "HASH" and not ref $_->{"text"}
!ll&&!rl&&r
0015
MC/DC0%0/2
ref $_ eq "HASH" and not ref $_->{"text"}
ref $_ eq "HASH" not ref $_->{"text"}
Truth table33%1/3
A and not(B)
A= ref $_ eq "HASH"B= not ref $_->{"text"}
ABresult
0X0
100
111
374 : ( !ref $inner ? $inner : undef );
375 10 ▶ $thinking = ( $thinking // '' ) . $_ for grep { defined } @texts;
Condition100%2/2
$thinking // ""
l!l
610
MC/DC100%1/1
$thinking // ""
$thinking
Truth table100%2/2
A
A= $thinking
Aresult
11
00
376 }
377 }
378 12 return ( $text, $thinking );
379 }
380  
381 540 ▶sub chat_response {
Subroutine chat_response: called CC=26 SCAR=32.7
Pod documented
382 540 my ( $self, $response ) = @_;
383 540 my $data = $self->parse_response($response);
384 # A 200 without a choice is no answer: gateways (OpenRouter and other
385 # proxies) put an `error` object into a 200 body, and an empty choices list
386 # parsed to content '' with no finish_reason -- the same as a model that
387 # legitimately said nothing. Croak, naming the engine and the error, like
388 # the k290 embedding/image croaks. -- karr k301
389 524 ▶ my $choice = ref $data eq 'HASH' && ref $data->{choices} eq 'ARRAY' ? $data->{choices}[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' && ref $data->{'choices'} eq 'ARRAY' ? : 510 14 524
Condition66%2/3
ref $data eq "HASH" and ref $data->{"choices"} eq "ARRAY"
!ll&&!rl&&r
014510
MC/DC50%1/2
ref $data eq "HASH" and ref $data->{"choices"} eq "ARRAY"
ref $data eq "HASH" ref $data->{"choices"} eq "ARRAY"
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= ref $data->{"choices"} eq "ARRAY"
ABresult
0X0
100
111
390 524 ▶ unless ( ref $choice eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $choice eq "HASH") 21 503 524
391 21 ▶ my $error = $self->_body_error_text( ref $data eq 'HASH' ? $data->{error} : undef );
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 21 0 21
392 21 ▶ croak "".(ref $self)." response carried an error: $error" if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 11 10 21
393 10 croak "".(ref $self)." response contained no choices";
394 }
395 # OpenRouter reports a provider failure inside the choice (its `error`,
396 # finish_reason 'error'); that parsed to an empty success. -- karr k311
397 503 ▶ if ( defined( my $error = $self->_openai_choice_error( $data, $choice ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $error = $self->_openai_choice_error($data, $choice))) 8 495 503
398 8 croak "".(ref $self)." response carried an error: $error";
399 }
400 # finish_reason 'error' with no error object anywhere is still a failed
401 # generation, not an answer. -- karr k317
402 croak "".(ref $self)." response ended with finish_reason error"
403 495 ▶ if ( $choice->{finish_reason} // '' ) eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if ($choice->{"finish_reason"} // "") eq "error" 6 489 495
Condition100%2/2
$choice->{"finish_reason"} // ""
l!l
44748
MC/DC100%1/1
$choice->{"finish_reason"} // ""
$choice->{"finish_reason"}
Truth table100%2/2
A
A= $choice->{"finish_reason"}
Aresult
11
00
404 489 ▶ my $msg = $choice->{message} || {};
Condition50%1/2
$choice->{'message'} || {}
l!l
4890
MC/DC0%0/1
$choice->{'message'} || {}
$choice->{'message'}
Truth table50%1/2
A
A= $choice->{'message'}
Aresult
11
00
405 # The OpenAI-compatible response envelope is always OpenAI-shaped, even for
406 # engines whose tool_wire_format is 'hermes' (their calls ride in the message
407 # text, parsed elsewhere).
408 # Pin the structured extractor to 'openai' rather than $self->tool_wire_format.
409 489 my @tcs = Langertha::ToolCall->extract( 'openai', $data );
410 # Chain-of-thought reaches the OpenAI-compatible message under two spellings:
411 # the DeepSeek/SGLang/Moonshot/xAI `reasoning_content`, and the bare
412 # `reasoning` that vLLM (renamed from reasoning_content), Groq, Cerebras,
413 # OpenRouter and AKI.IO send. Read the canonical spelling first, then fall
414 # back to `reasoning` -- guarded !ref so OpenRouter's structured
415 # `reasoning_details` ARRAY (or any non-string shape) never lands in the Str
416 # thinking attribute. The precedence tests `length`, not `defined`: a server
417 # that keeps `reasoning_content` as an empty back-compat stub beside a filled
418 # `reasoning` must not mask it -- the exact failure mode the vLLM migration
419 # note warns about. -- karr k127, k129, k79
420 # A content-chunk list (Mistral reasoning models) carries its own thinking
421 # chunks; they fill thinking only when neither reasoning field did. -- k296
422 489 my ( $content, $part_thinking ) = $self->_openai_content_parts( $msg->{content} );
423 my $thinking =
424 length( $msg->{reasoning_content} // '' ) ? $msg->{reasoning_content}
425 : ( defined $msg->{reasoning} && !ref $msg->{reasoning} ) ? $msg->{reasoning}
426 489 ▶ : $part_thinking;
Branch: 2 branches
BranchTrueFalseTotal
length($msg->{'reasoning_content'} // '') ? : 6 483 489
defined $msg->{'reasoning'} && !ref($msg->{'reasoning'}) ? : 13 470 483
Condition100%5/5
$msg->{"reasoning_content"} // ""
l!l
7482
defined $msg->{"reasoning"} and not ref $msg->{"reasoning"}
!ll&&!rl&&r
469113
MC/DC100%1/1
$msg->{"reasoning_content"} // ""
$msg->{"reasoning_content"}
MC/DC100%2/2
defined $msg->{"reasoning"} and not ref $msg->{"reasoning"}
defined $msg->{"reasoning"} not ref $msg->{"reasoning"}
Truth table100%2/2
A
A= $msg->{"reasoning_content"}
Aresult
11
00
Truth table100%3/3
A and not(B)
A= defined $msg->{"reasoning"}B= not ref $msg->{"reasoning"}
ABresult
0X0
100
111
427 return Langertha::Response->new(
428 content => $content,
429 raw => $data,
430 $data->{id} ? ( id => $data->{id} ) : (),
431 $data->{model} ? ( model => $data->{model} ) : (),
432 defined $choice->{finish_reason}
433 ? ( finish_reason => $self->_openai_finish_reason( $choice->{finish_reason}, scalar @tcs ) ) : (),
434 $data->{usage} ? ( usage => $self->_wire_usage( $data->{usage} ) ) : (),
435 ( $data->{usage} && $data->{usage}{prompt_tokens_details}
436 && defined $data->{usage}{prompt_tokens_details}{cached_tokens}
437 ? ( cached_tokens => $data->{usage}{prompt_tokens_details}{cached_tokens} ) : () ),
438 $data->{created} ? ( created => $data->{created} ) : (),
439 defined $thinking ? ( thinking => $thinking ) : (),
440 # A declined structured-output request answers content null plus
441 # message.refusal; it was reachable only through raw (ADR 0004). -- k301
442 489 ▶ ( defined $msg->{refusal} && !ref $msg->{refusal} ? ( refusal => $msg->{refusal} ) : () ),
Branch: 9 branches
BranchTrueFalseTotal
$data->{'id'} ? : 324 165 489
$data->{'model'} ? : 275 214 489
defined $choice->{'finish_reason'} ? : 441 48 489
$data->{'usage'} ? : 57 432 489
$data->{'usage'} && $data->{'usage'}{'prompt_tokens_details'} && defined $data->{'usage'}{'prompt_tokens_details'}{'cached_tokens'} ? : 25 464 489
$data->{'created'} ? : 146 343 489
defined $thinking ? : 26 463 489
defined $msg->{'refusal'} && !ref($msg->{'refusal'}) ? : 1 488 489
@tcs ? : 86 403 489
Condition77%7/9
$data->{"usage"} and $data->{"usage"}{"prompt_tokens_details"} and defined $data->{"usage"}{"prompt_tokens_details"}{"cached_tokens"}
!ll&&!rl&&r
464025
$data->{"usage"} and $data->{"usage"}{"prompt_tokens_details"}
!ll&&!rl&&r
4323225
defined $msg->{"refusal"} and not ref $msg->{"refusal"}
!ll&&!rl&&r
48801
MC/DC66%2/3
$data->{"usage"} and $data->{"usage"}{"prompt_tokens_details"} and defined $data->{"usage"}{"prompt_tokens_details"}{"cached_tokens"}
$data->{"usage"} $data->{"usage"}{"prompt_tokens_details"} defined $data->{"usage"}{"prompt_tokens_details"}{"cached_tokens"}
MC/DC50%1/2
defined $msg->{"refusal"} and not ref $msg->{"refusal"}
defined $msg->{"refusal"} not ref $msg->{"refusal"}
Truth table75%3/4
A and B and C
A= $data->{"usage"}B= $data->{"usage"}{"prompt_tokens_details"}C= defined $data->{"usage"}{"prompt_tokens_details"}{"cached_tokens"}
ABCresult
0XX0
10X0
1100
1111
Truth table66%2/3
A and not(B)
A= defined $msg->{"refusal"}B= not ref $msg->{"refusal"}
ABresult
0X0
100
111
443 @tcs ? ( tool_calls => [ @tcs ] ) : (),
444 );
445 }
446  
447 # The usage block as it goes onto the Response / a stream chunk. The default is
448 # the wire block itself; an engine that knows something the wire does not say
449 # overrides it and returns a copy with a canonical key added (OpenRouter states
450 # that its bare usage.cost is USD as cost_usd; ADR 0018 tier 3, ADR 0031, k363),
451 # as Role::AnthropicCompatible's _wire_usage does for input_includes_cache.
452 # The wire hash itself is never modified.
453 83 ▶sub _wire_usage {
Subroutine _wire_usage: called CC=1 SCAR=0.0
454 83 my ( $self, $usage ) = @_;
455 83 return $usage;
456 }
457  
458  
459 # The error a choice reports, as "message (code)", or undef: the choice's own
460 # `error` (OpenRouter's NonStreamingChoice / StreamingChoice `error`), or a
461 # top-level `error` beside a choice whose finish_reason is 'error' --
462 # OpenRouter's documented mid-stream failure frame. Shapes:
463 # https://openrouter.ai/docs/api-reference/overview and .../errors -- k311
464 2433 ▶sub _openai_choice_error {
Subroutine _openai_choice_error: called CC=5 SCAR=16.3
465 2433 my ( $self, $data, $choice ) = @_;
466 2433 ▶ return $self->_body_error_text( $choice->{error} ) if defined $choice->{error};
Branch: 1 branch
BranchTrueFalseTotal
if defined $choice->{"error"} 8 2425 2433
467 return $self->_body_error_text( $data->{error} )
468 2425 ▶ if defined $data->{error} && ( $choice->{finish_reason} // '' ) eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if defined $data->{"error"} and ($choice->{"finish_reason"} // "") eq "error" 2 2423 2425
Condition60%3/5
defined $data->{"error"} and ($choice->{"finish_reason"} // "") eq "error"
!ll&&!rl&&r
242302
$choice->{"finish_reason"} // ""
l!l
20
MC/DC50%1/2
defined $data->{"error"} and ($choice->{"finish_reason"} // "") eq "error"
defined $data->{"error"} $choice->{"finish_reason"}
Truth table66%2/3
A and B
A= defined $data->{"error"}B= $choice->{"finish_reason"}
ABresult
0X0
100
111
469 2423 return undef;
470 }
471  
472  
473 # Transcription
474  
475 58 ▶sub transcription_operation_id { 'createTranscription' }
Subroutine transcription_operation_id: called CC=1 SCAR=0.0
Pod undocumented
476  
477 64 ▶sub transcription_request {
Subroutine transcription_request: called CC=10 SCAR=23.1
Pod documented
478 64 my ( $self, $file, %extra ) = @_;
479 64 my $filename = delete $extra{filename};
480 # A list goes out as repeated languages[] parts (k286 convention), never as
481 # a file spec. gpt-transcribe takes only that plural field, so a singular
482 # language is folded into it for that model (k313).
483 128 ▶ my @languages = map { ref $_ eq 'ARRAY' ? @$_ : defined $_ ? ($_) : () }
Branch: 2 branches
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 3 125 128
defined $_ ? : 0 125 125
484 64 delete @extra{qw( languages languages[] )};
485 64 ▶ my $model = exists $extra{model} ? $extra{model} : $self->transcription_model;
Branch: 1 branch
BranchTrueFalseTotal
exists $extra{'model'} ? : 4 60 64
486 64 ▶ if ( defined $model && $model =~ /\Agpt-transcribe/ && defined $extra{language} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $model and $model =~ /\Agpt-transcribe/ and defined $extra{"language"}) 15 49 64
Condition83%5/6
defined $model and $model =~ /\Agpt-transcribe/ and defined $extra{"language"}
!ll&&!rl&&r
311815
defined $model and $model =~ /\Agpt-transcribe/
!ll&&!rl&&r
03133
MC/DC66%2/3
defined $model and $model =~ /\Agpt-transcribe/ and defined $extra{"language"}
defined $model $model =~ /\Agpt-transcribe/ defined $extra{"language"}
Truth table75%3/4
A and B and C
A= defined $modelB= $model =~ /\Agpt-transcribe/C= defined $extra{"language"}
ABCresult
0XX0
10X0
1100
1111
487 15 my $language = delete $extra{language};
488 15 ▶ push @languages, $language unless grep { $_ eq $language } @languages;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $language;} @languages 14 1 15
489 }
490 64 ▶ $extra{'languages[]'} = \@languages if @languages;
Branch: 1 branch
BranchTrueFalseTotal
if @languages 17 47 64
491 18 ▶ return $self->generate_request( $self->transcription_operation_id, sub { $self->transcription_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
492 64 ▶ file => $self->transcription_file_part( $file, $filename ),
Branch: 1 branch
BranchTrueFalseTotal
$self->transcription_model ? : 59 4 63
493 $self->transcription_model ? ( model => $self->transcription_model ) : (),
494 %extra,
495 );
496 }
497  
498  
499 61 ▶sub transcription_result {
Subroutine transcription_result: called CC=7 SCAR=19.5
Pod documented
500 61 my ( $self, $response ) = @_;
501 # response_format json / verbose_json answer JSON; text, srt and vtt answer
502 # the transcript as a plain body. Decide by Content-Type, and by the body
503 # only when the type says neither (a transcript can start with "{" but is
504 # then served as text/*). -- karr k288
505 61 ▶ my $type = lc( $response->content_type // '' );
Condition50%1/2
$response->content_type // ""
l!l
610
MC/DC0%0/1
$response->content_type // ""
$response->content_type
Truth table50%1/2
A
A= $response->content_type
Aresult
11
00
506 61 ▶ my $is_json = $type =~ /json/
Condition100%6/6
$type =~ /json/ || !($type =~ m[\Atext/]) && $response->content =~ /\A\s*\{/
l!l&&r!l&&!r
46114
not $type =~ m[\Atext/] and $response->content =~ /\A\s*\{/
!ll&&!rl&&r
1311
MC/DC100%3/3
$type =~ /json/ || !($type =~ m[\Atext/]) && $response->content =~ /\A\s*\{/
$type =~ /json/ not $type =~ m[\Atext/] $response->content =~ /\A\s*\{/
Truth table100%4/4
A || not(B) and C
A= $type =~ /json/B= not $type =~ m[\Atext/]C= $response->content =~ /\A\s*\{/
ABCresult
1XX1
0111
00X0
0100
507 || ( $type !~ m{\Atext/} && $response->content =~ /\A\s*\{/ );
508 61 ▶ return $self->parse_response($response) if $is_json || !$response->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $is_json or not $response->is_success 48 13 61
Condition100%3/3
$is_json or not $response->is_success
l!l&&r!l&&!r
47113
MC/DC100%2/2
$is_json or not $response->is_success
$is_json not $response->is_success
Truth table100%3/3
A or not(B)
A= $is_jsonB= not $response->is_success
ABresult
1X1
011
000
509 13 ▶ $self->_update_rate_limit($response) if $self->can('_update_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_update_rate_limit") 13 0 13
510 # Bounded Content-Encoding decode (karr k346): a gzip transcript body inflates
511 # under response_max_bytes or is refused with the too-big croak.
512 13 return { text => $self->_bounded_decoded_content( $response, default_charset => 'UTF-8' ) };
513 }
514  
515  
516 39 ▶sub transcription_response {
Subroutine transcription_response: called CC=1 SCAR=0.0
Pod documented
517 39 my ( $self, $response ) = @_;
518 39 return $self->transcription_result($response)->{text};
519 }
520  
521  
522 # Streaming
523  
524 248 ▶sub stream_format { 'sse' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod documented
525  
526  
527 795 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=11 SCAR=24.7
Pod documented
528 795 my ( $self, $messages, %extra ) = @_;
529  
530 # Same canonical-control consumption as chat_request (karr #46).
531 795 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
460335
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
532  
533 # Same tool_choice normalization and parallel_tool_calls placement as
534 # chat_request (karr k235, k240).
535 795 $self->_openai_tool_choice_kwarg(\%extra);
536 795 $self->_openai_parallel_tool_calls_kwarg(\%extra, $controls);
537  
538 0 ▶ return $self->generate_request( $self->chat_operation_id, sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
539 defined $self->chat_model ? ( model => $self->chat_model ) : (),
540 messages => $messages,
541 exists $controls->{max_tokens}
542 ? ( $self->_max_tokens_key => $controls->{max_tokens} )
543 : ( $self->get_response_size ? ( $self->_max_tokens_key => $self->get_response_size ) : () ),
544 exists $controls->{response_format}
545 ? ( response_format => $controls->{response_format} )
546 : ( ($self->can('has_response_format') && $self->has_response_format) ? ( response_format => $self->response_format ) : () ),
547 $self->_temperature_kwargs($controls),
548 795 ▶ exists $controls->{seed} ? ( seed => $controls->{seed} ) : (),
Branch: 8 branches
BranchTrueFalseTotal
defined $self->chat_model ? : 795 0 795
exists $controls->{'max_tokens'} ? : 0 795 795
$self->get_response_size ? : 125 670 795
exists $controls->{'response_format'} ? : 1 794 795
$self->can('has_response_format') && $self->has_response_format ? : 0 794 794
exists $controls->{'seed'} ? : 0 795 795
$self->can('knobs_kwargs_for') ? : 107 634 741
$self->supports('stream_usage') ? : 513 228 741
Condition66%2/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
197750
MC/DC0%0/2
$self->can("has_response_format") and $self->has_response_format
$self->can("has_response_format") $self->has_response_format
Truth table66%2/3
A and B
A= $self->can("has_response_format")B= $self->has_response_format
ABresult
0X0
100
111
549 $self->_openai_generation_kwargs(\%extra, $controls),
550 ( $self->can('knobs_kwargs_for') ? $self->knobs_kwargs_for(%$controls) : () ),
551 stream => JSON->true,
552 # The stream's token usage comes only when the request asks for it; before
553 # %extra, so a stream_options the caller passes wins. Gated: some
554 # compatible servers reject a field they do not know (ADR 0038).
555 $self->supports('stream_usage') ? ( stream_options => { include_usage => JSON->true } ) : (),
556 %extra,
557 );
558 }
559  
560  
561 1946 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=56 SCAR=41.8
Pod documented
562 1946 my ( $self, $data, $event, $state ) = @_;
563  
564 1946 ▶ return undef unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 1946 1946
565  
566 # A gateway that fails mid-stream (OpenRouter) sends a frame with a
567 # top-level `error` object and no choice. Returning undef ended the stream
568 # as a short, silent success; the croak fails the stream future, as the
569 # Responses parser does for its error events. -- karr k301
570 1946 ▶ if ( defined $data->{error} && !( ref $data->{choices} eq 'ARRAY' && @{ $data->{choices} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data->{"error"} and not ref $data->{"choices"} eq "ARRAY" && @{$data->{"choices"};}) 1 1945 1946
Condition83%5/6
defined $data->{"error"} and not ref $data->{"choices"} eq "ARRAY" && @{$data->{"choices"};}
!ll&&!rl&&r
194411
ref $data->{'choices'} eq 'ARRAY' && @{$data->{'choices'};}
!ll&&!rl&&r
101
MC/DC66%2/3
defined $data->{"error"} and not ref $data->{"choices"} eq "ARRAY" && @{$data->{"choices"};}
defined $data->{"error"} ref $data->{'choices'} eq 'ARRAY' @{$data->{'choices'};}
Truth table75%3/4
A and not(B && C)
A= defined $data->{"error"}B= ref $data->{'choices'} eq 'ARRAY'C= @{$data->{'choices'};}
ABCresult
0XX0
1110
10X1
1101
571 1 croak "".(ref $self)." stream carried an error: ".$self->_body_error_text( $data->{error} );
572 }
573 # OpenRouter's mid-stream failure frame keeps a choice (delta content '',
574 # finish_reason 'error') beside the error, or puts the error on the choice;
575 # both ended the stream as a silent success. -- karr k311
576 1945 ▶ if ( ref $data->{choices} eq 'ARRAY' && ref $data->{choices}[0] eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH" and defined(my $error = $self->_openai_choice_error($data, $data->{"choices"}[0]))) 2 1943 1945
Condition83%5/6
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH" and defined(my $error = $self->_openai_choice_error($data, $data->{"choices"}[0]))
!ll&&!rl&&r
1519282
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH"
!ll&&!rl&&r
0151930
MC/DC66%2/3
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH" and defined(my $error = $self->_openai_choice_error($data, $data->{"choices"}[0]))
ref $data->{"choices"} eq "ARRAY" ref $data->{"choices"}[0] eq "HASH" defined(my $error = $self->_openai_choice_error($data, $data->{"choices"}[0]))
Truth table75%3/4
A and B and C
A= ref $data->{"choices"} eq "ARRAY"B= ref $data->{"choices"}[0] eq "HASH"C= defined(my $error = $self->_openai_choice_error($data, $data->{"choices"}[0]))
ABCresult
0XX0
10X0
1100
1111
577 && defined( my $error = $self->_openai_choice_error( $data, $data->{choices}[0] ) ) ) {
578 2 croak "".(ref $self)." stream carried an error: $error";
579 }
580 # The same frame without any error object still ends a failed stream. -- k317
581 1943 ▶ if ( ref $data->{choices} eq 'ARRAY' && ref $data->{choices}[0] eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH" and ($data->{"choices"}[0]{"finish_reason"} // "") eq "error") 1 1942 1943
Condition87%7/8
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH" and ($data->{"choices"}[0]{"finish_reason"} // "") eq "error"
!ll&&!rl&&r
1519271
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH"
!ll&&!rl&&r
0151928
$data->{"choices"}[0]{"finish_reason"} // ""
l!l
2151713
MC/DC66%2/3
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH" and ($data->{"choices"}[0]{"finish_reason"} // "") eq "error"
ref $data->{"choices"} eq "ARRAY" ref $data->{"choices"}[0] eq "HASH" $data->{"choices"}[0]{"finish_reason"}
Truth table75%3/4
A and B and C
A= ref $data->{"choices"} eq "ARRAY"B= ref $data->{"choices"}[0] eq "HASH"C= $data->{"choices"}[0]{"finish_reason"}
ABCresult
0XX0
10X0
1100
1111
582 && ( $data->{choices}[0]{finish_reason} // '' ) eq 'error' ) {
583 1 croak "".(ref $self)." stream ended with finish_reason error";
584 }
585  
586 # With stream_options.include_usage (OpenAI; vLLM and SGLang emit it too) the
587 # usage arrives in a frame of its own after the finish chunk, with an empty
588 # choices list. It becomes a content-less, non-final chunk carrying the usage
589 # (and cached_tokens), so aggregate_usage and a caller scanning the chunks
590 # see it; dropping it lost the stream's token counts. -- karr k298
591 1942 ▶ my $choice = ref $data->{choices} eq 'ARRAY' ? $data->{choices}[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{'choices'} eq 'ARRAY' ? : 1942 0 1942
592 1942 ▶ unless ($choice) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($choice) 15 1927 1942
593 15 ▶ return undef unless ref $data->{usage} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data->{"usage"} eq "HASH" 2 13 15
594 13 require Langertha::Stream::Chunk;
595 return Langertha::Stream::Chunk->new(
596 content => '',
597 raw => $data,
598 is_final => 0,
599 $data->{model} ? ( model => $data->{model} ) : (),
600 13 ▶ $self->_openai_stream_usage_kwargs( $data->{usage} ),
Branch: 1 branch
BranchTrueFalseTotal
$data->{'model'} ? : 13 0 13
601 );
602 }
603  
604 # delta.content may be a content-chunk list too (k296, see
605 # _openai_content_parts); its thinking chunks feed the thinking below.
606 my ( $content, $part_thinking ) = $self->_openai_content_parts(
607 1927 ▶ ref $choice->{delta} eq 'HASH' ? $choice->{delta}{content} : undef );
Branch: 1 branch
BranchTrueFalseTotal
ref $choice->{'delta'} eq 'HASH' ? : 1927 0 1927
608 1927 my $finish_reason = $choice->{finish_reason};
609  
610 # A streamed tool call arrives as delta.tool_calls fragments keyed by
611 # `index`: the first carries id, type and function.name, the rest append to
612 # function.arguments, and fragments of parallel calls interleave. Assemble
613 # them per index in this stream's state and deliver the finished calls on the
614 # chunk that carries finish_reason -- read by the same
615 # ToolCall->extract('openai', ...) chat_response uses, so a streamed and a
616 # non-streamed reply of one response yield the same calls. The calls leave the
617 # state as they are delivered, so none arrives twice. A fragment without
618 # `index` (servers that stream whole calls) is keyed by its id, and only by
619 # its position when it has neither; an empty-string finish_reason is no
620 # finish and flushes nothing. A stream that ends without a finish_reason is
621 # reported by _finish_stream_state. -- karr k221
622 1927 ▶ $state //= $self->_stream_parse_state;
Condition66%2/3
$state //= $self->_stream_parse_state
l!l&&r!l&&!r
1887400
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
623 1927 ▶ my $pending = $state->{openai_tool_calls} //= {};
Condition100%2/2
$state->{"openai_tool_calls"} //= {}
l!l
1688239
MC/DC100%1/1
$state->{"openai_tool_calls"} //= {}
$state->{"openai_tool_calls"}
Truth table100%2/2
A
A= $state->{"openai_tool_calls"}
Aresult
11
00
624 1927 ▶ my $order = $state->{openai_tool_order} //= [];
Condition100%2/2
$state->{"openai_tool_order"} //= []
l!l
1688239
MC/DC100%1/1
$state->{"openai_tool_order"} //= []
$state->{"openai_tool_order"}
Truth table100%2/2
A
A= $state->{"openai_tool_order"}
Aresult
11
00
625 1927 ▶ my $delta_calls = ref $choice->{delta} eq 'HASH' ? $choice->{delta}{tool_calls} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $choice->{'delta'} eq 'HASH' ? : 1927 0 1927
626 1927 ▶ if ( ref $delta_calls eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $delta_calls eq "ARRAY") 62 1865 1927
627 62 for my $pos ( 0 .. $#$delta_calls ) {
628 62 my $fragment = $delta_calls->[$pos];
629 62 ▶ next unless ref $fragment eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fragment eq "HASH" 0 62 62
630 my $key = defined $fragment->{index} ? "index:$fragment->{index}"
631 62 ▶ : length( $fragment->{id} // '' ) ? "id:$fragment->{id}"
Branch: 2 branches
BranchTrueFalseTotal
defined $fragment->{'index'} ? : 60 2 62
length($fragment->{'id'} // '') ? : 2 0 2
Condition50%1/2
$fragment->{"id"} // ""
l!l
20
MC/DC0%0/1
$fragment->{"id"} // ""
$fragment->{"id"}
Truth table50%1/2
A
A= $fragment->{"id"}
Aresult
11
00
632 : "pos:$pos";
633 62 ▶ my $call = $pending->{$key} //= do {
Condition66%2/3
$pending->{$key} //= do { push @$order, $key; +{"type", "function", "function", {"arguments", ""}} }
l!l&&r!l&&!r
39230
MC/DC0%0/2
$pending->{$key} //= do { push @$order, $key; +{"type", "function", "function", {"arguments", ""}} }
$pending->{$key} do { push @$order, $key; +{"type", "function", "function", {"arguments", ""}} }
Truth table66%2/3
A //= B
A= $pending->{$key}B= do { push @$order, $key; +{"type", "function", "function", {"arguments", ""}} }
ABresult
1X1
011
000
634 23 push @$order, $key;
635 23 { type => 'function', function => { arguments => '' } };
636 };
637 62 ▶ $call->{id} = $fragment->{id} if !length( $call->{id} // '' ) && length( $fragment->{id} // '' );
Branch: 1 branch
BranchTrueFalseTotal
if not length($call->{"id"} // "") and length($fragment->{"id"} // "") 23 39 62
Condition71%5/7
not length($call->{"id"} // "") and length($fragment->{"id"} // "")
!ll&&!rl&&r
39023
$call->{"id"} // ""
l!l
3923
$fragment->{"id"} // ""
l!l
230
MC/DC50%1/2
not length($call->{"id"} // "") and length($fragment->{"id"} // "")
$call->{"id"} $fragment->{"id"}
Truth table66%2/3
not(A) and B
A= $call->{"id"}B= $fragment->{"id"}
ABresult
1X0
000
011
638 62 ▶ my $fn = ref $fragment->{function} eq 'HASH' ? $fragment->{function} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $fragment->{'function'} eq 'HASH' ? : 62 0 62
639 $call->{function}{name} = $fn->{name}
640 62 ▶ if !length( $call->{function}{name} // '' ) && length( $fn->{name} // '' );
Branch: 1 branch
BranchTrueFalseTotal
if not length($call->{"function"}{"name"} // "") and length($fn->{"name"} // "") 23 39 62
Condition71%5/7
not length($call->{"function"}{"name"} // "") and length($fn->{"name"} // "")
!ll&&!rl&&r
39023
$call->{"function"}{"name"} // ""
l!l
3923
$fn->{"name"} // ""
l!l
230
MC/DC50%1/2
not length($call->{"function"}{"name"} // "") and length($fn->{"name"} // "")
$call->{"function"}{"name"} $fn->{"name"}
Truth table66%2/3
not(A) and B
A= $call->{"function"}{"name"}B= $fn->{"name"}
ABresult
1X0
000
011
641 0 ▶ if ( ref $fn->{arguments} ) { $call->{function}{arguments} = $fn->{arguments} }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $fn->{'arguments'}) { } 0 62 62
elsif (defined $fn->{'arguments'}) { } 62 0 62
642 62 elsif ( defined $fn->{arguments} ) { $call->{function}{arguments} .= $fn->{arguments} }
643 }
644 }
645 1927 my @tool_calls;
646 1927 ▶ if ( length( $finish_reason // '' ) && @$order ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length($finish_reason // "") and @$order) 16 1911 1927
Condition100%5/5
length($finish_reason // "") and @$order
!ll&&!rl&&r
171819316
$finish_reason // ""
l!l
2141713
MC/DC100%2/2
length($finish_reason // "") and @$order
$finish_reason @$order
Truth table100%3/3
A and B
A= $finish_reasonB= @$order
ABresult
0X0
100
111
647 16 my @calls = map { $pending->{$_} } @$order;
648 16 %$pending = ();
649 16 @$order = ();
650 16 @tool_calls = Langertha::ToolCall->extract( 'openai',
651 { choices => [ { message => { tool_calls => \@calls } } ] } );
652 }
653  
654 # Streamed chain-of-thought reaches the delta under the same two spellings the
655 # non-streaming chat_response reads: the DeepSeek/SGLang/Moonshot/xAI
656 # `reasoning_content`, and the bare `reasoning` that vLLM (renamed from
657 # reasoning_content), Cerebras and AKI.IO send. Read the canonical spelling
658 # first, then fall back to `reasoning` -- guarded !ref so a non-string shape
659 # (e.g. OpenRouter's `reasoning_details` ARRAY, which the docs put on the
660 # delta) never lands in the Str thinking attribute. As in chat_response the
661 # precedence tests `length`, not `defined`, so an empty back-compat
662 # `reasoning_content` stub cannot mask a filled `reasoning`. -- karr k129, k79
663 1927 ▶ my $delta = $choice->{delta} || {};
Condition50%1/2
$choice->{'delta'} || {}
l!l
19270
MC/DC0%0/1
$choice->{'delta'} || {}
$choice->{'delta'}
Truth table50%1/2
A
A= $choice->{'delta'}
Aresult
11
00
664 my $thinking =
665 length( $delta->{reasoning_content} // '' ) ? $delta->{reasoning_content}
666 : ( defined $delta->{reasoning} && !ref $delta->{reasoning} ) ? $delta->{reasoning}
667 1927 ▶ : $part_thinking;
Branch: 2 branches
BranchTrueFalseTotal
length($delta->{'reasoning_content'} // '') ? : 12 1915 1927
defined $delta->{'reasoning'} && !ref($delta->{'reasoning'}) ? : 8 1907 1915
Condition100%5/5
$delta->{"reasoning_content"} // ""
l!l
131914
defined $delta->{"reasoning"} and not ref $delta->{"reasoning"}
!ll&&!rl&&r
190618
MC/DC100%1/1
$delta->{"reasoning_content"} // ""
$delta->{"reasoning_content"}
MC/DC100%2/2
defined $delta->{"reasoning"} and not ref $delta->{"reasoning"}
defined $delta->{"reasoning"} not ref $delta->{"reasoning"}
Truth table100%2/2
A
A= $delta->{"reasoning_content"}
Aresult
11
00
Truth table100%3/3
A and not(B)
A= defined $delta->{"reasoning"}B= not ref $delta->{"reasoning"}
ABresult
0X0
100
111
668  
669 # An empty-string finish_reason is no finish here either (as for the tool
670 # call flush above): the chunk is not final and carries no finish_reason,
671 # as Gemini's parser reads an empty finishReason. -- karr k253 review
672 1927 ▶ my $finished = length( $finish_reason // '' );
Condition100%2/2
$finish_reason // ""
l!l
2141713
MC/DC100%1/1
$finish_reason // ""
$finish_reason
Truth table100%2/2
A
A= $finish_reason
Aresult
11
00
673  
674 1927 require Langertha::Stream::Chunk;
675 return Langertha::Stream::Chunk->new(
676 content => $content,
677 raw => $data,
678 is_final => $finished ? 1 : 0,
679 $finished
680 ? (finish_reason => $self->_openai_finish_reason( $finish_reason, scalar @tool_calls )) : (),
681 $data->{model} ? (model => $data->{model}) : (),
682 $self->_openai_stream_usage_kwargs( $data->{usage} ),
683 defined $thinking ? ( thinking => $thinking ) : (),
684 ( defined $delta->{refusal} && !ref $delta->{refusal} && length $delta->{refusal}
685 1927 ▶ ? ( refusal => $delta->{refusal} ) : () ),
Branch: 6 branches
BranchTrueFalseTotal
$finished ? : 209 1718 1927
$finished ? : 209 1718 1927
$data->{'model'} ? : 178 1749 1927
defined $thinking ? : 22 1905 1927
defined $delta->{'refusal'} && !ref($delta->{'refusal'}) && length $delta->{'refusal'} ? : 1 1926 1927
@tool_calls ? : 16 1911 1927
Condition66%4/6
defined $delta->{"refusal"} and not ref $delta->{"refusal"} and length $delta->{"refusal"}
!ll&&!rl&&r
192601
defined $delta->{"refusal"} and not ref $delta->{"refusal"}
!ll&&!rl&&r
192601
MC/DC33%1/3
defined $delta->{"refusal"} and not ref $delta->{"refusal"} and length $delta->{"refusal"}
defined $delta->{"refusal"} not ref $delta->{"refusal"} length $delta->{"refusal"}
Truth table50%2/4
A and not(B) and C
A= defined $delta->{"refusal"}B= not ref $delta->{"refusal"}C= length $delta->{"refusal"}
ABCresult
0XX0
10X0
1100
1111
686 @tool_calls ? ( tool_calls => \@tool_calls ) : (),
687 );
688 }
689  
690 # The usage and cached_tokens constructor arguments of a stream chunk for one
691 # wire usage block (empty when there is none). Shared by the choice and the
692 # usage-only chunk, and by engines that find usage elsewhere (Groq's
693 # x_groq.usage). -- karr k298
694 1953 ▶sub _openai_stream_usage_kwargs {
Subroutine _openai_stream_usage_kwargs: called CC=4 SCAR=13.9
695 1953 my ( $self, $usage ) = @_;
696 1953 ▶ return () unless ref $usage eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 1925 28 1953
697 28 my $details = $usage->{prompt_tokens_details};
698 return (
699 usage => $self->_wire_usage($usage),
700 ( ref $details eq 'HASH' && defined $details->{cached_tokens}
701 28 ▶ ? ( cached_tokens => $details->{cached_tokens} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
ref $details eq 'HASH' && defined $details->{'cached_tokens'} ? : 17 11 28
Condition66%2/3
ref $details eq "HASH" and defined $details->{"cached_tokens"}
!ll&&!rl&&r
11017
MC/DC50%1/2
ref $details eq "HASH" and defined $details->{"cached_tokens"}
ref $details eq "HASH" defined $details->{"cached_tokens"}
Truth table66%2/3
A and B
A= ref $details eq "HASH"B= defined $details->{"cached_tokens"}
ABresult
0X0
100
111
702 );
703 }
704  
705  
706 219 ▶sub _finish_stream_state {
Subroutine _finish_stream_state: called CC=6 SCAR=18.1
707 219 my ( $self, $state ) = @_;
708 219 ▶ $state //= $self->_stream_parse_state;
Condition66%2/3
$state //= $self->_stream_parse_state
l!l&&r!l&&!r
206130
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
709 219 ▶ my $order = $state->{openai_tool_order} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $order = $state->{"openai_tool_order"} or return 211 8 219
710 211 ▶ return unless @$order;
Branch: 1 branch
BranchTrueFalseTotal
unless @$order 209 2 211
711 2 ▶ my $pending = $state->{openai_tool_calls} // {};
Condition50%1/2
$state->{"openai_tool_calls"} // {}
l!l
20
MC/DC0%0/1
$state->{"openai_tool_calls"} // {}
$state->{"openai_tool_calls"}
Truth table50%1/2
A
A= $state->{"openai_tool_calls"}
Aresult
11
00
712 2 ▶ my @names = map { $pending->{$_}{function}{name} // '?' } @$order;
Condition50%1/2
$pending->{$_}{"function"}{"name"} // "?"
l!l
20
MC/DC0%0/1
$pending->{$_}{"function"}{"name"} // "?"
$pending->{$_}{"function"}{"name"}
Truth table50%1/2
A
A= $pending->{$_}{"function"}{"name"}
Aresult
11
00
713 2 %$pending = ();
714 2 @$order = ();
715 2 carp "".( ref $self )." stream ended without a finish_reason; dropping "
716 . scalar(@names) . " unfinished tool call(s): " . join( ', ', @names );
717 2 return;
718 }
719  
720  
721 # Tool calling support (MCP) is provided by the tag-driven defaults in
722 # Langertha::Role::Tools (tool_wire_format => 'openai'). No per-engine copies.
723  
724 # Image generation
725  
726 30 ▶sub image_operation_id { 'createImage' }
Subroutine image_operation_id: called CC=1 SCAR=0.0
Pod undocumented
727  
728 30 ▶sub image_request {
Subroutine image_request: called CC=5 SCAR=16.1
Pod documented
729 30 my ( $self, $prompt, %extra ) = @_;
730 # GPT image models always answer b64_json and reject response_format with a
731 # 400 "Unknown parameter" (k308).
732 30 ▶ my $model = exists $extra{model} ? $extra{model} : $self->image_model;
Branch: 1 branch
BranchTrueFalseTotal
exists $extra{'model'} ? : 5 25 30
733 30 ▶ if ( defined $model && $model =~ /\Agpt-image/ && exists $extra{response_format} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $model and $model =~ /\Agpt-image/ and exists $extra{"response_format"}) 2 28 30
Condition83%5/6
defined $model and $model =~ /\Agpt-image/ and exists $extra{"response_format"}
!ll&&!rl&&r
6222
defined $model and $model =~ /\Agpt-image/
!ll&&!rl&&r
0624
MC/DC66%2/3
defined $model and $model =~ /\Agpt-image/ and exists $extra{"response_format"}
defined $model $model =~ /\Agpt-image/ exists $extra{"response_format"}
Truth table75%3/4
A and B and C
A= defined $modelB= $model =~ /\Agpt-image/C= exists $extra{"response_format"}
ABCresult
0XX0
10X0
1100
1111
734 2 delete $extra{response_format};
735 2 carp "".(ref $self)." image_request: $model does not take response_format"
736 . " (it always answers b64_json); dropped";
737 }
738 21 ▶ return $self->generate_request( $self->image_operation_id, sub { $self->image_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
739 30 model => $self->image_model,
740 prompt => $prompt,
741 %extra,
742 );
743 }
744  
745  
746 26 ▶sub image_response {
Subroutine image_response: called CC=4 SCAR=13.9
Pod documented
747 26 my ( $self, $response ) = @_;
748 26 my $data = $self->parse_response($response);
749 # An image call that yields no image is an error, not an empty result (k290).
750 23 ▶ unless ( ref $data eq 'HASH' && ref $data->{data} eq 'ARRAY' && @{$data->{data}} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $data eq "HASH" and ref $data->{"data"} eq "ARRAY" and @{$data->{"data"};}) 4 19 23
Condition83%5/6
ref $data eq "HASH" and ref $data->{"data"} eq "ARRAY" and @{$data->{"data"};}
!ll&&!rl&&r
1319
ref $data eq "HASH" and ref $data->{"data"} eq "ARRAY"
!ll&&!rl&&r
0122
MC/DC66%2/3
ref $data eq "HASH" and ref $data->{"data"} eq "ARRAY" and @{$data->{"data"};}
ref $data eq "HASH" ref $data->{"data"} eq "ARRAY" @{$data->{"data"};}
Truth table75%3/4
A and B and C
A= ref $data eq "HASH"B= ref $data->{"data"} eq "ARRAY"C= @{$data->{"data"};}
ABCresult
0XX0
10X0
1100
1111
751 4 croak "".(ref $self)." image response contained no image"
752 . $self->_payload_error_suffix($data);
753 }
754 19 return $data->{data};
755 }
756  
757  
758 2 ▶sub simple_image {
Subroutine simple_image: called CC=1 SCAR=0.0
Pod documented
759 2 my ( $self, $prompt, %extra ) = @_;
760 2 my $request = $self->image_request($prompt, %extra);
761 2 my $response = $self->user_agent->request($request);
762 2 return $request->response_call->($response);
763 }
764  
765  
766 1080 ▶sub _parse_rate_limit_headers {
Subroutine _parse_rate_limit_headers: called CC=12 SCAR=24.8
767 1080 my ( $self, $http_response ) = @_;
768 1080 require Langertha::RateLimit;
769 1080 require Langertha::Moment;
770 1080 my %raw = Langertha::RateLimit::_collect_headers($http_response);
771 1080 ▶ return undef unless %raw;
Branch: 1 branch
BranchTrueFalseTotal
unless %raw 1019 61 1080
772 61 my $req_reset = $raw{'x-ratelimit-reset-requests'};
773 61 my $tok_reset = $raw{'x-ratelimit-reset-tokens'};
774 # OpenAI-family reset headers are Go time.Duration strings ("6m0s",
775 # "2m59.56s", "250ms") — a duration, so they populate *_reset_after; the
776 # matching *_reset_at is derived lazily against `received`. A value that is
777 # not a Go duration parses to undef and neither half is set (raw keeps it).
778 61 ▶ my $req_after = defined $req_reset ? Langertha::RateLimit::_parse_go_duration($req_reset) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $req_reset ? : 27 34 61
779 61 ▶ my $tok_after = defined $tok_reset ? Langertha::RateLimit::_parse_go_duration($tok_reset) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $tok_reset ? : 5 56 61
780 return Langertha::RateLimit->new(
781 received => Langertha::Moment->now_utc,
782 ( defined $raw{'x-ratelimit-limit-requests'} ? ( requests_limit => $raw{'x-ratelimit-limit-requests'} + 0 ) : () ),
783 ( defined $raw{'x-ratelimit-remaining-requests'} ? ( requests_remaining => $raw{'x-ratelimit-remaining-requests'} + 0 ) : () ),
784 ( defined $req_reset ? ( requests_reset => $req_reset ) : () ),
785 ( defined $req_after ? ( requests_reset_after => $req_after ) : () ),
786 ( defined $raw{'x-ratelimit-limit-tokens'} ? ( tokens_limit => $raw{'x-ratelimit-limit-tokens'} + 0 ) : () ),
787 61 ▶ ( defined $raw{'x-ratelimit-remaining-tokens'} ? ( tokens_remaining => $raw{'x-ratelimit-remaining-tokens'} + 0 ) : () ),
Branch: 8 branches
BranchTrueFalseTotal
defined $raw{'x-ratelimit-limit-requests'} ? : 46 15 61
defined $raw{'x-ratelimit-remaining-requests'} ? : 47 14 61
defined $req_reset ? : 27 34 61
defined $req_after ? : 27 34 61
defined $raw{'x-ratelimit-limit-tokens'} ? : 6 55 61
defined $raw{'x-ratelimit-remaining-tokens'} ? : 6 55 61
defined $tok_reset ? : 5 56 61
defined $tok_after ? : 5 56 61
788 ( defined $tok_reset ? ( tokens_reset => $tok_reset ) : () ),
789 ( defined $tok_after ? ( tokens_reset_after => $tok_after ) : () ),
790 raw => \%raw,
791 );
792 }
793  
794  
795  
796 168 1;
797  
798 __END__
« blib/lib/Langertha/ServerToolCall.pm ↑ Summary blib/lib/Langertha/Role/Langfuse.pm »