Langertha/Role/OpenAICompatible.pm

filter: Statementstmt 80.2% 114 / 142 Branchbran 64.5% 62 / 96 Conditioncond 45.1% 23 / 51 MC/DCmcdc 14.2% 4 / 28 Subroutinesub 73.3% 33 / 45 Podpod 76.6% 23 / 30 totaltotal 66.0% 259 / 392 CC 70 SCAR 25.5
CC
70
Cov
69%
chat_request
54.2
list_models
18.1
chat_response
11.6
CRAP 12.9
« Langertha/Chat.pm ↑ Summary Langertha/Role/Streaming.pm »
1 package Langertha::Role::OpenAICompatible;
2 # ABSTRACT: Role for OpenAI-compatible API format
3 31 our $VERSION = '0.502';
4 31 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 31 ▶use File::ShareDir::ProjectDistDir qw( :all );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 31 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 31 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 31 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 31 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 31 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12  
13 31 has api_key => (
14 is => 'ro',
15 lazy_build => 1,
16 );
17 11 ▶sub _build_api_key { undef }
Subroutine _build_api_key: called CC=1 SCAR=0.0
18  
19  
20 sub update_request {
21 64 ▶ my ( $self, $request ) = @_;
Subroutine update_request: called CC=2 SCAR=6.9
Pod documented
22 64 my $key = $self->api_key;
23 64 ▶ $request->header('Authorization', 'Bearer '.$key) if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 54 10 64
24 }
25  
26  
27 0 ▶sub openapi_file { yaml => dist_file('Langertha','openai.yaml') };
Subroutine openapi_file: not called CC=1 SCAR=6.9
Pod documented
28  
29  
30 0 ▶sub default_embedding_model { 'text-embedding-3-large' }
Subroutine default_embedding_model: not called CC=1 SCAR=6.9
Pod undocumented
31 0 ▶sub default_transcription_model { 'whisper-1' }
Subroutine default_transcription_model: not called CC=1 SCAR=6.9
Pod undocumented
32 2 ▶sub default_image_model { 'gpt-image-1' }
Subroutine default_image_model: called CC=1 SCAR=0.0
Pod undocumented
33  
34 # Dynamic model listing
35  
36 15 ▶sub list_models_path { '/models' }
Subroutine list_models_path: called CC=1 SCAR=0.0
Pod documented
37  
38  
39 sub list_models_request {
40 15 ▶ my ($self, %params) = @_;
Subroutine list_models_request: called CC=2 SCAR=7.2
Pod documented
41 15 my $url = $self->url.$self->list_models_path;
42 15 ▶ if ($params{after}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{"after"}) 0 15 15
43 0 $url .= '?after='.$params{after};
44 }
45 return $self->generate_http_request(
46 GET => $url,
47 4 ▶ sub { $self->list_models_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
48 15 );
49 }
50  
51  
52 sub list_models_response {
53 8 ▶ my ($self, $response) = @_;
Subroutine list_models_response: called CC=1 SCAR=0.0
Pod documented
54 8 my $data = $self->parse_response($response);
55 8 return $data;
56 }
57  
58  
59 sub list_models {
60 6 ▶ my ($self, %opts) = @_;
Subroutine list_models: called CC=14 SCAR=29.0
Pod documented
61  
62 # Guard: if supported_operations excludes listModels, fall back to current model
63 6 ▶ unless ($self->can_operation('listModels')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->can_operation("listModels")) 0 6 6
64 0 return [$self->model];
65 }
66  
67 # Check cache unless force_refresh requested
68 6 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 5 1 6
69 5 my $cache = $self->_models_cache;
70 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
71 2 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 1 1 2
72 }
73 }
74  
75 # Fetch all pages
76 4 my @all_models;
77 my $after;
78 4 for my $page (1..100) {
79 4 ▶ my $request = $self->list_models_request($after ? (after => $after) : ());
Branch: 1 branch
BranchTrueFalseTotal
$after ? : 0 4 4
80 4 my $response = $self->user_agent->request($request);
81 4 my $data = $request->response_call->($response);
82 4 ▶ my $models = ref $data eq 'HASH' ? ($data->{data} // []) : $data;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 4 0 4
Condition50%1/2
$data->{"data"} // []
l!l
40
MC/DC0%0/1
$data->{"data"} // []
$data->{"data"}
Truth table50%1/2
A
A= $data->{"data"}
Aresult
11
00
83 4 push @all_models, @$models;
84 4 ▶ 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"} 4 0 4
Condition33%2/6
ref $data eq "HASH" and $data->{"has_more"} and $data->{"last_id"}
!ll&&!rl&&r
400
ref $data eq "HASH" and $data->{"has_more"}
!ll&&!rl&&r
040
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
85 0 $after = $data->{last_id};
86 }
87  
88 # Extract IDs and update cache
89 4 my @model_ids = map { $_->{id} } @all_models;
90 4 $self->_models_cache({
91 timestamp => time,
92 models => \@all_models,
93 model_ids => \@model_ids,
94 });
95  
96 4 ▶ return $opts{full} ? \@all_models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 4 4
97 }
98  
99  
100 # Embedding
101  
102 1 ▶sub embedding_operation_id { 'createEmbedding' }
Subroutine embedding_operation_id: called CC=1 SCAR=0.0
Pod undocumented
103  
104 sub embedding_request {
105 1 ▶ my ( $self, $input, %extra ) = @_;
Subroutine embedding_request: called CC=2 SCAR=8.1
Pod documented
106 0 ▶ return $self->generate_request( $self->embedding_operation_id, sub { $self->embedding_response(shift) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
107 1 ▶ defined $self->embedding_model ? ( model => $self->embedding_model ) : (),
Branch: 1 branch
BranchTrueFalseTotal
defined $self->embedding_model ? : 1 0 1
108 input => $input,
109 %extra,
110 );
111 }
112  
113  
114 sub embedding_response {
115 0 ▶ my ( $self, $response ) = @_;
Subroutine embedding_response: not called CC=1 SCAR=6.9
Pod documented
116 0 my $data = $self->parse_response($response);
117 # tracing
118 0 my @objects = @{$data->{data}};
119 0 return $objects[0]->{embedding};
120 }
121  
122  
123 # Chat
124  
125 34 ▶sub chat_operation_id { 'createChatCompletion' }
Subroutine chat_operation_id: called CC=1 SCAR=0.0
Pod undocumented
126  
127 sub chat_request {
128 31 ▶ my ( $self, $messages, %extra ) = @_;
Subroutine chat_request: called CC=14 SCAR=39.9
Pod documented
129  
130 # Normalize tool_choice to OpenAI native format (accepts Anthropic-style,
131 # OpenAI-style, and string shorthands).
132 31 ▶ if ( exists $extra{tool_choice} && defined $extra{tool_choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $extra{"tool_choice"} and defined $extra{"tool_choice"}) 0 31 31
Condition33%1/3
exists $extra{"tool_choice"} and defined $extra{"tool_choice"}
!ll&&!rl&&r
3100
MC/DC0%0/2
exists $extra{"tool_choice"} and defined $extra{"tool_choice"}
exists $extra{"tool_choice"} defined $extra{"tool_choice"}
Truth table33%1/3
A and B
A= exists $extra{"tool_choice"}B= defined $extra{"tool_choice"}
ABresult
0X0
100
111
133 0 ▶ if ( my $tc = Langertha::ToolChoice->from_hash( $extra{tool_choice} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tc = "Langertha::ToolChoice"->from_hash($extra{"tool_choice"})) 0 0 0
134 0 $extra{tool_choice} = $tc->to_openai;
135 }
136 }
137  
138 # parallel_tool_use -> OpenAI's parallel_tool_calls (only when tools present)
139 31 ▶ if ( !exists $extra{parallel_tool_calls}
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $extra{"parallel_tool_calls"} and exists $extra{"tools"} and $self->can("has_parallel_tool_use") and $self->has_parallel_tool_use) 0 31 31
Condition33%3/9
not exists $extra{"parallel_tool_calls"} and exists $extra{"tools"} and $self->can("has_parallel_tool_use") and $self->has_parallel_tool_use
!ll&&!rl&&r
3100
not exists $extra{"parallel_tool_calls"} and exists $extra{"tools"} and $self->can("has_parallel_tool_use")
!ll&&!rl&&r
3100
not exists $extra{"parallel_tool_calls"} and exists $extra{"tools"}
!ll&&!rl&&r
0310
MC/DC0%0/4
not exists $extra{"parallel_tool_calls"} and exists $extra{"tools"} and $self->can("has_parallel_tool_use") and $self->has_parallel_tool_use
not exists $extra{"parallel_tool_calls"} exists $extra{"tools"} $self->can("has_parallel_tool_use") $self->has_parallel_tool_use
Truth table20%1/5
not(A) and B and C and D
A= not exists $extra{"parallel_tool_calls"}B= exists $extra{"tools"}C= $self->can("has_parallel_tool_use")D= $self->has_parallel_tool_use
ABCDresult
0XXX0
10XX0
110X0
11100
11111
140 && exists $extra{tools}
141 && $self->can('has_parallel_tool_use') && $self->has_parallel_tool_use ) {
142 0 ▶ $extra{parallel_tool_calls} = $self->parallel_tool_use ? JSON->true : JSON->false;
Branch: 1 branch
BranchTrueFalseTotal
$self->parallel_tool_use ? : 0 0 0
143 }
144  
145 0 ▶ return $self->generate_request( $self->chat_operation_id, sub { $self->chat_response(shift) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
146 31 ▶ defined $self->chat_model ? ( model => $self->chat_model ) : (),
Branch: 4 branches
BranchTrueFalseTotal
defined $self->chat_model ? : 31 0 31
$self->get_response_size ? : 0 31 31
$self->can('has_response_format') && $self->has_response_format ? : 0 31 31
$self->has_temperature ? : 2 29 31
Condition33%1/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
0310
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
147 messages => $messages,
148 $self->get_response_size ? ( max_tokens => $self->get_response_size ) : (),
149 ($self->can('has_response_format') && $self->has_response_format) ? ( response_format => $self->response_format ) : (),
150 $self->has_temperature ? ( temperature => $self->temperature ) : (),
151 stream => JSON->false,
152 %extra,
153 );
154 }
155  
156  
157 sub chat_response {
158 15 ▶ my ( $self, $response ) = @_;
Subroutine chat_response: called CC=10 SCAR=24.5
Pod documented
159 15 my $data = $self->parse_response($response);
160 15 my $choice = $data->{choices}[0];
161 15 ▶ my $msg = $choice->{message} || {};
Condition50%1/2
$choice->{'message'} || {}
l!l
150
MC/DC0%0/1
$choice->{'message'} || {}
$choice->{'message'}
Truth table50%1/2
A
A= $choice->{'message'}
Aresult
11
00
162 15 my @tcs = Langertha::ToolCall->extract($data);
163 return Langertha::Response->new(
164 content => $msg->{content} // '',
165 raw => $data,
166 $data->{id} ? ( id => $data->{id} ) : (),
167 $data->{model} ? ( model => $data->{model} ) : (),
168 defined $choice->{finish_reason} ? ( finish_reason => $choice->{finish_reason} ) : (),
169 $data->{usage} ? ( usage => $data->{usage} ) : (),
170 $data->{created} ? ( created => $data->{created} ) : (),
171 15 ▶ defined $msg->{reasoning_content} ? ( thinking => $msg->{reasoning_content} ) : (),
Branch: 7 branches
BranchTrueFalseTotal
$data->{'id'} ? : 15 0 15
$data->{'model'} ? : 15 0 15
defined $choice->{'finish_reason'} ? : 15 0 15
$data->{'usage'} ? : 11 4 15
$data->{'created'} ? : 2 13 15
defined $msg->{'reasoning_content'} ? : 2 13 15
@tcs ? : 0 15 15
Condition50%1/2
$msg->{"content"} // ""
l!l
150
MC/DC0%0/1
$msg->{"content"} // ""
$msg->{"content"}
Truth table50%1/2
A
A= $msg->{"content"}
Aresult
11
00
172 @tcs ? ( tool_calls => [ @tcs ] ) : (),
173 );
174 }
175  
176  
177 # Transcription
178  
179 1 ▶sub transcription_operation_id { 'createTranscription' }
Subroutine transcription_operation_id: called CC=1 SCAR=0.0
Pod undocumented
180  
181 sub transcription_request {
182 1 ▶ my ( $self, $file, %extra ) = @_;
Subroutine transcription_request: called CC=2 SCAR=8.1
Pod documented
183 0 ▶ return $self->generate_request( $self->transcription_operation_id, sub { $self->transcription_response(shift) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
184 1 ▶ file => [ $file ],
Branch: 1 branch
BranchTrueFalseTotal
$self->transcription_model ? : 1 0 1
185 $self->transcription_model ? ( model => $self->transcription_model ) : (),
186 %extra,
187 );
188 }
189  
190  
191 sub transcription_response {
192 0 ▶ my ( $self, $response ) = @_;
Subroutine transcription_response: not called CC=1 SCAR=6.9
Pod documented
193 0 my $data = $self->parse_response($response);
194 0 return $data->{text};
195 }
196  
197  
198 # Streaming
199  
200 7 ▶sub stream_format { 'sse' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod documented
201  
202  
203 sub chat_stream_request {
204 5 ▶ my ( $self, $messages, %extra ) = @_;
Subroutine chat_stream_request: called CC=6 SCAR=22.6
Pod documented
205 ▶ return $self->generate_request( $self->chat_operation_id, sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
206 5 ▶ defined $self->chat_model ? ( model => $self->chat_model ) : (),
Branch: 4 branches
BranchTrueFalseTotal
defined $self->chat_model ? : 5 0 5
$self->get_response_size ? : 0 5 5
$self->can('has_response_format') && $self->has_response_format ? : 0 5 5
$self->has_temperature ? : 0 5 5
Condition33%1/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
050
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
207 messages => $messages,
208 $self->get_response_size ? ( max_tokens => $self->get_response_size ) : (),
209 ($self->can('has_response_format') && $self->has_response_format) ? ( response_format => $self->response_format ) : (),
210 $self->has_temperature ? ( temperature => $self->temperature ) : (),
211 stream => JSON->true,
212 %extra,
213 );
214 }
215  
216  
217 sub parse_stream_chunk {
218 7 ▶ my ( $self, $data, $event ) = @_;
Subroutine parse_stream_chunk: called CC=8 SCAR=22.1
Pod documented
219  
220 7 ▶ return undef unless $data && $data->{choices};
Branch: 1 branch
BranchTrueFalseTotal
unless $data and $data->{"choices"} 0 7 7
Condition33%1/3
$data and $data->{"choices"}
!ll&&!rl&&r
007
MC/DC0%0/2
$data and $data->{"choices"}
$data $data->{"choices"}
Truth table33%1/3
A and B
A= $dataB= $data->{"choices"}
ABresult
0X0
100
111
221  
222 7 my $choice = $data->{choices}[0];
223 7 ▶ return undef unless $choice;
Branch: 1 branch
BranchTrueFalseTotal
unless $choice 0 7 7
224  
225 7 ▶ my $content = $choice->{delta}{content} // '';
Condition100%2/2
$choice->{"delta"}{"content"} // ""
l!l
52
MC/DC100%1/1
$choice->{"delta"}{"content"} // ""
$choice->{"delta"}{"content"}
Truth table100%2/2
A
A= $choice->{"delta"}{"content"}
Aresult
11
00
226 7 my $finish_reason = $choice->{finish_reason};
227  
228 7 require Langertha::Stream::Chunk;
229 return Langertha::Stream::Chunk->new(
230 content => $content,
231 raw => $data,
232 is_final => defined $finish_reason,
233 defined $finish_reason ? (finish_reason => $finish_reason) : (),
234 $data->{model} ? (model => $data->{model}) : (),
235 7 ▶ $data->{usage} ? (usage => $data->{usage}) : (),
Branch: 3 branches
BranchTrueFalseTotal
defined $finish_reason ? : 2 5 7
$data->{'model'} ? : 0 7 7
$data->{'usage'} ? : 0 7 7
236 );
237 }
238  
239  
240 # Tool calling support (MCP)
241  
242 sub format_tools {
243 2 ▶ my ( $self, $mcp_tools ) = @_;
Subroutine format_tools: called CC=3 SCAR=13.3
Pod documented
244 return [map {
245 2 {
246 type => 'function',
247 function => {
248 name => $_->{name},
249 description => $_->{description},
250 parameters => $_->{input_schema} // $_->{inputSchema} // $_->{parameters},
251 },
252 }
253 3 ▶ } @$mcp_tools];
Condition33%2/6
($_->{"input_schema"} // $_->{"inputSchema"}) // $_->{"parameters"}
l!l&&r!l&&!r
300
$_->{"input_schema"} // $_->{"inputSchema"}
l!l&&r!l&&!r
030
MC/DC0%0/3
($_->{"input_schema"} // $_->{"inputSchema"}) // $_->{"parameters"}
$_->{"input_schema"} $_->{"inputSchema"} $_->{"parameters"}
Truth table25%1/4
A // B // C
A= $_->{"input_schema"}B= $_->{"inputSchema"}C= $_->{"parameters"}
ABCresult
1XX1
01X1
0011
0000
254 }
255  
256  
257 sub response_tool_calls {
258 5 ▶ my ( $self, $data ) = @_;
Subroutine response_tool_calls: called CC=4 SCAR=14.2
Pod documented
259 5 ▶ my $choice = $data->{choices}[0] or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $choice = $data->{"choices"}[0] or return [] 0 5 5
260 5 ▶ my $msg = $choice->{message} or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $msg = $choice->{"message"} or return [] 0 5 5
261 5 ▶ return $msg->{tool_calls} // [];
Condition100%2/2
$msg->{"tool_calls"} // []
l!l
41
MC/DC100%1/1
$msg->{"tool_calls"} // []
$msg->{"tool_calls"}
Truth table100%2/2
A
A= $msg->{"tool_calls"}
Aresult
11
00
262 }
263  
264  
265 sub extract_tool_call {
266 3 ▶ my ( $self, $tc ) = @_;
Subroutine extract_tool_call: called CC=3 SCAR=12.0
Pod documented
267 3 my $args = $tc->{function}{arguments};
268 3 ▶ $args = $self->decode_json_text($args) if $args && !ref $args;
Branch: 1 branch
BranchTrueFalseTotal
if $args and not ref $args 3 0 3
Condition33%1/3
$args and not ref $args
!ll&&!rl&&r
003
MC/DC0%0/2
$args and not ref $args
$args not ref $args
Truth table33%1/3
A and not(B)
A= $argsB= not ref $args
ABresult
0X0
100
111
269 3 return ( $tc->{function}{name}, $args );
270 }
271  
272  
273 sub response_text_content {
274 3 ▶ my ( $self, $data ) = @_;
Subroutine response_text_content: called CC=3 SCAR=11.1
Pod documented
275 3 ▶ my $choice = $data->{choices}[0] or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $choice = $data->{"choices"}[0] or return "" 0 3 3
276 3 ▶ return $choice->{message}{content} // '';
Condition100%2/2
$choice->{"message"}{"content"} // ""
l!l
21
MC/DC100%1/1
$choice->{"message"}{"content"} // ""
$choice->{"message"}{"content"}
Truth table100%2/2
A
A= $choice->{"message"}{"content"}
Aresult
11
00
277 }
278  
279  
280 sub format_tool_results {
281 3 ▶ my ( $self, $data, $results ) = @_;
Subroutine format_tool_results: called CC=1 SCAR=0.0
Pod documented
282 3 my $choice = $data->{choices}[0];
283 return (
284 { role => 'assistant', content => $choice->{message}{content},
285 tool_calls => $choice->{message}{tool_calls} },
286 map {
287 3 my $r = $_;
288 {
289 role => 'tool',
290 tool_call_id => $r->{tool_call}{id},
291 4 content => $self->json->encode($r->{result}{content}),
292 }
293 } @$results
294 );
295 }
296  
297  
298 # Image generation
299  
300 2 ▶sub image_operation_id { 'createImage' }
Subroutine image_operation_id: called CC=1 SCAR=0.0
Pod undocumented
301  
302 sub image_request {
303 2 ▶ my ( $self, $prompt, %extra ) = @_;
Subroutine image_request: called CC=1 SCAR=0.4
Pod documented
304 0 ▶ return $self->generate_request( $self->image_operation_id, sub { $self->image_response(shift) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
305 2 model => $self->image_model,
306 prompt => $prompt,
307 %extra,
308 );
309 }
310  
311  
312 sub image_response {
313 0 ▶ my ( $self, $response ) = @_;
Subroutine image_response: not called CC=1 SCAR=6.9
Pod documented
314 0 my $data = $self->parse_response($response);
315 0 return $data->{data};
316 }
317  
318  
319 sub simple_image {
320 0 ▶ my ( $self, $prompt, %extra ) = @_;
Subroutine simple_image: not called CC=1 SCAR=6.9
Pod documented
321 0 my $request = $self->image_request($prompt, %extra);
322 0 my $response = $self->user_agent->request($request);
323 0 return $request->response_call->($response);
324 }
325  
326  
327 sub _parse_rate_limit_headers {
328 33 ▶ my ( $self, $http_response ) = @_;
Subroutine _parse_rate_limit_headers: called CC=10 SCAR=23.0
329 33 my %raw;
330 33 for my $name (qw(
331 x-ratelimit-limit-requests
332 x-ratelimit-remaining-requests
333 x-ratelimit-reset-requests
334 x-ratelimit-limit-tokens
335 x-ratelimit-remaining-tokens
336 x-ratelimit-reset-tokens
337 )) {
338 198 my $val = $http_response->header($name);
339 198 ▶ $raw{$name} = $val if defined $val;
Branch: 1 branch
BranchTrueFalseTotal
if defined $val 14 184 198
340 }
341 33 ▶ return undef unless %raw;
Branch: 1 branch
BranchTrueFalseTotal
unless %raw 28 5 33
342 5 require Langertha::RateLimit;
343 return Langertha::RateLimit->new(
344 ( defined $raw{'x-ratelimit-limit-requests'} ? ( requests_limit => $raw{'x-ratelimit-limit-requests'} + 0 ) : () ),
345 ( defined $raw{'x-ratelimit-remaining-requests'} ? ( requests_remaining => $raw{'x-ratelimit-remaining-requests'} + 0 ) : () ),
346 ( defined $raw{'x-ratelimit-reset-requests'} ? ( requests_reset => $raw{'x-ratelimit-reset-requests'} ) : () ),
347 ( defined $raw{'x-ratelimit-limit-tokens'} ? ( tokens_limit => $raw{'x-ratelimit-limit-tokens'} + 0 ) : () ),
348 ( defined $raw{'x-ratelimit-remaining-tokens'} ? ( tokens_remaining => $raw{'x-ratelimit-remaining-tokens'} + 0 ) : () ),
349 5 ▶ ( defined $raw{'x-ratelimit-reset-tokens'} ? ( tokens_reset => $raw{'x-ratelimit-reset-tokens'} ) : () ),
Branch: 6 branches
BranchTrueFalseTotal
defined $raw{'x-ratelimit-limit-requests'} ? : 3 2 5
defined $raw{'x-ratelimit-remaining-requests'} ? : 5 0 5
defined $raw{'x-ratelimit-reset-requests'} ? : 1 4 5
defined $raw{'x-ratelimit-limit-tokens'} ? : 2 3 5
defined $raw{'x-ratelimit-remaining-tokens'} ? : 2 3 5
defined $raw{'x-ratelimit-reset-tokens'} ? : 1 4 5
350 raw => \%raw,
351 );
352 }
353  
354  
355  
356 31 1;
357  
358 __END__
359  
360 =pod
361  
362 =encoding UTF-8
363  
364 =head1 NAME
365  
366 Langertha::Role::OpenAICompatible - Role for OpenAI-compatible API format
367  
368 =head1 VERSION
369  
370 version 0.502
371  
372 =head1 SYNOPSIS
373  
374 # This role is not used directly - it's composed by engines
375 # that implement the OpenAI-compatible API format.
376  
377 package My::Engine;
378 use Moose;
379  
380 with map { 'Langertha::Role::'.$_ } qw(
381 JSON HTTP OpenAICompatible OpenAPI Models Temperature
382 ResponseSize SystemPrompt Streaming Chat Tools
383 );
384  
385 sub _build_api_key { $ENV{MY_API_KEY} || die "needs api_key" }
386 sub default_model { 'my-model' }
387  
388 __PACKAGE__->meta->make_immutable;
389  
390 =head1 DESCRIPTION
391  
392 This role provides the OpenAI API format methods for chat completions,
393 embeddings, transcription, streaming, and tool calling. Engines that
394 use the OpenAI-compatible API format (whether OpenAI itself, Ollama's
395 C</v1> endpoint, or other compatible providers) can compose this role
396 instead of inheriting from L<Langertha::Engine::OpenAI>.
397  
398 The role provides default implementations for all OpenAI-format operations.
399 Engines can override individual methods to customize behavior (e.g.,
400 different operation IDs for Mistral, or disabling unsupported features).
401  
402 B<Engines should also compose these roles:>
403  
404 =over 4
405  
406 =item * L<Langertha::Role::JSON> - JSON encoding/decoding
407  
408 =item * L<Langertha::Role::HTTP> - HTTP request handling
409  
410 =item * L<Langertha::Role::OpenAPI> - OpenAPI spec-driven request generation
411  
412 =item * L<Langertha::Role::Models> - Model management
413  
414 =back
415  
416 B<Engines using this role:> L<Langertha::Engine::OpenAI>, L<Langertha::Engine::DeepSeek>,
417 L<Langertha::Engine::Groq>, L<Langertha::Engine::Mistral>, L<Langertha::Engine::vLLM>,
418 L<Langertha::Engine::NousResearch>, L<Langertha::Engine::Perplexity>,
419 L<Langertha::Engine::HuggingFace>, L<Langertha::Engine::OllamaOpenAI>,
420 L<Langertha::Engine::AKIOpenAI>.
421  
422 =head2 api_key
423  
424 Optional API key for Bearer token authentication. Override
425 C<_build_api_key> in engines that require authentication (typically
426 from an environment variable). When C<undef>, no Authorization header
427 is sent.
428  
429 =head2 update_request
430  
431 $role->update_request($http_request);
432  
433 Adds C<Authorization: Bearer {api_key}> header to outgoing requests
434 when an API key is configured. Skipped when C<api_key> is C<undef>
435 (e.g. for local servers like vLLM or llama.cpp).
436  
437 =head2 openapi_file
438  
439 my ($type, $path) = $role->openapi_file;
440  
441 Returns the OpenAI OpenAPI spec file path used for request generation.
442 Override in an engine to use a provider-specific spec (e.g., Mistral).
443  
444 =head2 list_models_path
445  
446 my $path = $engine->list_models_path;
447  
448 Returns the path appended to C<url> for the models endpoint.
449 Default: C</models>. Override in engines whose API spec uses a
450 different path (e.g. Mistral uses C</v1/models> because its base URL
451 does not include C</v1>).
452  
453 =head2 list_models_request
454  
455 my $request = $engine->list_models_request;
456 my $request = $engine->list_models_request(after => $last_id);
457  
458 Generates an HTTP GET request for the models endpoint using
459 C<list_models_path>. Pass C<after> for cursor-based pagination.
460 Returns an HTTP request object.
461  
462 =head2 list_models_response
463  
464 my $data = $engine->list_models_response($http_response);
465  
466 Parses the C</v1/models> response. Returns the full response hashref
467 including C<data>, C<has_more>, and C<last_id> for pagination.
468  
469 =head2 list_models
470  
471 my $model_ids = $engine->list_models;
472 # Returns: ['gpt-4o', 'gpt-4o-mini', ...]
473  
474 my $models = $engine->list_models(full => 1);
475 # Returns: [{id => 'gpt-4o', created => ..., ...}, ...]
476  
477 my $fresh = $engine->list_models(force_refresh => 1);
478  
479 Fetches available models from the C</v1/models> endpoint with caching.
480 Automatically paginates through all pages using cursor-based pagination
481 (C<has_more> / C<after>). By default returns an ArrayRef of model ID
482 strings. Pass C<full =E<gt> 1> for full model objects. Results are cached
483 for C<models_cache_ttl> seconds (default: 3600). Pass C<force_refresh =E<gt> 1>
484 to bypass the cache.
485  
486 =head2 embedding_request
487  
488 my $request = $engine->embedding_request($input, %extra);
489  
490 Generates an OpenAI-format embedding request for the given C<$input>
491 string. Uses C<embedding_model> (default: C<text-embedding-3-large>).
492 Returns an HTTP request object.
493  
494 =head2 embedding_response
495  
496 my $vector = $engine->embedding_response($http_response);
497  
498 Parses an OpenAI-format embedding response. Returns an ArrayRef of
499 floats representing the embedding vector.
500  
501 =head2 chat_request
502  
503 my $request = $engine->chat_request($messages, %extra);
504  
505 Generates an OpenAI-format chat completion request. Includes model,
506 messages, max_tokens, temperature, response_format (if set), and
507 C<stream =E<gt> false>. Returns an HTTP request object.
508  
509 =head2 chat_response
510  
511 my $response = $engine->chat_response($http_response);
512  
513 Parses an OpenAI-format chat completion response. Returns a
514 L<Langertha::Response> object with C<content>, C<model>, C<finish_reason>,
515 C<usage>, C<created>, and C<raw>.
516  
517 =head2 transcription_request
518  
519 my $request = $engine->transcription_request($file_path, %extra);
520  
521 Generates an OpenAI-format transcription request for the given audio file.
522 Uses C<transcription_model> (default: C<whisper-1>). Returns an HTTP
523 request object.
524  
525 =head2 transcription_response
526  
527 my $text = $engine->transcription_response($http_response);
528  
529 Parses an OpenAI-format transcription response. Returns the transcribed
530 text as a string.
531  
532 =head2 stream_format
533  
534 my $format = $engine->stream_format;
535  
536 Returns C<'sse'> (Server-Sent Events), indicating the streaming format
537 used by OpenAI-compatible APIs. Used by L<Langertha::Role::Chat> to
538 select the correct stream parser.
539  
540 =head2 chat_stream_request
541  
542 my $request = $engine->chat_stream_request($messages, %extra);
543  
544 Generates an OpenAI-format streaming chat request (C<stream =E<gt> true>).
545 Returns an HTTP request object for use with streaming execution.
546  
547 =head2 parse_stream_chunk
548  
549 my $chunk = $engine->parse_stream_chunk($data, $event);
550  
551 Parses a single SSE data payload from an OpenAI-format stream. Returns
552 a L<Langertha::Stream::Chunk> with C<content>, C<is_final>, C<finish_reason>,
553 C<model>, and C<usage>, or C<undef> if the chunk has no content.
554  
555 =head2 format_tools
556  
557 my $tools = $engine->format_tools($mcp_tools);
558  
559 Converts an ArrayRef of MCP tool definitions to OpenAI function calling
560 format. Each tool becomes C<{ type =E<gt> 'function', function =E<gt> { name, description, parameters } }>.
561  
562 =head2 response_tool_calls
563  
564 my $tool_calls = $engine->response_tool_calls($raw_data);
565  
566 Extracts the tool call objects from a raw OpenAI-format response hashref.
567 Returns an ArrayRef of tool call objects (may be empty).
568  
569 =head2 extract_tool_call
570  
571 my ($name, $args) = $engine->extract_tool_call($tool_call);
572  
573 Extracts the function name and decoded argument hashref from a single
574 OpenAI tool call object. JSON-decodes the arguments string if needed.
575  
576 =head2 response_text_content
577  
578 my $text = $engine->response_text_content($raw_data);
579  
580 Extracts the assistant message text content from a raw OpenAI-format
581 response hashref. Returns an empty string if no content.
582  
583 =head2 format_tool_results
584  
585 my @messages = $engine->format_tool_results($raw_data, $results);
586  
587 Converts tool execution results into OpenAI-format messages to append
588 to the conversation. Returns a list: first the assistant message (with
589 tool calls), then one C<role =E<gt> 'tool'> message per result.
590  
591 =head2 image_request
592  
593 my $request = $engine->image_request($prompt, %extra);
594  
595 Generates an OpenAI-format image generation request for the given
596 C<$prompt>. Uses C<image_model> (default: C<gpt-image-1>). Accepts
597 optional C<size>, C<quality>, C<n>, C<response_format> via C<%extra>.
598 Returns an HTTP request object.
599  
600 =head2 image_response
601  
602 my $images = $engine->image_response($http_response);
603  
604 Parses an OpenAI-format image generation response. Returns an ArrayRef
605 of image objects, each with C<url> or C<b64_json> and optionally
606 C<revised_prompt>.
607  
608 =head2 simple_image
609  
610 my $images = $engine->simple_image('A cat in space');
611  
612 Sends an image generation request and returns the result. Blocks until
613 the request completes. Returns an ArrayRef of image objects.
614  
615 =head2 _parse_rate_limit_headers
616  
617 Parses C<x-ratelimit-*> headers from the HTTP response into a
618 L<Langertha::RateLimit> object. Covers OpenAI, Groq, Cerebras, OpenRouter,
619 Replicate, and all other OpenAI-compatible engines.
620  
621 =head1 SEE ALSO
622  
623 =over
624  
625 =item * L<Langertha::RateLimit> - Normalized rate limit data
626  
627 =item * L<Langertha::Engine::OpenAI> - OpenAI engine
628  
629 =item * L<Langertha::Engine::DeepSeek> - DeepSeek engine
630  
631 =item * L<Langertha::Engine::Groq> - Groq engine
632  
633 =item * L<Langertha::Engine::Mistral> - Mistral engine
634  
635 =item * L<Langertha::Engine::vLLM> - vLLM inference server
636  
637 =item * L<Langertha::Engine::NousResearch> - Nous Research Hermes engine
638  
639 =item * L<Langertha::Engine::Perplexity> - Perplexity Sonar engine
640  
641 =item * L<Langertha::Engine::OllamaOpenAI> - Ollama OpenAI-compatible engine
642  
643 =item * L<Langertha::Engine::AKIOpenAI> - AKI.IO OpenAI-compatible engine
644  
645 =back
646  
647 =head1 SUPPORT
648  
649 =head2 Issues
650  
651 Please report bugs and feature requests on GitHub at
652 L<https://github.com/Getty/langertha/issues>.
653  
654 =head2 IRC
655  
656 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
657  
658 =head1 CONTRIBUTING
659  
660 Contributions are welcome! Please fork the repository and submit a pull request.
661  
662 =head1 AUTHOR
663  
664 Torsten Raudssus <getty@cpan.org>
665  
666 =head1 COPYRIGHT AND LICENSE
667  
668 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
669  
670 This is free software; you can redistribute it and/or modify it under
671 the same terms as the Perl 5 programming language system itself.
672  
673 =cut
« Langertha/Chat.pm ↑ Summary Langertha/Role/Streaming.pm »