blib/lib/Langertha/Role/OpenAICompatible.pm

filter: Statementstmt 97.9% 283 / 289 Branchbran 87.9% 241 / 274 Conditioncond 76.2% 157 / 206 MC/DCmcdc 55.9% 61 / 109 Subroutinesub 94.5% 52 / 55 Podpod 73.0% 19 / 26 totaltotal 84.7% 813 / 959 CC 220 SCAR 31.2
CC
220
Cov
89%
parse_stream_chunk
65.1
chat_response
26.2
_openai_content_parts
22.5
CRAP 22.7
« blib/lib/Langertha/Role/Langfuse.pm ↑ Summary blib/lib/Langertha/HTTP/Redirect.pm »
1 package Langertha::Role::OpenAICompatible;
2 # ABSTRACT: Role for OpenAI-compatible API format
3 154 our $VERSION = '0.503';
4 154 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 154 ▶use File::ShareDir::ProjectDistDir qw( :all );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 154 ▶use Carp qw( croak carp );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 154 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 154 ▶use MIME::Base64 qw( decode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 154 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 154 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 154 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 154 has api_key => (
15 is => 'ro',
16 lazy_build => 1,
17 );
18 0 ▶sub _build_api_key { undef }
Subroutine _build_api_key: not called CC=1 SCAR=6.9
19  
20  
21 2143 ▶sub update_request {
Subroutine update_request: called CC=2 SCAR=6.9
Pod documented
22 2143 my ( $self, $request ) = @_;
23 2143 my $key = $self->api_key;
24 2143 ▶ $request->header('Authorization', 'Bearer '.$key) if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 2016 127 2143
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 87 ▶sub list_models_path { '/models' }
Subroutine list_models_path: called CC=1 SCAR=0.0
Pod documented
42  
43  
44 61 ▶sub list_models_request {
Subroutine list_models_request: called CC=2 SCAR=7.2
Pod documented
45 61 my ($self, %params) = @_;
46 61 my $url = $self->url.$self->list_models_path;
47 61 ▶ if ($params{after}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{"after"}) 0 61 61
48 0 $url .= '?after='.$params{after};
49 }
50 return $self->generate_http_request(
51 GET => $url,
52 9 ▶ sub { $self->list_models_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
53 61 );
54 }
55  
56  
57 13 ▶sub list_models_response {
Subroutine list_models_response: called CC=1 SCAR=0.0
Pod documented
58 13 my ($self, $response) = @_;
59 13 my $data = $self->parse_response($response);
60 10 return $data;
61 }
62  
63  
64 11 ▶sub list_models {
Subroutine list_models: called CC=14 SCAR=29.0
Pod documented
65 11 my ($self, %opts) = @_;
66  
67 # Guard: if supported_operations excludes listModels, fall back to current model
68 11 ▶ unless ($self->can_operation('listModels')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->can_operation("listModels")) 0 11 11
69 0 return [$self->model];
70 }
71  
72 # Check cache unless force_refresh requested
73 11 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 5 6 11
74 5 my $cache = $self->_models_cache;
75 5 ▶ 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 3 5
Condition66%2/3
$cache->{"timestamp"} and time - $cache->{"timestamp"} < $self->models_cache_ttl
!ll&&!rl&&r
302
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 9 my @all_models;
82 my $after;
83 9 for my $page (1..100) {
84 9 ▶ my $request = $self->list_models_request($after ? (after => $after) : ());
Branch: 1 branch
BranchTrueFalseTotal
$after ? : 0 9 9
85 9 my $response = $self->user_agent->request($request);
86 9 my $data = $request->response_call->($response);
87 6 ▶ my $models = ref $data eq 'HASH' ? ($data->{data} // []) : $data;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 6 0 6
Condition50%1/2
$data->{"data"} // []
l!l
60
MC/DC0%0/1
$data->{"data"} // []
$data->{"data"}
Truth table50%1/2
A
A= $data->{"data"}
Aresult
11
00
88 6 push @all_models, @$models;
89 6 ▶ 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"} 6 0 6
Condition33%2/6
ref $data eq "HASH" and $data->{"has_more"} and $data->{"last_id"}
!ll&&!rl&&r
600
ref $data eq "HASH" and $data->{"has_more"}
!ll&&!rl&&r
060
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 6 my @model_ids = map { $_->{id} } @all_models;
95 6 $self->_models_cache({
96 timestamp => time,
97 models => \@all_models,
98 model_ids => \@model_ids,
99 });
100  
101 6 ▶ return $opts{full} ? \@all_models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 6 6
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 1729 ▶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 306 ▶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 1761 ▶sub _temperature_kwargs {
Subroutine _temperature_kwargs: called CC=17 SCAR=28.5
222 1761 my ( $self, $controls ) = @_;
223 my $temp = exists $controls->{temperature} ? $controls->{temperature}
224 1761 ▶ : $self->can('has_temperature') && $self->has_temperature ? $self->temperature
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'temperature'} ? : 21 1740 1761
$self->can('has_temperature') && $self->has_temperature ? : 86 1654 1740
Condition66%2/3
$self->can("has_temperature") and $self->has_temperature
!ll&&!rl&&r
0165486
MC/DC50%1/2
$self->can("has_temperature") and $self->has_temperature
$self->can("has_temperature") $self->has_temperature
Truth table66%2/3
A and B
A= $self->can("has_temperature")B= $self->has_temperature
ABresult
0X0
100
111
225 : undef;
226 1761 ▶ return () unless defined $temp;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $temp 1654 107 1761
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 107 ▶ : 'temperature=' . $temp . ' model=' . ( $self->can('chat_model') ? $self->chat_model // '' : '' );
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'temperature'} ? : 21 86 107
$self->can('chat_model') ? : 86 0 86
Condition50%1/2
$self->chat_model // ""
l!l
860
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
231 107 ▶ unless ( $self->supports('temperature') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->supports("temperature")) 55 52 107
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 52 ▶ if ( $temp != 1
Branch: 1 branch
BranchTrueFalseTotal
if ($temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)) 24 28 52
Condition100%6/6
$temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)
!ll&&!rl&&r
82024
$temp != 1 and $self->can("_temperature_rejected_by_reasoning")
!ll&&!rl&&r
1744
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 24 ▶ $self->_langertha_carp( "".( ref $self ).": dropping temperature=$temp -- this reasoning model "
Branch: 1 branch
BranchTrueFalseTotal
defined $once ? : 19 5 24
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 24 return ();
248 }
249 28 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 1761 ▶sub _openai_tool_choice_kwarg {
Subroutine _openai_tool_choice_kwarg: called CC=2 SCAR=6.9
260 1761 my ( $self, $extra ) = @_;
261 1761 ▶ my $tc = $self->_gate_tool_choice($extra) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $tc = $self->_gate_tool_choice($extra) or return 25 1736 1761
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 1761 ▶sub _openai_parallel_tool_calls_kwarg {
Subroutine _openai_parallel_tool_calls_kwarg: called CC=1 SCAR=0.0
270 1761 my ( $self, $extra, $controls ) = @_;
271 1761 return $self->_parallel_tool_calls_kwarg( $extra, $controls );
272 }
273  
274 1033 ▶sub chat_request {
Subroutine chat_request: called CC=10 SCAR=23.1
Pod documented
275 1033 my ( $self, $messages, %extra ) = @_;
276  
277 # Canonical per-request controls (chat_f, karr #46) beat the engine
278 # attributes on a per-key basis; the rest of %extra passes straight through.
279 1033 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
558475
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
280  
281 1033 $self->_openai_tool_choice_kwarg(\%extra);
282 1033 $self->_openai_parallel_tool_calls_kwarg(\%extra, $controls);
283  
284 168 ▶ return $self->generate_request( $self->chat_operation_id, sub { $self->chat_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
285 defined $self->chat_model ? ( model => $self->chat_model ) : (),
286 messages => $messages,
287 exists $controls->{max_tokens}
288 ? ( $self->_max_tokens_key => $controls->{max_tokens} )
289 : ( $self->get_response_size ? ( $self->_max_tokens_key => $self->get_response_size ) : () ),
290 exists $controls->{response_format}
291 ? ( response_format => $controls->{response_format} )
292 : ( ($self->can('has_response_format') && $self->has_response_format) ? ( response_format => $self->response_format ) : () ),
293 $self->_temperature_kwargs($controls),
294 1033 ▶ exists $controls->{seed} ? ( seed => $controls->{seed} ) : (),
Branch: 7 branches
BranchTrueFalseTotal
defined $self->chat_model ? : 1033 0 1033
exists $controls->{'max_tokens'} ? : 14 1019 1033
$self->get_response_size ? : 174 845 1019
exists $controls->{'response_format'} ? : 36 997 1033
$self->can('has_response_format') && $self->has_response_format ? : 3 994 997
exists $controls->{'seed'} ? : 2 1031 1033
$self->can('knobs_kwargs_for') ? : 130 849 979
Condition66%2/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
09943
MC/DC50%1/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
295 $self->generation_kwargs_for(%$controls),
296 ( $self->can('knobs_kwargs_for') ? $self->knobs_kwargs_for(%$controls) : () ),
297 stream => JSON->false,
298 %extra,
299 );
300 }
301  
302  
303 # A reply that carries tool calls finishes with 'tool_calls' in the
304 # Chat-Completions convention, but gpt-oss served by vLLM-style stacks (seen
305 # live on AKI.IO, gpt-oss-120b and llama3-chat-8b) answers a non-streaming tool
306 # call with 'stop'. Response.tool_calls is the one tool-call shape (ADR 0003),
307 # so the finish reported alongside it says 'tool_calls' too -- the rule
308 # ResponsesCompatible applies (k171). Only 'stop' is rewritten: 'length' and
309 # the other values carry information ('length' = cut off) and pass through; a
310 # missing finish stays missing. The wire value remains on ->raw.
311 # Shared by chat_response and parse_stream_chunk. -- karr k248, ADR 0018
312 513 ▶sub _openai_finish_reason {
Subroutine _openai_finish_reason: called CC=4 SCAR=13.9
313 513 my ( $self, $finish_reason, $has_tool_calls ) = @_;
314 513 ▶ return 'tool_calls'
Branch: 1 branch
BranchTrueFalseTotal
if $has_tool_calls and defined $finish_reason and $finish_reason eq "stop" 16 497 513
Condition83%5/6
$has_tool_calls and defined $finish_reason and $finish_reason eq "stop"
!ll&&!rl&&r
4455216
$has_tool_calls and defined $finish_reason
!ll&&!rl&&r
445068
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
315 if $has_tool_calls && defined $finish_reason && $finish_reason eq 'stop';
316 497 return $finish_reason;
317 }
318  
319 # message.content / delta.content is a string on most OpenAI-compatible
320 # servers, but Mistral's reasoning models (Magistral, or any model called with
321 # reasoning_effort) send a list of content chunks instead:
322 # [ { type => 'thinking', thinking => [ { type => 'text', text => ... } ] },
323 # { type => 'text', text => ... } ]
324 # and a stream switches from the list to plain strings mid-answer.
325 # Response.content and Stream::Chunk.content are Str, so the list is read here,
326 # in the dialect role (ADR 0018 tier 2): text chunks and bare strings join into
327 # content, the text of thinking chunks (a list of text chunks, or a string)
328 # joins into thinking, and any other chunk type (image_url, reference, ...)
329 # carries no answer text and is skipped. Returns ($content, $thinking);
330 # $thinking is undef when no thinking chunk carried text. -- karr k296
331 2203 ▶sub _openai_content_parts {
Subroutine _openai_content_parts: called CC=20 SCAR=31.2
332 2203 my ( $self, $content ) = @_;
333 2203 ▶ return ( $content // '', undef ) unless ref $content;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content 2191 12 2203
Condition100%2/2
$content // ""
l!l
1889302
MC/DC100%1/1
$content // ""
$content
Truth table100%2/2
A
A= $content
Aresult
11
00
334 12 ▶ return ( '', undef ) unless ref $content eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content eq "ARRAY" 0 12 12
335 12 my ( $text, $thinking ) = ( '', undef );
336 12 for my $part (@$content) {
337 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
338 30 ▶ next unless ref $part eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $part eq "HASH" 1 29 30
339 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
340 29 ▶ if ( $type eq 'text' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'text') { } 10 19 29
elsif ($type eq 'thinking') { } 10 9 19
341 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
342 }
343 elsif ( $type eq 'thinking' ) {
344 10 my $inner = $part->{thinking};
345 my @texts = ref $inner eq 'ARRAY'
346 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
347 : ( !ref $inner ? $inner : undef );
348 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
349 }
350 }
351 12 return ( $text, $thinking );
352 }
353  
354 412 ▶sub chat_response {
Subroutine chat_response: called CC=26 SCAR=32.7
Pod documented
355 412 my ( $self, $response ) = @_;
356 412 my $data = $self->parse_response($response);
357 # A 200 without a choice is no answer: gateways (OpenRouter and other
358 # proxies) put an `error` object into a 200 body, and an empty choices list
359 # parsed to content '' with no finish_reason -- the same as a model that
360 # legitimately said nothing. Croak, naming the engine and the error, like
361 # the k290 embedding/image croaks. -- karr k301
362 403 ▶ 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' ? : 389 14 403
Condition66%2/3
ref $data eq "HASH" and ref $data->{"choices"} eq "ARRAY"
!ll&&!rl&&r
014389
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
363 403 ▶ unless ( ref $choice eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $choice eq "HASH") 21 382 403
364 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
365 21 ▶ croak "".(ref $self)." response carried an error: $error" if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 11 10 21
366 10 croak "".(ref $self)." response contained no choices";
367 }
368 # OpenRouter reports a provider failure inside the choice (its `error`,
369 # finish_reason 'error'); that parsed to an empty success. -- karr k311
370 382 ▶ 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 374 382
371 8 croak "".(ref $self)." response carried an error: $error";
372 }
373 # finish_reason 'error' with no error object anywhere is still a failed
374 # generation, not an answer. -- karr k317
375 croak "".(ref $self)." response ended with finish_reason error"
376 374 ▶ if ( $choice->{finish_reason} // '' ) eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if ($choice->{"finish_reason"} // "") eq "error" 6 368 374
Condition100%2/2
$choice->{"finish_reason"} // ""
l!l
32648
MC/DC100%1/1
$choice->{"finish_reason"} // ""
$choice->{"finish_reason"}
Truth table100%2/2
A
A= $choice->{"finish_reason"}
Aresult
11
00
377 368 ▶ my $msg = $choice->{message} || {};
Condition50%1/2
$choice->{'message'} || {}
l!l
3680
MC/DC0%0/1
$choice->{'message'} || {}
$choice->{'message'}
Truth table50%1/2
A
A= $choice->{'message'}
Aresult
11
00
378 # The OpenAI-compatible response envelope is always OpenAI-shaped, even for
379 # engines whose tool_wire_format is 'hermes' (their calls ride in the message
380 # text, parsed elsewhere).
381 # Pin the structured extractor to 'openai' rather than $self->tool_wire_format.
382 368 my @tcs = Langertha::ToolCall->extract( 'openai', $data );
383 # Chain-of-thought reaches the OpenAI-compatible message under two spellings:
384 # the DeepSeek/SGLang/Moonshot/xAI `reasoning_content`, and the bare
385 # `reasoning` that vLLM (renamed from reasoning_content), Groq, Cerebras,
386 # OpenRouter and AKI.IO send. Read the canonical spelling first, then fall
387 # back to `reasoning` -- guarded !ref so OpenRouter's structured
388 # `reasoning_details` ARRAY (or any non-string shape) never lands in the Str
389 # thinking attribute. The precedence tests `length`, not `defined`: a server
390 # that keeps `reasoning_content` as an empty back-compat stub beside a filled
391 # `reasoning` must not mask it -- the exact failure mode the vLLM migration
392 # note warns about. -- karr k127, k129, k79
393 # A content-chunk list (Mistral reasoning models) carries its own thinking
394 # chunks; they fill thinking only when neither reasoning field did. -- k296
395 368 my ( $content, $part_thinking ) = $self->_openai_content_parts( $msg->{content} );
396 my $thinking =
397 length( $msg->{reasoning_content} // '' ) ? $msg->{reasoning_content}
398 : ( defined $msg->{reasoning} && !ref $msg->{reasoning} ) ? $msg->{reasoning}
399 368 ▶ : $part_thinking;
Branch: 2 branches
BranchTrueFalseTotal
length($msg->{'reasoning_content'} // '') ? : 6 362 368
defined $msg->{'reasoning'} && !ref($msg->{'reasoning'}) ? : 13 349 362
Condition100%5/5
$msg->{"reasoning_content"} // ""
l!l
7361
defined $msg->{"reasoning"} and not ref $msg->{"reasoning"}
!ll&&!rl&&r
348113
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
400 return Langertha::Response->new(
401 content => $content,
402 raw => $data,
403 $data->{id} ? ( id => $data->{id} ) : (),
404 $data->{model} ? ( model => $data->{model} ) : (),
405 defined $choice->{finish_reason}
406 ? ( finish_reason => $self->_openai_finish_reason( $choice->{finish_reason}, scalar @tcs ) ) : (),
407 $data->{usage} ? ( usage => $self->_wire_usage( $data->{usage} ) ) : (),
408 ( $data->{usage} && $data->{usage}{prompt_tokens_details}
409 && defined $data->{usage}{prompt_tokens_details}{cached_tokens}
410 ? ( cached_tokens => $data->{usage}{prompt_tokens_details}{cached_tokens} ) : () ),
411 $data->{created} ? ( created => $data->{created} ) : (),
412 defined $thinking ? ( thinking => $thinking ) : (),
413 # A declined structured-output request answers content null plus
414 # message.refusal; it was reachable only through raw (ADR 0004). -- k301
415 368 ▶ ( defined $msg->{refusal} && !ref $msg->{refusal} ? ( refusal => $msg->{refusal} ) : () ),
Branch: 9 branches
BranchTrueFalseTotal
$data->{'id'} ? : 204 164 368
$data->{'model'} ? : 154 214 368
defined $choice->{'finish_reason'} ? : 320 48 368
$data->{'usage'} ? : 47 321 368
$data->{'usage'} && $data->{'usage'}{'prompt_tokens_details'} && defined $data->{'usage'}{'prompt_tokens_details'}{'cached_tokens'} ? : 24 344 368
$data->{'created'} ? : 54 314 368
defined $thinking ? : 26 342 368
defined $msg->{'refusal'} && !ref($msg->{'refusal'}) ? : 1 367 368
@tcs ? : 58 310 368
Condition77%7/9
$data->{"usage"} and $data->{"usage"}{"prompt_tokens_details"} and defined $data->{"usage"}{"prompt_tokens_details"}{"cached_tokens"}
!ll&&!rl&&r
344024
$data->{"usage"} and $data->{"usage"}{"prompt_tokens_details"}
!ll&&!rl&&r
3212324
defined $msg->{"refusal"} and not ref $msg->{"refusal"}
!ll&&!rl&&r
36701
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
416 @tcs ? ( tool_calls => [ @tcs ] ) : (),
417 );
418 }
419  
420 # The usage block as it goes onto the Response / a stream chunk. The default is
421 # the wire block itself; an engine that knows something the wire does not say
422 # overrides it and returns a copy with a canonical key added (OpenRouter states
423 # that its bare usage.cost is USD as cost_usd; ADR 0018 tier 3, ADR 0031, k363),
424 # as Role::AnthropicCompatible's _wire_usage does for input_includes_cache.
425 # The wire hash itself is never modified.
426 66 ▶sub _wire_usage {
Subroutine _wire_usage: called CC=1 SCAR=0.0
427 66 my ( $self, $usage ) = @_;
428 66 return $usage;
429 }
430  
431  
432 # The error a choice reports, as "message (code)", or undef: the choice's own
433 # `error` (OpenRouter's NonStreamingChoice / StreamingChoice `error`), or a
434 # top-level `error` beside a choice whose finish_reason is 'error' --
435 # OpenRouter's documented mid-stream failure frame. Shapes:
436 # https://openrouter.ai/docs/api-reference/overview and .../errors -- k311
437 2220 ▶sub _openai_choice_error {
Subroutine _openai_choice_error: called CC=5 SCAR=16.3
438 2220 my ( $self, $data, $choice ) = @_;
439 2220 ▶ return $self->_body_error_text( $choice->{error} ) if defined $choice->{error};
Branch: 1 branch
BranchTrueFalseTotal
if defined $choice->{"error"} 8 2212 2220
440 return $self->_body_error_text( $data->{error} )
441 2212 ▶ if defined $data->{error} && ( $choice->{finish_reason} // '' ) eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if defined $data->{"error"} and ($choice->{"finish_reason"} // "") eq "error" 2 2210 2212
Condition60%3/5
defined $data->{"error"} and ($choice->{"finish_reason"} // "") eq "error"
!ll&&!rl&&r
221002
$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
442 2210 return undef;
443 }
444  
445  
446 # Transcription
447  
448 56 ▶sub transcription_operation_id { 'createTranscription' }
Subroutine transcription_operation_id: called CC=1 SCAR=0.0
Pod undocumented
449  
450 62 ▶sub transcription_request {
Subroutine transcription_request: called CC=10 SCAR=23.1
Pod documented
451 62 my ( $self, $file, %extra ) = @_;
452 62 my $filename = delete $extra{filename};
453 # A list goes out as repeated languages[] parts (k286 convention), never as
454 # a file spec. gpt-transcribe takes only that plural field, so a singular
455 # language is folded into it for that model (k313).
456 124 ▶ my @languages = map { ref $_ eq 'ARRAY' ? @$_ : defined $_ ? ($_) : () }
Branch: 2 branches
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 3 121 124
defined $_ ? : 0 121 121
457 62 delete @extra{qw( languages languages[] )};
458 62 ▶ my $model = exists $extra{model} ? $extra{model} : $self->transcription_model;
Branch: 1 branch
BranchTrueFalseTotal
exists $extra{'model'} ? : 4 58 62
459 62 ▶ 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 47 62
Condition83%5/6
defined $model and $model =~ /\Agpt-transcribe/ and defined $extra{"language"}
!ll&&!rl&&r
291815
defined $model and $model =~ /\Agpt-transcribe/
!ll&&!rl&&r
02933
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
460 15 my $language = delete $extra{language};
461 15 ▶ push @languages, $language unless grep { $_ eq $language } @languages;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $language;} @languages 14 1 15
462 }
463 62 ▶ $extra{'languages[]'} = \@languages if @languages;
Branch: 1 branch
BranchTrueFalseTotal
if @languages 17 45 62
464 18 ▶ return $self->generate_request( $self->transcription_operation_id, sub { $self->transcription_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
465 62 ▶ file => $self->transcription_file_part( $file, $filename ),
Branch: 1 branch
BranchTrueFalseTotal
$self->transcription_model ? : 58 3 61
466 $self->transcription_model ? ( model => $self->transcription_model ) : (),
467 %extra,
468 );
469 }
470  
471  
472 52 ▶sub transcription_result {
Subroutine transcription_result: called CC=7 SCAR=19.5
Pod documented
473 52 my ( $self, $response ) = @_;
474 # response_format json / verbose_json answer JSON; text, srt and vtt answer
475 # the transcript as a plain body. Decide by Content-Type, and by the body
476 # only when the type says neither (a transcript can start with "{" but is
477 # then served as text/*). -- karr k288
478 52 ▶ my $type = lc( $response->content_type // '' );
Condition50%1/2
$response->content_type // ""
l!l
520
MC/DC0%0/1
$response->content_type // ""
$response->content_type
Truth table50%1/2
A
A= $response->content_type
Aresult
11
00
479 52 ▶ my $is_json = $type =~ /json/
Condition100%6/6
$type =~ /json/ || !($type =~ m[\Atext/]) && $response->content =~ /\A\s*\{/
l!l&&r!l&&!r
40111
not $type =~ m[\Atext/] and $response->content =~ /\A\s*\{/
!ll&&!rl&&r
1011
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
480 || ( $type !~ m{\Atext/} && $response->content =~ /\A\s*\{/ );
481 52 ▶ return $self->parse_response($response) if $is_json || !$response->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $is_json or not $response->is_success 42 10 52
Condition100%3/3
$is_json or not $response->is_success
l!l&&r!l&&!r
41110
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
482 10 ▶ $self->_update_rate_limit($response) if $self->can('_update_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_update_rate_limit") 10 0 10
483 # Bounded Content-Encoding decode (karr k346): a gzip transcript body inflates
484 # under response_max_bytes or is refused with the too-big croak.
485 10 return { text => $self->_bounded_decoded_content( $response, default_charset => 'UTF-8' ) };
486 }
487  
488  
489 33 ▶sub transcription_response {
Subroutine transcription_response: called CC=1 SCAR=0.0
Pod documented
490 33 my ( $self, $response ) = @_;
491 33 return $self->transcription_result($response)->{text};
492 }
493  
494  
495 # Streaming
496  
497 227 ▶sub stream_format { 'sse' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod documented
498  
499  
500 728 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=10 SCAR=24.5
Pod documented
501 728 my ( $self, $messages, %extra ) = @_;
502  
503 # Same canonical-control consumption as chat_request (karr #46).
504 728 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
460268
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
505  
506 # Same tool_choice normalization and parallel_tool_calls placement as
507 # chat_request (karr k235, k240).
508 728 $self->_openai_tool_choice_kwarg(\%extra);
509 728 $self->_openai_parallel_tool_calls_kwarg(\%extra, $controls);
510  
511 0 ▶ return $self->generate_request( $self->chat_operation_id, sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
512 defined $self->chat_model ? ( model => $self->chat_model ) : (),
513 messages => $messages,
514 exists $controls->{max_tokens}
515 ? ( $self->_max_tokens_key => $controls->{max_tokens} )
516 : ( $self->get_response_size ? ( $self->_max_tokens_key => $self->get_response_size ) : () ),
517 exists $controls->{response_format}
518 ? ( response_format => $controls->{response_format} )
519 : ( ($self->can('has_response_format') && $self->has_response_format) ? ( response_format => $self->response_format ) : () ),
520 $self->_temperature_kwargs($controls),
521 728 ▶ exists $controls->{seed} ? ( seed => $controls->{seed} ) : (),
Branch: 7 branches
BranchTrueFalseTotal
defined $self->chat_model ? : 728 0 728
exists $controls->{'max_tokens'} ? : 0 728 728
$self->get_response_size ? : 122 606 728
exists $controls->{'response_format'} ? : 1 727 728
$self->can('has_response_format') && $self->has_response_format ? : 0 727 727
exists $controls->{'seed'} ? : 0 728 728
$self->can('knobs_kwargs_for') ? : 86 588 674
Condition33%1/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
07270
MC/DC0%0/2
$self->can("has_response_format") and $self->has_response_format
$self->can("has_response_format") $self->has_response_format
Truth table33%1/3
A and B
A= $self->can("has_response_format")B= $self->has_response_format
ABresult
0X0
100
111
522 $self->generation_kwargs_for(%$controls),
523 ( $self->can('knobs_kwargs_for') ? $self->knobs_kwargs_for(%$controls) : () ),
524 stream => JSON->true,
525 %extra,
526 );
527 }
528  
529  
530 1847 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=56 SCAR=41.8
Pod documented
531 1847 my ( $self, $data, $event, $state ) = @_;
532  
533 1847 ▶ return undef unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 1847 1847
534  
535 # A gateway that fails mid-stream (OpenRouter) sends a frame with a
536 # top-level `error` object and no choice. Returning undef ended the stream
537 # as a short, silent success; the croak fails the stream future, as the
538 # Responses parser does for its error events. -- karr k301
539 1847 ▶ 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 1846 1847
Condition83%5/6
defined $data->{"error"} and not ref $data->{"choices"} eq "ARRAY" && @{$data->{"choices"};}
!ll&&!rl&&r
184511
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
540 1 croak "".(ref $self)." stream carried an error: ".$self->_body_error_text( $data->{error} );
541 }
542 # OpenRouter's mid-stream failure frame keeps a choice (delta content '',
543 # finish_reason 'error') beside the error, or puts the error on the choice;
544 # both ended the stream as a silent success. -- karr k311
545 1846 ▶ 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 1844 1846
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
818362
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH"
!ll&&!rl&&r
081838
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
546 && defined( my $error = $self->_openai_choice_error( $data, $data->{choices}[0] ) ) ) {
547 2 croak "".(ref $self)." stream carried an error: $error";
548 }
549 # The same frame without any error object still ends a failed stream. -- k317
550 1844 ▶ 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 1843 1844
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
818351
ref $data->{"choices"} eq "ARRAY" and ref $data->{"choices"}[0] eq "HASH"
!ll&&!rl&&r
081836
$data->{"choices"}[0]{"finish_reason"} // ""
l!l
1991637
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
551 && ( $data->{choices}[0]{finish_reason} // '' ) eq 'error' ) {
552 1 croak "".(ref $self)." stream ended with finish_reason error";
553 }
554  
555 # With stream_options.include_usage (OpenAI; vLLM and SGLang emit it too) the
556 # usage arrives in a frame of its own after the finish chunk, with an empty
557 # choices list. It becomes a content-less, non-final chunk carrying the usage
558 # (and cached_tokens), so aggregate_usage and a caller scanning the chunks
559 # see it; dropping it lost the stream's token counts. -- karr k298
560 1843 ▶ my $choice = ref $data->{choices} eq 'ARRAY' ? $data->{choices}[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{'choices'} eq 'ARRAY' ? : 1843 0 1843
561 1843 ▶ unless ($choice) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($choice) 8 1835 1843
562 8 ▶ return undef unless ref $data->{usage} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data->{"usage"} eq "HASH" 2 6 8
563 6 require Langertha::Stream::Chunk;
564 return Langertha::Stream::Chunk->new(
565 content => '',
566 raw => $data,
567 is_final => 0,
568 $data->{model} ? ( model => $data->{model} ) : (),
569 6 ▶ $self->_openai_stream_usage_kwargs( $data->{usage} ),
Branch: 1 branch
BranchTrueFalseTotal
$data->{'model'} ? : 6 0 6
570 );
571 }
572  
573 # delta.content may be a content-chunk list too (k296, see
574 # _openai_content_parts); its thinking chunks feed the thinking below.
575 my ( $content, $part_thinking ) = $self->_openai_content_parts(
576 1835 ▶ ref $choice->{delta} eq 'HASH' ? $choice->{delta}{content} : undef );
Branch: 1 branch
BranchTrueFalseTotal
ref $choice->{'delta'} eq 'HASH' ? : 1835 0 1835
577 1835 my $finish_reason = $choice->{finish_reason};
578  
579 # A streamed tool call arrives as delta.tool_calls fragments keyed by
580 # `index`: the first carries id, type and function.name, the rest append to
581 # function.arguments, and fragments of parallel calls interleave. Assemble
582 # them per index in this stream's state and deliver the finished calls on the
583 # chunk that carries finish_reason -- read by the same
584 # ToolCall->extract('openai', ...) chat_response uses, so a streamed and a
585 # non-streamed reply of one response yield the same calls. The calls leave the
586 # state as they are delivered, so none arrives twice. A fragment without
587 # `index` (servers that stream whole calls) is keyed by its id, and only by
588 # its position when it has neither; an empty-string finish_reason is no
589 # finish and flushes nothing. A stream that ends without a finish_reason is
590 # reported by _finish_stream_state. -- karr k221
591 1835 ▶ $state //= $self->_stream_parse_state;
Condition66%2/3
$state //= $self->_stream_parse_state
l!l&&r!l&&!r
1795400
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
592 1835 ▶ my $pending = $state->{openai_tool_calls} //= {};
Condition100%2/2
$state->{"openai_tool_calls"} //= {}
l!l
1612223
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
593 1835 ▶ my $order = $state->{openai_tool_order} //= [];
Condition100%2/2
$state->{"openai_tool_order"} //= []
l!l
1612223
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
594 1835 ▶ my $delta_calls = ref $choice->{delta} eq 'HASH' ? $choice->{delta}{tool_calls} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $choice->{'delta'} eq 'HASH' ? : 1835 0 1835
595 1835 ▶ if ( ref $delta_calls eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $delta_calls eq "ARRAY") 42 1793 1835
596 42 for my $pos ( 0 .. $#$delta_calls ) {
597 42 my $fragment = $delta_calls->[$pos];
598 42 ▶ next unless ref $fragment eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fragment eq "HASH" 0 42 42
599 my $key = defined $fragment->{index} ? "index:$fragment->{index}"
600 42 ▶ : length( $fragment->{id} // '' ) ? "id:$fragment->{id}"
Branch: 2 branches
BranchTrueFalseTotal
defined $fragment->{'index'} ? : 40 2 42
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
601 : "pos:$pos";
602 42 ▶ my $call = $pending->{$key} //= do {
Condition66%2/3
$pending->{$key} //= do {
l!l&&r!l&&!r
25170
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
603 17 push @$order, $key;
604 17 { type => 'function', function => { arguments => '' } };
605 };
606 42 ▶ $call->{id} = $fragment->{id} if !length( $call->{id} // '' ) && length( $fragment->{id} // '' );
Branch: 1 branch
BranchTrueFalseTotal
if not length($call->{"id"} // "") and length($fragment->{"id"} // "") 17 25 42
Condition71%5/7
not length($call->{"id"} // "") and length($fragment->{"id"} // "")
!ll&&!rl&&r
25017
$call->{"id"} // ""
l!l
2517
$fragment->{"id"} // ""
l!l
170
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
607 42 ▶ my $fn = ref $fragment->{function} eq 'HASH' ? $fragment->{function} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $fragment->{'function'} eq 'HASH' ? : 42 0 42
608 $call->{function}{name} = $fn->{name}
609 42 ▶ if !length( $call->{function}{name} // '' ) && length( $fn->{name} // '' );
Branch: 1 branch
BranchTrueFalseTotal
if not length($call->{"function"}{"name"} // "") and length($fn->{"name"} // "") 17 25 42
Condition71%5/7
not length($call->{"function"}{"name"} // "") and length($fn->{"name"} // "")
!ll&&!rl&&r
25017
$call->{"function"}{"name"} // ""
l!l
2517
$fn->{"name"} // ""
l!l
170
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
610 42 ▶ if ( ref $fn->{arguments} ) { $call->{function}{arguments} = $fn->{arguments} }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $fn->{'arguments'}) { } 0 42 42
elsif (defined $fn->{'arguments'}) { } 42 0 42
611 42 elsif ( defined $fn->{arguments} ) { $call->{function}{arguments} .= $fn->{arguments} }
612 }
613 }
614 1835 my @tool_calls;
615 1835 ▶ if ( length( $finish_reason // '' ) && @$order ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length($finish_reason // "") and @$order) 12 1823 1835
Condition100%5/5
length($finish_reason // "") and @$order
!ll&&!rl&&r
164218112
$finish_reason // ""
l!l
1981637
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
616 12 my @calls = map { $pending->{$_} } @$order;
617 12 %$pending = ();
618 12 @$order = ();
619 12 @tool_calls = Langertha::ToolCall->extract( 'openai',
620 { choices => [ { message => { tool_calls => \@calls } } ] } );
621 }
622  
623 # Streamed chain-of-thought reaches the delta under the same two spellings the
624 # non-streaming chat_response reads: the DeepSeek/SGLang/Moonshot/xAI
625 # `reasoning_content`, and the bare `reasoning` that vLLM (renamed from
626 # reasoning_content), Cerebras and AKI.IO send. Read the canonical spelling
627 # first, then fall back to `reasoning` -- guarded !ref so a non-string shape
628 # (e.g. OpenRouter's `reasoning_details` ARRAY, which the docs put on the
629 # delta) never lands in the Str thinking attribute. As in chat_response the
630 # precedence tests `length`, not `defined`, so an empty back-compat
631 # `reasoning_content` stub cannot mask a filled `reasoning`. -- karr k129, k79
632 1835 ▶ my $delta = $choice->{delta} || {};
Condition50%1/2
$choice->{'delta'} || {}
l!l
18350
MC/DC0%0/1
$choice->{'delta'} || {}
$choice->{'delta'}
Truth table50%1/2
A
A= $choice->{'delta'}
Aresult
11
00
633 my $thinking =
634 length( $delta->{reasoning_content} // '' ) ? $delta->{reasoning_content}
635 : ( defined $delta->{reasoning} && !ref $delta->{reasoning} ) ? $delta->{reasoning}
636 1835 ▶ : $part_thinking;
Branch: 2 branches
BranchTrueFalseTotal
length($delta->{'reasoning_content'} // '') ? : 12 1823 1835
defined $delta->{'reasoning'} && !ref($delta->{'reasoning'}) ? : 8 1815 1823
Condition100%5/5
$delta->{"reasoning_content"} // ""
l!l
131822
defined $delta->{"reasoning"} and not ref $delta->{"reasoning"}
!ll&&!rl&&r
181418
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
637  
638 # An empty-string finish_reason is no finish here either (as for the tool
639 # call flush above): the chunk is not final and carries no finish_reason,
640 # as Gemini's parser reads an empty finishReason. -- karr k253 review
641 1835 ▶ my $finished = length( $finish_reason // '' );
Condition100%2/2
$finish_reason // ""
l!l
1981637
MC/DC100%1/1
$finish_reason // ""
$finish_reason
Truth table100%2/2
A
A= $finish_reason
Aresult
11
00
642  
643 1835 require Langertha::Stream::Chunk;
644 return Langertha::Stream::Chunk->new(
645 content => $content,
646 raw => $data,
647 is_final => $finished ? 1 : 0,
648 $finished
649 ? (finish_reason => $self->_openai_finish_reason( $finish_reason, scalar @tool_calls )) : (),
650 $data->{model} ? (model => $data->{model}) : (),
651 $self->_openai_stream_usage_kwargs( $data->{usage} ),
652 defined $thinking ? ( thinking => $thinking ) : (),
653 ( defined $delta->{refusal} && !ref $delta->{refusal} && length $delta->{refusal}
654 1835 ▶ ? ( refusal => $delta->{refusal} ) : () ),
Branch: 6 branches
BranchTrueFalseTotal
$finished ? : 193 1642 1835
$finished ? : 193 1642 1835
$data->{'model'} ? : 86 1749 1835
defined $thinking ? : 22 1813 1835
defined $delta->{'refusal'} && !ref($delta->{'refusal'}) && length $delta->{'refusal'} ? : 1 1834 1835
@tool_calls ? : 12 1823 1835
Condition66%4/6
defined $delta->{"refusal"} and not ref $delta->{"refusal"} and length $delta->{"refusal"}
!ll&&!rl&&r
183401
defined $delta->{"refusal"} and not ref $delta->{"refusal"}
!ll&&!rl&&r
183401
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
655 @tool_calls ? ( tool_calls => \@tool_calls ) : (),
656 );
657 }
658  
659 # The usage and cached_tokens constructor arguments of a stream chunk for one
660 # wire usage block (empty when there is none). Shared by the choice and the
661 # usage-only chunk, and by engines that find usage elsewhere (Groq's
662 # x_groq.usage). -- karr k298
663 1854 ▶sub _openai_stream_usage_kwargs {
Subroutine _openai_stream_usage_kwargs: called CC=4 SCAR=13.9
664 1854 my ( $self, $usage ) = @_;
665 1854 ▶ return () unless ref $usage eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 1833 21 1854
666 21 my $details = $usage->{prompt_tokens_details};
667 return (
668 usage => $self->_wire_usage($usage),
669 ( ref $details eq 'HASH' && defined $details->{cached_tokens}
670 21 ▶ ? ( cached_tokens => $details->{cached_tokens} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
ref $details eq 'HASH' && defined $details->{'cached_tokens'} ? : 17 4 21
Condition66%2/3
ref $details eq "HASH" and defined $details->{"cached_tokens"}
!ll&&!rl&&r
4017
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
671 );
672 }
673  
674  
675 203 ▶sub _finish_stream_state {
Subroutine _finish_stream_state: called CC=6 SCAR=18.1
676 203 my ( $self, $state ) = @_;
677 203 ▶ $state //= $self->_stream_parse_state;
Condition66%2/3
$state //= $self->_stream_parse_state
l!l&&r!l&&!r
190130
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
678 203 ▶ my $order = $state->{openai_tool_order} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $order = $state->{"openai_tool_order"} or return 195 8 203
679 195 ▶ return unless @$order;
Branch: 1 branch
BranchTrueFalseTotal
unless @$order 193 2 195
680 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
681 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
682 2 %$pending = ();
683 2 @$order = ();
684 2 carp "".( ref $self )." stream ended without a finish_reason; dropping "
685 . scalar(@names) . " unfinished tool call(s): " . join( ', ', @names );
686 2 return;
687 }
688  
689  
690 # Tool calling support (MCP) is provided by the tag-driven defaults in
691 # Langertha::Role::Tools (tool_wire_format => 'openai'). No per-engine copies.
692  
693 # Image generation
694  
695 30 ▶sub image_operation_id { 'createImage' }
Subroutine image_operation_id: called CC=1 SCAR=0.0
Pod undocumented
696  
697 30 ▶sub image_request {
Subroutine image_request: called CC=5 SCAR=16.1
Pod documented
698 30 my ( $self, $prompt, %extra ) = @_;
699 # GPT image models always answer b64_json and reject response_format with a
700 # 400 "Unknown parameter" (k308).
701 30 ▶ my $model = exists $extra{model} ? $extra{model} : $self->image_model;
Branch: 1 branch
BranchTrueFalseTotal
exists $extra{'model'} ? : 5 25 30
702 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
703 2 delete $extra{response_format};
704 2 carp "".(ref $self)." image_request: $model does not take response_format"
705 . " (it always answers b64_json); dropped";
706 }
707 21 ▶ return $self->generate_request( $self->image_operation_id, sub { $self->image_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
708 30 model => $self->image_model,
709 prompt => $prompt,
710 %extra,
711 );
712 }
713  
714  
715 26 ▶sub image_response {
Subroutine image_response: called CC=4 SCAR=13.9
Pod documented
716 26 my ( $self, $response ) = @_;
717 26 my $data = $self->parse_response($response);
718 # An image call that yields no image is an error, not an empty result (k290).
719 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
720 4 croak "".(ref $self)." image response contained no image"
721 . $self->_payload_error_suffix($data);
722 }
723 19 return $data->{data};
724 }
725  
726  
727 2 ▶sub simple_image {
Subroutine simple_image: called CC=1 SCAR=0.0
Pod documented
728 2 my ( $self, $prompt, %extra ) = @_;
729 2 my $request = $self->image_request($prompt, %extra);
730 2 my $response = $self->user_agent->request($request);
731 2 return $request->response_call->($response);
732 }
733  
734  
735 912 ▶sub _parse_rate_limit_headers {
Subroutine _parse_rate_limit_headers: called CC=12 SCAR=24.8
736 912 my ( $self, $http_response ) = @_;
737 912 require Langertha::RateLimit;
738 912 require Langertha::Moment;
739 912 my %raw = Langertha::RateLimit::_collect_headers($http_response);
740 912 ▶ return undef unless %raw;
Branch: 1 branch
BranchTrueFalseTotal
unless %raw 851 61 912
741 61 my $req_reset = $raw{'x-ratelimit-reset-requests'};
742 61 my $tok_reset = $raw{'x-ratelimit-reset-tokens'};
743 # OpenAI-family reset headers are Go time.Duration strings ("6m0s",
744 # "2m59.56s", "250ms") — a duration, so they populate *_reset_after; the
745 # matching *_reset_at is derived lazily against `received`. A value that is
746 # not a Go duration parses to undef and neither half is set (raw keeps it).
747 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
748 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
749 return Langertha::RateLimit->new(
750 received => Langertha::Moment->now_utc,
751 ( defined $raw{'x-ratelimit-limit-requests'} ? ( requests_limit => $raw{'x-ratelimit-limit-requests'} + 0 ) : () ),
752 ( defined $raw{'x-ratelimit-remaining-requests'} ? ( requests_remaining => $raw{'x-ratelimit-remaining-requests'} + 0 ) : () ),
753 ( defined $req_reset ? ( requests_reset => $req_reset ) : () ),
754 ( defined $req_after ? ( requests_reset_after => $req_after ) : () ),
755 ( defined $raw{'x-ratelimit-limit-tokens'} ? ( tokens_limit => $raw{'x-ratelimit-limit-tokens'} + 0 ) : () ),
756 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
757 ( defined $tok_reset ? ( tokens_reset => $tok_reset ) : () ),
758 ( defined $tok_after ? ( tokens_reset_after => $tok_after ) : () ),
759 raw => \%raw,
760 );
761 }
762  
763  
764  
765 154 1;
766  
767 __END__
768  
769 =pod
770  
771 =encoding UTF-8
772  
773 =head1 NAME
774  
775 Langertha::Role::OpenAICompatible - Role for OpenAI-compatible API format
776  
777 =head1 VERSION
778  
779 version 0.503
780  
781 =head1 SYNOPSIS
782  
783 # This role is not used directly - it's composed by engines
784 # that implement the OpenAI-compatible API format.
785  
786 package My::Engine;
787 use Moose;
788  
789 with map { 'Langertha::Role::'.$_ } qw(
790 JSON HTTP OpenAICompatible OpenAPI Models Temperature
791 ResponseSize SystemPrompt Streaming Chat Tools
792 );
793  
794 sub _build_api_key { $ENV{MY_API_KEY} || die "needs api_key" }
795 sub default_model { 'my-model' }
796  
797 __PACKAGE__->meta->make_immutable;
798  
799 =head1 DESCRIPTION
800  
801 This role provides the OpenAI API format methods for chat completions,
802 embeddings, transcription, streaming, and tool calling. Engines that
803 use the OpenAI-compatible API format (whether OpenAI itself, Ollama's
804 C</v1> endpoint, or other compatible providers) can compose this role
805 instead of inheriting from L<Langertha::Engine::OpenAI>.
806  
807 The role provides default implementations for all OpenAI-format operations.
808 Engines can override individual methods to customize behavior (e.g.,
809 different operation IDs for Mistral, or disabling unsupported features).
810  
811 B<Engines should also compose these roles:>
812  
813 =over 4
814  
815 =item * L<Langertha::Role::JSON> - JSON encoding/decoding
816  
817 =item * L<Langertha::Role::HTTP> - HTTP request handling
818  
819 =item * L<Langertha::Role::OpenAPI> - OpenAPI spec-driven request generation
820  
821 =item * L<Langertha::Role::Models> - Model management
822  
823 =back
824  
825 B<Engines using this role:>
826  
827 =over 4
828  
829 =item * Cloud providers — L<Langertha::Engine::OpenAI>,
830 L<Langertha::Engine::DeepSeek>, L<Langertha::Engine::Groq>,
831 L<Langertha::Engine::Hetzner>, L<Langertha::Engine::MiniMax>,
832 L<Langertha::Engine::Mistral>, L<Langertha::Engine::Moonshot>,
833 L<Langertha::Engine::XAI>, L<Langertha::Engine::Cerebras>,
834 L<Langertha::Engine::NousResearch>, L<Langertha::Engine::OpenRouter>,
835 L<Langertha::Engine::Replicate>, L<Langertha::Engine::HuggingFace>,
836 L<Langertha::Engine::Perplexity>, L<Langertha::Engine::AKIOpenAI>,
837 L<Langertha::Engine::TSystems>, L<Langertha::Engine::Scaleway>
838  
839 =item * Self-hosted — L<Langertha::Engine::OllamaOpenAI>,
840 L<Langertha::Engine::vLLM>, L<Langertha::Engine::SGLang>,
841 L<Langertha::Engine::LlamaCpp>, L<Langertha::Engine::LMStudioOpenAI>
842  
843 =back
844  
845 The base classes L<Langertha::Engine::OpenAIBase> and
846 L<Langertha::Engine::OpenAI> also compose this role (and so every engine
847 that extends them inherits it without listing it explicitly).
848  
849 =head2 api_key
850  
851 Optional API key for Bearer token authentication. Override
852 C<_build_api_key> in engines that require authentication (typically
853 from an environment variable). When C<undef>, no Authorization header
854 is sent.
855  
856 =head2 update_request
857  
858 $role->update_request($http_request);
859  
860 Adds C<Authorization: Bearer {api_key}> header to outgoing requests
861 when an API key is configured. Skipped when C<api_key> is C<undef>
862 (e.g. for local servers like vLLM or llama.cpp).
863  
864 =head2 openapi_file
865  
866 my ($type, $path) = $role->openapi_file;
867  
868 Returns the OpenAI OpenAPI spec file path used for request generation.
869 Override in an engine to use a provider-specific spec (e.g., Mistral).
870  
871 =head2 list_models_path
872  
873 my $path = $engine->list_models_path;
874  
875 Returns the path appended to C<url> for the models endpoint.
876 Default: C</models>. Override in engines whose API spec uses a
877 different path (e.g. Mistral uses C</v1/models> because its base URL
878 does not include C</v1>).
879  
880 =head2 list_models_request
881  
882 my $request = $engine->list_models_request;
883 my $request = $engine->list_models_request(after => $last_id);
884  
885 Generates an HTTP GET request for the models endpoint using
886 C<list_models_path>. Pass C<after> for cursor-based pagination.
887 Returns an HTTP request object.
888  
889 =head2 list_models_response
890  
891 my $data = $engine->list_models_response($http_response);
892  
893 Parses the C</v1/models> response. Returns the full response hashref
894 including C<data>, C<has_more>, and C<last_id> for pagination.
895  
896 =head2 list_models
897  
898 my $model_ids = $engine->list_models;
899 # Returns: ['gpt-4o', 'gpt-4o-mini', ...]
900  
901 my $models = $engine->list_models(full => 1);
902 # Returns: [{id => 'gpt-4o', created => ..., ...}, ...]
903  
904 my $fresh = $engine->list_models(force_refresh => 1);
905  
906 Fetches available models from the C</v1/models> endpoint with caching.
907 Automatically paginates through all pages using cursor-based pagination
908 (C<has_more> / C<after>). By default returns an ArrayRef of model ID
909 strings. Pass C<full =E<gt> 1> for full model objects. Results are cached
910 for C<models_cache_ttl> seconds (default: 3600). Pass C<force_refresh =E<gt> 1>
911 to bypass the cache.
912  
913 =head2 embedding_request
914  
915 my $request = $engine->embedding_request($input, %extra);
916  
917 Generates an OpenAI-format embedding request for C<$input>: a string, or
918 an ArrayRef of strings for a batch (sent as one C<input> array). Uses
919 C<embedding_model> (default: C<text-embedding-3-large>). C<%extra> goes
920 into the body unchanged (C<dimensions>, C<encoding_format>, ...);
921 L<Langertha::Role::Embedding/embedding_dimensions>, when set, is sent under
922 the field the private hook C<_embedding_dimensions_field> names
923 (C<dimensions> by default; L<Langertha::Engine::Mistral> overrides it with
924 C<output_dimension>), unless C<%extra> carries C<dimensions> or that field.
925 An engine whose hook returns C<undef> documents no such field for its
926 C<embedding_model>: the attribute is then not sent and carps once per engine
927 instance, while an explicit C<dimensions> extra still goes out untouched. The
928 request's response parser knows the input shape, so a batch comes back as
929 one vector per input (see L</embedding_response>). Returns an HTTP request
930 object.
931  
932 =head2 embedding_response
933  
934 my $vector = $engine->embedding_response($http_response);
935 my $vectors = $engine->embedding_response($http_response, \@inputs);
936  
937 Parses an OpenAI-format embedding response. The second argument is the
938 request's input; the parser built by L</embedding_request> passes it itself.
939 For a string input (or none) it returns the vector of the first input
940 (C<data[].index> 0) as an ArrayRef of floats. For an ArrayRef input it
941 returns an ArrayRef with one vector per input, in input order (sorted by
942 C<data[].index>), and croaks when the number of vectors does not match the
943 number of inputs. A response without a vector (no C<data> array, an empty
944 one, or an entry without an C<embedding>) croaks too, naming the engine and
945 any C<error> in the body; it never returns C<undef>.
946  
947 A response requested with C<< encoding_format => 'base64' >> is decoded
948 (little-endian float32), so the result is floats either way; there is no
949 option to get the base64 string back. Parse the L<HTTP::Response> yourself
950 when you need the raw form.
951  
952 =head2 chat_request
953  
954 my $request = $engine->chat_request($messages, %extra);
955  
956 Generates an OpenAI-format chat completion request. Includes model,
957 messages, max_tokens, temperature, response_format (if set), and
958 C<stream =E<gt> false>. Returns an HTTP request object.
959  
960 =head2 _wire_usage
961  
962 Internal hook. Returns the usage block that goes onto the
963 L<Langertha::Response> of L</chat_response> and onto a stream chunk. The
964 default returns the wire block unchanged. An engine that knows what the wire
965 does not say overrides it and returns a copy with a canonical key added, which
966 L<Langertha::Usage/from_hash> reads on both paths:
967 L<Langertha::Engine::OpenRouter> adds C<cost_usd> from its bare C<usage.cost>.
968  
969 =head2 chat_response
970  
971 my $response = $engine->chat_response($http_response);
972  
973 Parses an OpenAI-format chat completion response. Returns a
974 L<Langertha::Response> object with C<content>, C<model>, C<finish_reason>,
975 C<usage>, C<created>, and C<raw>.
976  
977 C<finish_reason> is the wire value, with one normalization: a reply that
978 carries tool calls but says C<stop> (gpt-oss on vLLM-style servers, e.g.
979 AKI.IO) reports C<tool_calls>, so it agrees with C<tool_calls>. Every other
980 value, C<length> included, passes through; the wire value stays readable in
981 C<raw>.
982  
983 C<message.content> may be a list of content chunks instead of a string, as
984 Mistral's reasoning models send it: the text of C<text> chunks becomes
985 C<content>, the text inside C<thinking> chunks becomes C<thinking> (unless
986 C<reasoning_content> / C<reasoning> already filled it), and other chunk types
987 are skipped.
988  
989 C<message.refusal> (a declined structured-output request, C<content> then
990 null) becomes L<Langertha::Response/refusal>.
991  
992 A body without a choice is not an answer and croaks, naming the engine: with
993 an C<error> object (gateways such as OpenRouter return one in a 200 body)
994 C<"E<lt>engineE<gt> response carried an error: E<lt>messageE<gt> (E<lt>codeE<gt>)">,
995 otherwise C<"E<lt>engineE<gt> response contained no choices">. A choice
996 carrying an C<error> object, or a top-level C<error> beside a choice whose
997 C<finish_reason> is C<error> (OpenRouter reports a provider failure this
998 way), croaks the same C<response carried an error>; a C<finish_reason> of
999 C<error> with no error object anywhere croaks
1000 C<"E<lt>engineE<gt> response ended with finish_reason error">. Only
1001 C<choices[0]> is read.
1002  
1003 =head2 transcription_request
1004  
1005 my $request = $engine->transcription_request($audio, %extra);
1006  
1007 Generates an OpenAI-format transcription request for the given audio (a path,
1008 C<\$bytes> or a filehandle; C<filename> in C<%extra> names the upload, see
1009 L<Langertha::Role::Transcription/transcription_file_part>).
1010 Uses C<transcription_model> (default: C<whisper-1>; C<gpt-transcribe> on
1011 L<Langertha::Engine::OpenAI>). Returns an HTTP request object.
1012  
1013 C<< languages => [ 'de', 'en' ] >> is sent as repeated C<languages[]> fields.
1014 C<gpt-transcribe> takes only that plural field, so for a C<gpt-transcribe*>
1015 model a C<language> you pass is sent as C<languages[]> too (merged into
1016 C<languages> if both are given); other models get C<language> as given.
1017  
1018 C<gpt-transcribe> (and the older C<gpt-4o-transcribe> /
1019 C<gpt-4o-mini-transcribe>) answer only C<< response_format => 'json' >>, which
1020 is what the API sends when no C<response_format> is given; Langertha never
1021 defaults one. C<verbose_json>, C<srt>, C<vtt> and
1022 C<timestamp_granularities[]> need a model that supports them, such as
1023 C<whisper-1> on OpenAI or a Whisper server; a C<response_format> you pass is
1024 sent as given.
1025  
1026 =head2 transcription_result
1027  
1028 my $result = $engine->transcription_result($http_response);
1029 say $result->{text};
1030 for my $segment ( @{ $result->{segments} // [] } ) { ... }
1031  
1032 Parses a transcription response into a HashRef. A JSON answer
1033 (C<response_format> C<json> or C<verbose_json>) is returned as decoded, so
1034 C<segments>, C<words>, C<language>, C<duration> and C<usage> stay reachable. A
1035 plain-text answer (C<text>, C<srt>, C<vtt>) becomes C<< { text => $body } >>,
1036 decoded as UTF-8 unless the response names another charset. Croaks like
1037 L<Langertha::Role::HTTP/parse_response> on an HTTP error.
1038  
1039 =head2 transcription_response
1040  
1041 my $text = $engine->transcription_response($http_response);
1042  
1043 Parses an OpenAI-format transcription response and returns the transcript as
1044 a string, for every C<response_format>: the C<text> field of a C<json> or
1045 C<verbose_json> answer, the body of a C<text>, C<srt> or C<vtt> answer (the
1046 subtitle markup included). Use L</transcription_result> to keep segments and
1047 word timestamps.
1048  
1049 =head2 stream_format
1050  
1051 my $format = $engine->stream_format;
1052  
1053 Returns C<'sse'> (Server-Sent Events), indicating the streaming format
1054 used by OpenAI-compatible APIs. Used by L<Langertha::Role::Chat> to
1055 select the correct stream parser.
1056  
1057 =head2 chat_stream_request
1058  
1059 my $request = $engine->chat_stream_request($messages, %extra);
1060  
1061 Generates an OpenAI-format streaming chat request (C<stream =E<gt> true>).
1062 Returns an HTTP request object for use with streaming execution.
1063  
1064 =head2 parse_stream_chunk
1065  
1066 my $chunk = $engine->parse_stream_chunk($data, $event, \%state);
1067  
1068 Parses a single SSE data payload from an OpenAI-format stream. Returns
1069 a L<Langertha::Stream::Chunk> with C<content>, C<is_final>, C<finish_reason>,
1070 C<model>, C<usage>, C<cached_tokens> (lifted from
1071 C<usage.prompt_tokens_details.cached_tokens> when present), and C<thinking>
1072 (the streamed C<delta.reasoning_content> / bare C<delta.reasoning>, guarded
1073 C<!ref>). A C<delta.content> that is a list of content chunks is read as in
1074 L</chat_response>: C<text> chunks into C<content>, C<thinking> chunks into
1075 C<thinking>. The usage-only frame that C<stream_options =E<gt> { include_usage
1076 =E<gt> 1 }> adds after the finish chunk (an empty C<choices> list) becomes a
1077 content-less chunk that is not C<is_final> and carries C<usage> and
1078 C<cached_tokens>; collect the stream's usage with
1079 L<Langertha::Role::Chat/aggregate_usage>. Returns C<undef> only when the
1080 payload carries neither a choice nor a usage block. A frame with a top-level
1081 C<error> object and no choice (a gateway failing mid-stream) croaks
1082 C<"E<lt>engineE<gt> stream carried an error: E<lt>messageE<gt> (E<lt>codeE<gt>)">,
1083 which fails the stream; so does a choice carrying an C<error> object, or a
1084 top-level C<error> beside a choice with C<finish_reason> C<error>
1085 (OpenRouter's mid-stream failure frame). A choice with C<finish_reason>
1086 C<error> and no error object anywhere croaks
1087 C<"E<lt>engineE<gt> stream ended with finish_reason error">. A C<delta.refusal> fragment lands on the chunk's
1088 C<refusal>.
1089  
1090 C<delta.tool_calls> fragments are assembled per C<index> (a fragment without
1091 C<index> by its C<id>, and by its position only when it has neither) in
1092 C<\%state>, and the finished calls land as L<Langertha::ToolCall> objects, in
1093 stream order, on the chunk that carries a non-empty C<finish_reason>, read by the
1094 same L<Langertha::ToolCall/extract> as L</chat_response>. Collect them with
1095 L<Langertha::Role::Chat/aggregate_tool_calls>. C<finish_reason> is read as on
1096 the non-streaming path: the wire value, except that C<stop> on the chunk that
1097 delivers tool calls reports C<tool_calls> (the wire value stays in C<raw>). A stream that
1098 ends without one drops its pending calls with a C<carp> (see
1099 L</_finish_stream_state>).
1100  
1101 C<\%state> is one HashRef per stream. The stream paths pass it;
1102 C<$event> is only set by L<Langertha::Role::Streaming/process_stream_data>, the
1103 C<chat_stream_realtime_f> path passes C<undef>. A direct caller may omit
1104 C<\%state> and share the engine's fallback, which is closed when a
1105 C<_process_stream_buffer> flush with C<$final> set ends the stream; a caller
1106 feeding events to C<parse_stream_chunk> one by one should pass its own state.
1107  
1108 =head2 _finish_stream_state
1109  
1110 $engine->_finish_stream_state(\%state);
1111  
1112 Internal: called once when a stream ends (by
1113 L<Langertha::Role::Streaming/process_stream_data> and
1114 L<Langertha::Role::Chat/chat_stream_realtime_f>, and by a final
1115 C<_process_stream_buffer> flush that was given no state). Tool calls still
1116 pending because no chunk carried a C<finish_reason> -- a truncated stream -- are
1117 dropped with one C<carp> naming them, not flushed: their C<arguments> may be
1118 cut off, and a partial JSON string would decode to C<{}>. Clearing them also
1119 keeps them out of the next stream that shares the same state.
1120  
1121 =head2 image_request
1122  
1123 my $request = $engine->image_request($prompt, %extra);
1124  
1125 Generates an OpenAI-format image generation request for the given
1126 C<$prompt>. Uses C<image_model> (default: C<gpt-image-2>). Accepts
1127 optional C<model>, C<size>, C<quality> and C<n> via C<%extra>, passed
1128 through as given. Returns an HTTP request object.
1129  
1130 GPT image models (C<gpt-image-*>) always return the image as C<b64_json> and
1131 reject C<response_format>, so a C<response_format> in C<%extra> is dropped
1132 with a warning for them.
1133  
1134 =head2 image_response
1135  
1136 my $images = $engine->image_response($http_response);
1137  
1138 Parses an OpenAI-format image generation response. Returns an ArrayRef
1139 of image objects, each with C<url> or C<b64_json> (GPT image models answer
1140 C<b64_json> only) and optionally C<revised_prompt>. Croaks, naming the engine and any C<error> in the
1141 body, when the response carries no image.
1142  
1143 =head2 simple_image
1144  
1145 my $images = $engine->simple_image('A cat in space');
1146  
1147 Sends an image generation request and returns the result. Blocks until
1148 the request completes. Returns an ArrayRef of image objects.
1149  
1150 =head2 _parse_rate_limit_headers
1151  
1152 Parses C<x-ratelimit-*> headers from the HTTP response into a
1153 L<Langertha::RateLimit> object. Covers OpenAI, Groq, Cerebras, OpenRouter,
1154 Replicate, and all other OpenAI-compatible engines. Collects the full C<raw>
1155 superset via L<Langertha::RateLimit/_collect_headers>, then normalizes the
1156 Go C<time.Duration> reset strings into L<Langertha::RateLimit/requests_reset_after>
1157 / L<Langertha::RateLimit/tokens_reset_after> (seconds); the C<*_reset_at>
1158 instants are derived lazily against L<Langertha::RateLimit/received>.
1159  
1160 =head1 SEE ALSO
1161  
1162 =over
1163  
1164 =item * L<Langertha::RateLimit> - Normalized rate limit data
1165  
1166 =item * L<Langertha::Engine::OpenAI> - OpenAI engine
1167  
1168 =item * L<Langertha::Engine::DeepSeek> - DeepSeek engine
1169  
1170 =item * L<Langertha::Engine::Groq> - Groq engine
1171  
1172 =item * L<Langertha::Engine::Mistral> - Mistral engine
1173  
1174 =item * L<Langertha::Engine::vLLM> - vLLM inference server
1175  
1176 =item * L<Langertha::Engine::NousResearch> - Nous Research Hermes engine
1177  
1178 =item * L<Langertha::Engine::Perplexity> - Perplexity Sonar engine
1179  
1180 =item * L<Langertha::Engine::OllamaOpenAI> - Ollama OpenAI-compatible engine
1181  
1182 =item * L<Langertha::Engine::AKIOpenAI> - AKI.IO OpenAI-compatible engine
1183  
1184 =back
1185  
1186 =head1 SUPPORT
1187  
1188 =head2 Issues
1189  
1190 Please report bugs and feature requests on GitHub at
1191 L<https://github.com/Getty/langertha/issues>.
1192  
1193 =head2 IRC
1194  
1195 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
1196  
1197 =head1 CONTRIBUTING
1198  
1199 Contributions are welcome! Please fork the repository and submit a pull request.
1200  
1201 =head1 AUTHOR
1202  
1203 Torsten Raudssus <getty@cpan.org>
1204  
1205 =head1 COPYRIGHT AND LICENSE
1206  
1207 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
1208  
1209 This is free software; you can redistribute it and/or modify it under
1210 the same terms as the Perl 5 programming language system itself.
1211  
1212 =cut
« blib/lib/Langertha/Role/Langfuse.pm ↑ Summary blib/lib/Langertha/HTTP/Redirect.pm »