Knarr/Protocol/OpenAI.pm

filter: Statementstmt 100% 50 / 50 Branchbran 90.0% 9 / 10 Conditioncond 66.6% 14 / 21 MC/DCmcdc 36.3% 4 / 11 Subroutinesub 100% 12 / 12 Podpod 0.0% 0 / 6 totaltotal 80.9% 89 / 110 CC 16 SCAR 16.0
CC
16
Cov
90%
parse_chat_request
8.5
format_chat_response
7.0
format_stream_chunk
2.0
CRAP 4.9
« Knarr/Handler/ACPClient.pm ↑ Summary Knarr/Protocol/Ollama.pm »
1 package Langertha::Knarr::Protocol::OpenAI;
2 # ABSTRACT: OpenAI-compatible wire protocol (chat/completions, models) for Knarr
3  
4 13 our $VERSION = '1.100';
5 13 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 13 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 13 ▶use Time::HiRes qw( time );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 13 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 13 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 13 with 'Langertha::Knarr::Protocol';
12  
13 has _json => (
14 is => 'ro',
15 19 ▶ default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
16 13 );
17  
18 1 ▶sub protocol_name { 'openai' }
Subroutine protocol_name: called CC=1 SCAR=0.0
Pod undocumented
19  
20 sub protocol_routes {
21 return [
22 15 ▶ { method => 'POST', path => '/v1/chat/completions', action => 'chat' },
Subroutine protocol_routes: called CC=1 SCAR=0.0
Pod undocumented
23 { method => 'GET', path => '/v1/models', action => 'models' },
24 ];
25 }
26  
27 sub parse_chat_request {
28 23 ▶ my ($self, $http_req, $body_ref) = @_;
Subroutine parse_chat_request: called CC=8 SCAR=21.4
Pod undocumented
29 23 ▶ my $data = $self->_json->decode( $$body_ref || '{}' );
Condition50%1/2
$$body_ref || '{}'
l!l
230
MC/DC0%0/1
$$body_ref || '{}'
$$body_ref
Truth table50%1/2
A
A= $$body_ref
Aresult
11
00
30 # Capture auth headers for passthrough
31 23 my %fwd;
32 23 for my $h (qw( authorization )) {
33 23 my $v = scalar $http_req->header($h);
34 23 ▶ $fwd{$h} = $v if defined $v && length $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and length $v 1 22 23
Condition66%2/3
defined $v and length $v
!ll&&!rl&&r
2201
MC/DC50%1/2
defined $v and length $v
defined $v length $v
Truth table66%2/3
A and B
A= defined $vB= length $v
ABresult
0X0
100
111
35 }
36 return Langertha::Knarr::Request->new(
37 protocol => 'openai',
38 raw => $data,
39 model => $data->{model},
40 messages => $data->{messages} || [],
41 stream => $data->{stream} ? 1 : 0,
42 temperature => $data->{temperature},
43 max_tokens => $data->{max_tokens},
44 tools => $data->{tools},
45 tool_choice => $data->{tool_choice},
46 response_format => $data->{response_format},
47 23 ▶ session_id => $data->{user} // scalar( $http_req->header('X-Session-Id') ),
Branch: 1 branch
BranchTrueFalseTotal
$data->{'stream'} ? : 7 16 23
Condition50%2/4
$data->{'messages'} || []
l!l
230
$data->{"user"} // scalar $http_req->header("X-Session-Id")
l!l
023
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
48 extra => { forward_headers => \%fwd },
49 );
50 }
51  
52 sub format_chat_response {
53 18 ▶ my ($self, $response, $request) = @_;
Subroutine format_chat_response: called CC=7 SCAR=19.5
Pod undocumented
54 18 my $r = Langertha::Knarr::Response->coerce($response);
55 18 my $message = { role => 'assistant', content => $r->content };
56 18 ▶ my $finish = $r->finish_reason // 'stop';
Condition100%2/2
$r->finish_reason // "stop"
l!l
117
MC/DC100%1/1
$r->finish_reason // "stop"
$r->finish_reason
Truth table100%2/2
A
A= $r->finish_reason
Aresult
11
00
57 18 ▶ if ( $r->has_tool_calls ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->has_tool_calls) 1 17 18
58 1 $message->{tool_calls} = [ map { $_->to_openai } @{ $r->tool_calls } ];
59 1 $finish = 'tool_calls';
60 }
61 18 ▶ my $usage = $r->usage && $r->usage->can('to_openai_format')
Branch: 1 branch
BranchTrueFalseTotal
$r->usage && $r->usage->can('to_openai_format') ? : 1 17 18
Condition66%2/3
$r->usage and $r->usage->can("to_openai_format")
!ll&&!rl&&r
1701
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
62 ? $r->usage->to_openai_format
63 : { prompt_tokens => 0, completion_tokens => 0, total_tokens => 0 };
64 18 ▶ my $payload = {
Condition80%4/5
($r->model // $request->model) // "unknown"
l!l
171
$r->model // $request->model
l!l&&r!l&&!r
1701
MC/DC50%1/2
($r->model // $request->model) // "unknown"
$r->model $request->model
Truth table66%2/3
A // B
A= $r->modelB= $request->model
ABresult
1X1
011
000
65 id => 'chatcmpl-' . int( time() * 1000 ),
66 object => 'chat.completion',
67 created => int( time() ),
68 model => $r->model // $request->model // 'unknown',
69 choices => [
70 {
71 index => 0,
72 message => $message,
73 finish_reason => $finish,
74 },
75 ],
76 usage => $usage,
77 };
78 18 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
79 }
80  
81 sub format_models_response {
82 2 ▶ my ($self, $models) = @_;
Subroutine format_models_response: called CC=2 SCAR=7.0
Pod undocumented
83 my @data = map {
84 2 ▶ ref $_ eq 'HASH' ? { object => 'model', %$_ } : { id => "$_", object => 'model' }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 2 0 2
85 } @$models;
86 2 my $payload = { object => 'list', data => \@data };
87 2 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
88 }
89  
90 sub format_stream_chunk {
91 17 ▶ my ($self, $delta_text, $request) = @_;
Subroutine format_stream_chunk: called CC=2 SCAR=7.1
Pod undocumented
92 17 ▶ my $payload = {
Condition50%1/2
$request->model // "unknown"
l!l
170
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table50%1/2
A
A= $request->model
Aresult
11
00
93 id => 'chatcmpl-stream',
94 object => 'chat.completion.chunk',
95 created => int( time() ),
96 model => $request->model // 'unknown',
97 choices => [ { index => 0, delta => { content => $delta_text }, finish_reason => undef } ],
98 };
99 17 return "data: " . $self->_json->encode($payload) . "\n\n";
100 }
101  
102 13 __PACKAGE__->meta->make_immutable;
103 13 1;
104  
105 __END__
106  
107 =pod
108  
109 =encoding UTF-8
110  
111 =head1 NAME
112  
113 Langertha::Knarr::Protocol::OpenAI - OpenAI-compatible wire protocol (chat/completions, models) for Knarr
114  
115 =head1 VERSION
116  
117 version 1.100
118  
119 =head1 DESCRIPTION
120  
121 Implements the OpenAI Chat Completions wire format on top of
122 L<Langertha::Knarr::Protocol>. Loaded by default in every
123 L<Langertha::Knarr> instance.
124  
125 =over
126  
127 =item * C<POST /v1/chat/completions> — sync and SSE streaming
128  
129 =item * C<GET /v1/models> — model listing
130  
131 =back
132  
133 Streaming uses the standard SSE chunk format with C<data: [DONE]> as
134 the terminator. C<tools>, C<tool_choice>, and C<response_format> are
135 extracted into L<Langertha::Knarr::Request> attributes and forwarded to
136 the engine via C<chat_f>. Tool-call responses are serialised into
137 C<message.tool_calls> with C<finish_reason: "tool_calls">.
138  
139 =head1 SUPPORT
140  
141 =head2 Issues
142  
143 Please report bugs and feature requests on GitHub at
144 L<https://github.com/Getty/langertha-knarr/issues>.
145  
146 =head2 IRC
147  
148 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
149  
150 =head1 CONTRIBUTING
151  
152 Contributions are welcome! Please fork the repository and submit a pull request.
153  
154 =head1 AUTHOR
155  
156 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
157  
158 =head1 COPYRIGHT AND LICENSE
159  
160 This software is copyright (c) 2026 by Torsten Raudssus.
161  
162 This is free software; you can redistribute it and/or modify it under
163 the same terms as the Perl 5 programming language system itself.
164  
165 =cut
« Knarr/Handler/ACPClient.pm ↑ Summary Knarr/Protocol/Ollama.pm »