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

filter: Statementstmt 60.7% 51 / 84 Branchbran 44.4% 8 / 18 Conditioncond 31.4% 11 / 35 MC/DCmcdc 16.6% 3 / 18 Subroutinesub 61.9% 13 / 21 Podpod 0.0% 0 / 9 totaltotal 46.4% 86 / 185 CC 26 SCAR 28.0
CC
26
Cov
51%
format_stream_close
72.0
_wants_usage
12.0
format_chat_response
6.0
CRAP 16.4
« blib/lib/Langertha/Knarr/Authorizer/Token.pm ↑ Summary blib/lib/Langertha/Knarr/Tracing.pm »
1 package Langertha::Knarr::Protocol::OpenAI;
2 # ABSTRACT: OpenAI-compatible wire protocol (chat/completions, models) for Knarr
3  
4 7 our $VERSION = '1.103';
5 7 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use Time::HiRes qw( time );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 7 with 'Langertha::Knarr::Protocol';
13  
14 has _json => (
15 is => 'ro',
16 14 ▶ default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
17 7 );
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 14 ▶has _args_json => ( is => 'ro', default => sub { JSON::MaybeXS->new( canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
22  
23 0 ▶sub protocol_name { 'openai' }
Subroutine protocol_name: not called CC=1 SCAR=6.9
Pod undocumented
24  
25 0 ▶sub protocol_routes {
Subroutine protocol_routes: not called CC=1 SCAR=6.9
Pod undocumented
26 return [
27 0 { 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 1 ▶sub manifest_endpoint {
Subroutine manifest_endpoint: called CC=1 SCAR=0.0
Pod undocumented
37 return {
38 1 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 13 ▶sub parse_chat_request {
Subroutine parse_chat_request: called CC=5 SCAR=17.8
Pod undocumented
57 13 my ($self, $http_req, $body_ref) = @_;
58 13 ▶ my $data = $self->_json->decode( $$body_ref || '{}' );
Condition50%1/2
$$body_ref || '{}'
l!l
130
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 13 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 13 ▶ session_id => $data->{user} // scalar( $http_req->header('X-Session-Id') ),
Branch: 1 branch
BranchTrueFalseTotal
$data->{'stream'} ? : 0 13 13
Condition50%2/4
$data->{'messages'} || []
l!l
130
$data->{"user"} // scalar $http_req->header("X-Session-Id")
l!l
013
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 7 ( 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 9 ▶sub _finish_reason {
Subroutine _finish_reason: called CC=4 SCAR=16.1
100 9 my ( $finish_reason, $has_tool_calls ) = @_;
101 9 ▶ return 'tool_calls' if $has_tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
if $has_tool_calls 1 8 9
102 8 ▶ return 'stop' unless defined $finish_reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $finish_reason 8 0 8
103 0 ▶ return $FINISH_REASON{ lc $finish_reason } // 'stop';
Condition0%0/2
$FINISH_REASON{lc $finish_reason} // "stop"
l!l
00
MC/DC0%0/1
$FINISH_REASON{lc $finish_reason} // "stop"
$FINISH_REASON{lc $finish_reason}
Truth table0%0/2
A
A= $FINISH_REASON{lc $finish_reason}
Aresult
11
00
104 }
105  
106 9 ▶sub format_chat_response {
Subroutine format_chat_response: called CC=6 SCAR=17.9
Pod undocumented
107 9 my ($self, $response, $request) = @_;
108 9 my $r = Langertha::Knarr::Response->coerce($response);
109 9 my $message = { role => 'assistant', content => $r->content };
110 9 my $finish = _finish_reason( $r->finish_reason, $r->has_tool_calls );
111 9 ▶ if ( $r->has_tool_calls ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->has_tool_calls) 1 8 9
112 1 $message->{tool_calls} = [ map { $self->_wire_call($_) } @{ $r->tool_calls } ];
113 }
114 9 ▶ my $usage = $r->usage && $r->usage->can('to_openai_format')
Branch: 1 branch
BranchTrueFalseTotal
$r->usage && $r->usage->can('to_openai_format') ? : 7 2 9
Condition66%2/3
$r->usage and $r->usage->can("to_openai_format")
!ll&&!rl&&r
207
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 9 ▶ my $payload = {
Condition100%5/5
($r->model // $request->model) // "unknown"
l!l
81
$r->model // $request->model
l!l&&r!l&&!r
621
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 9 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 1 ▶sub _wire_call {
Subroutine _wire_call: called CC=2 SCAR=7.0
139 1 my ($self, $tc, @fallback) = @_;
140 1 my $wire = $tc->to_openai(@fallback);
141 return {
142 %$wire,
143 function => {
144 1 ▶ %{ $wire->{function} },
Condition50%1/2
$tc->arguments // {}
l!l
10
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 0 ▶sub format_models_response {
Subroutine format_models_response: not called CC=2 SCAR=17.9
Pod undocumented
151 0 my ($self, $models) = @_;
152 my @data = map {
153 0 ▶ ref $_ eq 'HASH' ? { object => 'model', %$_ } : { id => "$_", object => 'model' }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 0 0
154 } @$models;
155 0 my $payload = { object => 'list', data => \@data };
156 0 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
157 }
158  
159 0 ▶sub format_stream_chunk {
Subroutine format_stream_chunk: not called CC=2 SCAR=17.9
Pod undocumented
160 0 my ($self, $delta_text, $request) = @_;
161 0 ▶ my $payload = {
Condition0%0/2
$request->model // "unknown"
l!l
00
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table0%0/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 0 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 0 ▶sub format_stream_close {
Subroutine format_stream_close: not called CC=8 SCAR=42.8
Pod undocumented
180 0 my ($self, $request, $finish_reason, $tool_calls, $usage) = @_;
181 0 ▶ my @calls = @{ $tool_calls // [] };
Condition0%0/2
$tool_calls // []
l!l
00
MC/DC0%0/1
$tool_calls // []
$tool_calls
Truth table0%0/2
A
A= $tool_calls
Aresult
11
00
182 0 my $out = '';
183 0 ▶ if (@calls) {
Branch: 1 branch
BranchTrueFalseTotal
if (@calls) 0 0 0
184 0 my @delta_calls;
185 0 for my $index ( 0 .. $#calls ) {
186 0 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 0 };
193 }
194 0 $out .= $self->_stream_chunk( $request,
195 { index => 0, delta => { tool_calls => \@delta_calls }, finish_reason => undef } );
196 }
197 0 $out .= $self->_stream_chunk( $request,
198 { index => 0, delta => {}, finish_reason => _finish_reason( $finish_reason, scalar @calls ) } );
199 0 ▶ 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)) 0 0 0
Condition0%0/6
$usage and $usage->can("to_openai_format") and _wants_usage($request)
!ll&&!rl&&r
000
$usage and $usage->can("to_openai_format")
!ll&&!rl&&r
000
MC/DC0%0/3
$usage and $usage->can("to_openai_format") and _wants_usage($request)
$usage $usage->can("to_openai_format") _wants_usage($request)
Truth table0%0/4
A and B and C
A= $usageB= $usage->can("to_openai_format")C= _wants_usage($request)
ABCresult
0XX0
10X0
1100
1111
200 0 ▶ $out .= "data: " . $self->_json->encode({
Condition0%0/2
$request->model // "unknown"
l!l
00
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table0%0/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 0 return $out;
210 }
211  
212 0 ▶sub _wants_usage {
Subroutine _wants_usage: not called CC=3 SCAR=24.8
213 0 my ($request) = @_;
214 0 my $opts = $request->raw->{stream_options};
215 0 ▶ return ref $opts eq 'HASH' && $opts->{include_usage} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $opts eq 'HASH' && $opts->{'include_usage'} ? : 0 0 0
Condition0%0/3
ref $opts eq "HASH" and $opts->{"include_usage"}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $opts eq "HASH" and $opts->{"include_usage"}
ref $opts eq "HASH" $opts->{"include_usage"}
Truth table0%0/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 0 ▶sub format_stream_error {
Subroutine format_stream_error: not called CC=1 SCAR=6.9
Pod undocumented
221 0 my ($self, $status, $message) = @_;
222 0 return "data: " . $self->_json->encode({ error => { message => "$message" } }) . "\n\n";
223 }
224  
225 0 ▶sub _stream_chunk {
Subroutine _stream_chunk: not called CC=2 SCAR=17.9
226 0 my ($self, $request, $choice) = @_;
227 0 ▶ my $payload = {
Condition0%0/2
$request->model // "unknown"
l!l
00
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table0%0/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 0 return "data: " . $self->_json->encode($payload) . "\n\n";
235 }
236  
237 7 __PACKAGE__->meta->make_immutable;
238 7 1;
239  
240 __END__
« blib/lib/Langertha/Knarr/Authorizer/Token.pm ↑ Summary blib/lib/Langertha/Knarr/Tracing.pm »