blib/lib/Langertha/Knarr/Protocol/OpenAI.pm

filter: Statementstmt 100% 84 / 84 Branchbran 94.4% 17 / 18 Conditioncond 74.2% 26 / 35 MC/DCmcdc 50.0% 9 / 18 Subroutinesub 100% 21 / 21 Podpod 0.0% 0 / 9 totaltotal 84.8% 157 / 185 CC 26 SCAR 13.7
CC
26
Cov
93%
format_stream_close
8.0
format_chat_response
6.0
parse_chat_request
5.4
CRAP 3.9
« blib/lib/Langertha/Knarr/Protocol/Anthropic.pm ↑ Summary blib/lib/Langertha/Knarr/Role/UpstreamHTTP.pm »
1 package Langertha::Knarr::Protocol::OpenAI;
2 # ABSTRACT: OpenAI-compatible wire protocol (chat/completions, models) for Knarr
3  
4 48 our $VERSION = '1.102';
5 48 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 48 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 48 ▶use Time::HiRes qw( time );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 48 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 48 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 48 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 48 with 'Langertha::Knarr::Protocol';
13  
14 has _json => (
15 is => 'ro',
16 114 ▶ default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
17 48 );
18  
19 # Tool arguments become a JSON string inside a chunk that _json encodes to
20 # UTF-8, so they are encoded to characters here, not to bytes.
21 114 ▶has _args_json => ( is => 'ro', default => sub { JSON::MaybeXS->new( canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
22  
23 37 ▶sub protocol_name { 'openai' }
Subroutine protocol_name: called CC=1 SCAR=0.0
Pod undocumented
24  
25 92 ▶sub protocol_routes {
Subroutine protocol_routes: called CC=1 SCAR=0.0
Pod undocumented
26 return [
27 92 { method => 'POST', path => '/v1/chat/completions', action => 'chat' },
28 { method => 'GET', path => '/v1/models', action => 'models' },
29 ];
30 }
31  
32 # Provider manifest (k14): what parse_chat_request below carries to the
33 # engine. The whole OpenAI tool / structured-output / control surface is
34 # forwarded; thinking_budget, prompt_cache (Anthropic cache_control) and
35 # server_tools are not.
36 37 ▶sub manifest_endpoint {
Subroutine manifest_endpoint: called CC=1 SCAR=0.0
Pod undocumented
37 return {
38 37 dialect => 'openai-chat',
39 path => '/v1',
40 capabilities => [qw(
41 chat streaming system_prompt
42 tools_native tools_hermes
43 tool_choice_auto tool_choice_any tool_choice_none tool_choice_named
44 parallel_tool_use
45 response_format_json_object response_format_json_schema
46 reasoning_effort temperature seed response_size prompt_cache_key
47 image_input
48 )],
49 # image_url parts become Langertha::Content::Image objects (k33) that
50 # core writes in any engine's format; an older core without that gets
51 # them as sent, readable by OpenAI-shape engines and Gemini.
52 image_content_formats => Langertha::Knarr::Image::content_formats(qw( openai gemini )),
53 };
54 }
55  
56 264 ▶sub parse_chat_request {
Subroutine parse_chat_request: called CC=5 SCAR=16.8
Pod undocumented
57 264 my ($self, $http_req, $body_ref) = @_;
58 264 ▶ my $data = $self->_json->decode( $$body_ref || '{}' );
Condition50%1/2
$$body_ref || '{}'
l!l
2640
MC/DC0%0/1
$$body_ref || '{}'
$$body_ref
Truth table50%1/2
A
A= $$body_ref
Aresult
11
00
59 # Capture auth headers for passthrough, one pair per line (k60)
60 264 my $fwd = $self->_forward_headers( $http_req, qw( authorization ) );
61 return Langertha::Knarr::Request->new(
62 protocol => 'openai',
63 raw => $data,
64 model => $data->{model},
65 messages => Langertha::Knarr::Image::openai_messages( $data->{messages} || [] ),
66 stream => $data->{stream} ? 1 : 0,
67 temperature => $data->{temperature},
68 max_tokens => $data->{max_tokens},
69 reasoning_effort => $data->{reasoning_effort},
70 seed => $data->{seed},
71 parallel_tool_use => $data->{parallel_tool_calls},
72 prompt_cache_key => $data->{prompt_cache_key},
73 tools => $data->{tools},
74 tool_choice => $data->{tool_choice},
75 response_format => $data->{response_format},
76 264 ▶ session_id => $data->{user} // scalar( $http_req->header('X-Session-Id') ),
Branch: 1 branch
BranchTrueFalseTotal
$data->{'stream'} ? : 111 153 264
Condition50%2/4
$data->{'messages'} || []
l!l
2640
$data->{"user"} // scalar $http_req->header("X-Session-Id")
l!l
0264
MC/DC0%0/1
$data->{'messages'} || []
$data->{'messages'}
MC/DC0%0/1
$data->{"user"} // scalar $http_req->header("X-Session-Id")
$data->{"user"}
Truth table50%1/2
A
A= $data->{'messages'}
Aresult
11
00
Truth table50%1/2
A
A= $data->{"user"}
Aresult
11
00
77 extra => { forward_headers => $fwd },
78 );
79 }
80  
81 # OpenAI's finish_reason is a closed enum; the engine carries the backend's
82 # own value (Anthropic end_turn/max_tokens/tool_use, Gemini STOP/MAX_TOKENS/
83 # SAFETY, Ollama stop/length, ...). Values already in OpenAI vocabulary pass
84 # through; a value with no OpenAI counterpart falls back like an absent one.
85 my %FINISH_REASON = (
86 48 ( map { $_ => $_ } qw( stop length tool_calls content_filter function_call ) ),
87 end_turn => 'stop',
88 stop_sequence => 'stop',
89 max_tokens => 'length',
90 tool_use => 'tool_calls',
91 refusal => 'content_filter',
92 safety => 'content_filter',
93 recitation => 'content_filter',
94 blocklist => 'content_filter',
95 prohibited_content => 'content_filter',
96 spii => 'content_filter',
97 );
98  
99 145 ▶sub _finish_reason {
Subroutine _finish_reason: called CC=4 SCAR=13.9
100 145 my ( $finish_reason, $has_tool_calls ) = @_;
101 145 ▶ return 'tool_calls' if $has_tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
if $has_tool_calls 8 137 145
102 137 ▶ return 'stop' unless defined $finish_reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $finish_reason 96 41 137
103 41 ▶ return $FINISH_REASON{ lc $finish_reason } // 'stop';
Condition100%2/2
$FINISH_REASON{lc $finish_reason} // "stop"
l!l
401
MC/DC100%1/1
$FINISH_REASON{lc $finish_reason} // "stop"
$FINISH_REASON{lc $finish_reason}
Truth table100%2/2
A
A= $FINISH_REASON{lc $finish_reason}
Aresult
11
00
104 }
105  
106 80 ▶sub format_chat_response {
Subroutine format_chat_response: called CC=6 SCAR=17.9
Pod undocumented
107 80 my ($self, $response, $request) = @_;
108 80 my $r = Langertha::Knarr::Response->coerce($response);
109 80 my $message = { role => 'assistant', content => $r->content };
110 80 my $finish = _finish_reason( $r->finish_reason, $r->has_tool_calls );
111 80 ▶ if ( $r->has_tool_calls ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->has_tool_calls) 2 78 80
112 2 $message->{tool_calls} = [ map { $self->_wire_call($_) } @{ $r->tool_calls } ];
113 }
114 80 ▶ my $usage = $r->usage && $r->usage->can('to_openai_format')
Branch: 1 branch
BranchTrueFalseTotal
$r->usage && $r->usage->can('to_openai_format') ? : 9 71 80
Condition66%2/3
$r->usage and $r->usage->can("to_openai_format")
!ll&&!rl&&r
7109
MC/DC50%1/2
$r->usage and $r->usage->can("to_openai_format")
$r->usage $r->usage->can("to_openai_format")
Truth table66%2/3
A and B
A= $r->usageB= $r->usage->can("to_openai_format")
ABresult
0X0
100
111
115 ? $r->usage->to_openai_format
116 : { prompt_tokens => 0, completion_tokens => 0, total_tokens => 0 };
117 80 ▶ my $payload = {
Condition100%5/5
($r->model // $request->model) // "unknown"
l!l
791
$r->model // $request->model
l!l&&r!l&&!r
7451
MC/DC100%2/2
($r->model // $request->model) // "unknown"
$r->model $request->model
Truth table100%3/3
A // B
A= $r->modelB= $request->model
ABresult
1X1
011
000
118 id => 'chatcmpl-' . int( time() * 1000 ),
119 object => 'chat.completion',
120 created => int( time() ),
121 model => $r->model // $request->model // 'unknown',
122 choices => [
123 {
124 index => 0,
125 message => $message,
126 finish_reason => $finish,
127 },
128 ],
129 usage => $usage,
130 };
131 80 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
132 }
133  
134 # The arguments string is built here from the structured arguments, not taken
135 # from core's to_openai: core up to 0.503 returned it as UTF-8 bytes, which
136 # _json then encoded a second time (a non-ASCII value arrived mangled);
137 # later cores return characters. Encoding it ourselves gives one encoding on every core (k24).
138 15 ▶sub _wire_call {
Subroutine _wire_call: called CC=2 SCAR=7.0
139 15 my ($self, $tc, @fallback) = @_;
140 15 my $wire = $tc->to_openai(@fallback);
141 return {
142 %$wire,
143 function => {
144 15 ▶ %{ $wire->{function} },
Condition50%1/2
$tc->arguments // {}
l!l
150
MC/DC0%0/1
$tc->arguments // {}
$tc->arguments
Truth table50%1/2
A
A= $tc->arguments
Aresult
11
00
145 arguments => $self->_args_json->encode( $tc->arguments // {} ),
146 },
147 };
148 }
149  
150 23 ▶sub format_models_response {
Subroutine format_models_response: called CC=2 SCAR=7.0
Pod undocumented
151 23 my ($self, $models) = @_;
152 my @data = map {
153 23 ▶ ref $_ eq 'HASH' ? { object => 'model', %$_ } : { id => "$_", object => 'model' }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 27 0 27
154 } @$models;
155 23 my $payload = { object => 'list', data => \@data };
156 23 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
157 }
158  
159 73 ▶sub format_stream_chunk {
Subroutine format_stream_chunk: called CC=2 SCAR=7.1
Pod undocumented
160 73 my ($self, $delta_text, $request) = @_;
161 73 ▶ my $payload = {
Condition50%1/2
$request->model // "unknown"
l!l
730
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table50%1/2
A
A= $request->model
Aresult
11
00
162 id => 'chatcmpl-stream',
163 object => 'chat.completion.chunk',
164 created => int( time() ),
165 model => $request->model // 'unknown',
166 choices => [ { index => 0, delta => { content => $delta_text }, finish_reason => undef } ],
167 };
168 73 return "data: " . $self->_json->encode($payload) . "\n\n";
169 }
170  
171 # OpenAI streams end with a chunk whose delta is empty and whose
172 # finish_reason is set, before data: [DONE]. The routed stream carries the
173 # backend's tool calls complete, so they go out ahead of it in one chunk:
174 # delta.tool_calls with every call whole, keyed by index (k19). A client that
175 # asked for stream_options.include_usage gets the usage the way OpenAI sends
176 # it: one more chunk after the terminal one, with empty choices. Without the
177 # option OpenAI sends none, and neither does Knarr; without usage from the
178 # backend there is nothing to report, and no zeroed chunk pretends otherwise.
179 65 ▶sub format_stream_close {
Subroutine format_stream_close: called CC=8 SCAR=20.8
Pod undocumented
180 65 my ($self, $request, $finish_reason, $tool_calls, $usage) = @_;
181 65 ▶ my @calls = @{ $tool_calls // [] };
Condition100%2/2
$tool_calls // []
l!l
5510
MC/DC100%1/1
$tool_calls // []
$tool_calls
Truth table100%2/2
A
A= $tool_calls
Aresult
11
00
182 65 my $out = '';
183 65 ▶ if (@calls) {
Branch: 1 branch
BranchTrueFalseTotal
if (@calls) 6 59 65
184 6 my @delta_calls;
185 6 for my $index ( 0 .. $#calls ) {
186 12 my $wire = $self->_wire_call( $calls[$index], fallback_id => 'call_knarr_' . ( $index + 1 ) );
187 push @delta_calls, {
188 index => $index,
189 id => $wire->{id},
190 type => 'function',
191 function => $wire->{function},
192 12 };
193 }
194 6 $out .= $self->_stream_chunk( $request,
195 { index => 0, delta => { tool_calls => \@delta_calls }, finish_reason => undef } );
196 }
197 65 $out .= $self->_stream_chunk( $request,
198 { index => 0, delta => {}, finish_reason => _finish_reason( $finish_reason, scalar @calls ) } );
199 65 ▶ if ( $usage && $usage->can('to_openai_format') && _wants_usage($request) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage and $usage->can("to_openai_format") and _wants_usage($request)) 3 62 65
Condition83%5/6
$usage and $usage->can("to_openai_format") and _wants_usage($request)
!ll&&!rl&&r
5843
$usage and $usage->can("to_openai_format")
!ll&&!rl&&r
5807
MC/DC66%2/3
$usage and $usage->can("to_openai_format") and _wants_usage($request)
$usage $usage->can("to_openai_format") _wants_usage($request)
Truth table75%3/4
A and B and C
A= $usageB= $usage->can("to_openai_format")C= _wants_usage($request)
ABCresult
0XX0
10X0
1100
1111
200 3 ▶ $out .= "data: " . $self->_json->encode({
Condition50%1/2
$request->model // "unknown"
l!l
30
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table50%1/2
A
A= $request->model
Aresult
11
00
201 id => 'chatcmpl-stream',
202 object => 'chat.completion.chunk',
203 created => int( time() ),
204 model => $request->model // 'unknown',
205 choices => [],
206 usage => $usage->to_openai_format,
207 }) . "\n\n";
208 }
209 65 return $out;
210 }
211  
212 7 ▶sub _wants_usage {
Subroutine _wants_usage: called CC=3 SCAR=11.0
213 7 my ($request) = @_;
214 7 my $opts = $request->raw->{stream_options};
215 7 ▶ return ref $opts eq 'HASH' && $opts->{include_usage} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $opts eq 'HASH' && $opts->{'include_usage'} ? : 3 4 7
Condition100%3/3
ref $opts eq "HASH" and $opts->{"include_usage"}
!ll&&!rl&&r
313
MC/DC100%2/2
ref $opts eq "HASH" and $opts->{"include_usage"}
ref $opts eq "HASH" $opts->{"include_usage"}
Truth table100%3/3
A and B
A= ref $opts eq "HASH"B= $opts->{"include_usage"}
ABresult
0X0
100
111
216 }
217  
218 # OpenAI reports a failure inside a stream as a data line carrying an error
219 # object; the SDKs raise it.
220 6 ▶sub format_stream_error {
Subroutine format_stream_error: called CC=1 SCAR=0.0
Pod undocumented
221 6 my ($self, $status, $message) = @_;
222 6 return "data: " . $self->_json->encode({ error => { message => "$message" } }) . "\n\n";
223 }
224  
225 71 ▶sub _stream_chunk {
Subroutine _stream_chunk: called CC=2 SCAR=7.1
226 71 my ($self, $request, $choice) = @_;
227 71 ▶ my $payload = {
Condition50%1/2
$request->model // "unknown"
l!l
710
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table50%1/2
A
A= $request->model
Aresult
11
00
228 id => 'chatcmpl-stream',
229 object => 'chat.completion.chunk',
230 created => int( time() ),
231 model => $request->model // 'unknown',
232 choices => [ $choice ],
233 };
234 71 return "data: " . $self->_json->encode($payload) . "\n\n";
235 }
236  
237 48 __PACKAGE__->meta->make_immutable;
238 48 1;
239  
240 __END__
241  
242 =pod
243  
244 =encoding UTF-8
245  
246 =head1 NAME
247  
248 Langertha::Knarr::Protocol::OpenAI - OpenAI-compatible wire protocol (chat/completions, models) for Knarr
249  
250 =head1 VERSION
251  
252 version 1.102
253  
254 =head1 DESCRIPTION
255  
256 Implements the OpenAI Chat Completions wire format on top of
257 L<Langertha::Knarr::Protocol>. Loaded by default in every
258 L<Langertha::Knarr> instance.
259  
260 =over
261  
262 =item * C<POST /v1/chat/completions> — sync and SSE streaming
263  
264 =item * C<GET /v1/models> — model listing
265  
266 =back
267  
268 Streaming uses the standard SSE chunk format with C<data: [DONE]> as
269 the terminator. A request with C<< stream_options => { include_usage => true } >>
270 gets the backend's token usage in one more chunk before it, with empty
271 C<choices>, as OpenAI sends it. C<tools>, C<tool_choice>, and C<response_format> are
272 extracted into L<Langertha::Knarr::Request> attributes and forwarded to
273 the engine via C<chat_f>. Tool-call responses are serialised into
274 C<message.tool_calls> with C<finish_reason: "tool_calls">.
275  
276 =head1 SUPPORT
277  
278 =head2 Issues
279  
280 Please report bugs and feature requests on GitHub at
281 L<https://github.com/Getty/langertha-knarr/issues>.
282  
283 =head2 IRC
284  
285 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
286  
287 =head1 CONTRIBUTING
288  
289 Contributions are welcome! Please fork the repository and submit a pull request.
290  
291 =head1 AUTHOR
292  
293 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
294  
295 =head1 COPYRIGHT AND LICENSE
296  
297 This software is copyright (c) 2026 by Torsten Raudssus.
298  
299 This is free software; you can redistribute it and/or modify it under
300 the same terms as the Perl 5 programming language system itself.
301  
302 =cut
« blib/lib/Langertha/Knarr/Protocol/Anthropic.pm ↑ Summary blib/lib/Langertha/Knarr/Role/UpstreamHTTP.pm »