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

filter: Statementstmt 70.3% 71 / 101 Branchbran 59.3% 19 / 32 Conditioncond 37.1% 13 / 35 MC/DCmcdc 10.5% 2 / 19 Subroutinesub 64.2% 18 / 28 Podpod 23.0% 3 / 13 totaltotal 55.2% 126 / 228 CC 33 SCAR 21.5
CC
33
Cov
61%
format_stream_done
30.0
parse_chat_request
16.2
format_show_response
12.0
CRAP 8.6
« blib/lib/Langertha/Knarr/Role/UpstreamHTTP.pm ↑ Summary blib/lib/Langertha/Knarr/RequestLog.pm »
1 package Langertha::Knarr::Protocol::Ollama;
2 # ABSTRACT: Ollama-compatible wire protocol (/api/chat, /api/generate, /api/tags, /api/version, /api/show) for Knarr
3  
4 6 our $VERSION = '1.103';
5 6 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 6 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use Time::HiRes qw( time );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use POSIX qw( strftime );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 6 ▶use Langertha::Knarr::Reasoning;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 6 with 'Langertha::Knarr::Protocol';
16  
17 # --- Streaming model ---
18 # Ollama streams via newline-delimited JSON (NDJSON), NOT SSE.
19 # Each chunk: { model, created_at, message:{role,content}, done:false }
20 # Final: { model, created_at, message:{role,content:""}, done:true,
21 # total_duration, eval_count, ... }
22 # /api/generate carries the text on response instead of message (k48):
23 # { model, created_at, response, done, ... }
24 # Content-Type stays application/x-ndjson (or application/json with chunked).
25 # ----------------------
26  
27 23 ▶has _json => ( is => 'ro', default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
28  
29 6 has reasoning => (
30 is => 'ro',
31 isa => 'Langertha::Knarr::Reasoning',
32 lazy => 1,
33 builder => '_build_reasoning',
34 );
35  
36 12 ▶sub _build_reasoning { Langertha::Knarr::Reasoning->new }
Subroutine _build_reasoning: called CC=1 SCAR=0.0
37  
38  
39 0 ▶sub protocol_name { 'ollama' }
Subroutine protocol_name: not called CC=1 SCAR=6.9
Pod undocumented
40  
41 0 ▶sub protocol_routes {
Subroutine protocol_routes: not called CC=1 SCAR=6.9
Pod undocumented
42 return [
43 0 { method => 'POST', path => '/api/chat', action => 'chat' },
44 { method => 'POST', path => '/api/generate', action => 'chat' },
45 { method => 'GET', path => '/api/tags', action => 'models' },
46 { method => 'GET', path => '/api/version', action => 'version' },
47 { method => 'POST', path => '/api/show', action => 'show' },
48 ];
49 }
50  
51 # Provider manifest (k14): parse_chat_request below carries tools, format,
52 # options.temperature and options.seed. Ollama has no tool_choice; a schema
53 # in `format` is not mapped onto a json_schema response_format, so only
54 # the loose JSON mode is claimed; num_predict is not forwarded.
55 1 ▶sub manifest_endpoint {
Subroutine manifest_endpoint: called CC=1 SCAR=0.0
Pod undocumented
56 return {
57 1 dialect => 'ollama',
58 path => '',
59 capabilities => [qw(
60 chat streaming system_prompt
61 tools_native tools_hermes
62 response_format_json_object
63 temperature seed reasoning_effort
64 image_input
65 )],
66 # A message's images array becomes Langertha::Content::Image objects
67 # (k33); an older core gets it as sent, read only by native Ollama.
68 image_content_formats => Langertha::Knarr::Image::content_formats(qw( ollama )),
69 };
70 }
71  
72 8 ▶sub _ts { strftime( "%Y-%m-%dT%H:%M:%S.000000000Z", gmtime ) }
Subroutine _ts: called CC=1 SCAR=0.0
73  
74 # The path the client asked for, recorded by parse_chat_request as
75 # extra->{path} (k48). /api/generate answers in its own shape, and a
76 # passthrough handler in the chain sends it to the upstream's /api/generate.
77 8 ▶sub _is_generate {
Subroutine _is_generate: called CC=3 SCAR=12.0
78 8 my ($self, $request) = @_;
79 8 ▶ return ( $request->extra->{path} // '' ) eq '/api/generate' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($request->extra->{'path'} // '') eq '/api/generate' ? : 0 8 8
Condition50%1/2
$request->extra->{"path"} // ""
l!l
08
MC/DC0%0/1
$request->extra->{"path"} // ""
$request->extra->{"path"}
Truth table50%1/2
A
A= $request->extra->{"path"}
Aresult
11
00
80 }
81  
82 # The client's answer text and the fields around it: message for /api/chat,
83 # response for /api/generate.
84 8 ▶sub _text_fields {
Subroutine _text_fields: called CC=4 SCAR=14.0
85 8 my ($self, $request, $text, $tool_calls) = @_;
86 8 ▶ return ( response => $text ) if $self->_is_generate($request);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_generate($request) 0 8 8
87 8 my $message = { role => 'assistant', content => $text };
88 8 ▶ $message->{tool_calls} = [ map { $_->to_ollama } @$tool_calls ]
Branch: 1 branch
BranchTrueFalseTotal
if $tool_calls and @$tool_calls 1 7 8
Condition66%2/3
$tool_calls and @$tool_calls
!ll&&!rl&&r
071
MC/DC50%1/2
$tool_calls and @$tool_calls
$tool_calls @$tool_calls
Truth table66%2/3
A and B
A= $tool_callsB= @$tool_calls
ABresult
0X0
100
111
89 if $tool_calls && @$tool_calls;
90 8 return ( message => $message );
91 }
92  
93 28 ▶sub parse_chat_request {
Subroutine parse_chat_request: called CC=12 SCAR=27.8
Pod undocumented
94 28 my ($self, $http_req, $body_ref) = @_;
95 28 ▶ my $data = $self->_json->decode( $$body_ref || '{}' );
Condition50%1/2
$$body_ref || '{}'
l!l
280
MC/DC0%0/1
$$body_ref || '{}'
$$body_ref
Truth table50%1/2
A
A= $$body_ref
Aresult
11
00
96 # The native server's request and the PSGI adapter's both know the path;
97 # which of the two chat routes the request came in on picks the answer's
98 # shape (k48).
99 28 ▶ my $path = $http_req && Scalar::Util::blessed($http_req) && $http_req->can('path')
Branch: 1 branch
BranchTrueFalseTotal
$http_req && builtin::blessed($http_req) && $http_req->can('path') ? : 0 28 28
Condition33%2/6
$http_req and builtin::blessed($http_req) and $http_req->can("path")
!ll&&!rl&&r
0280
$http_req and builtin::blessed($http_req)
!ll&&!rl&&r
0028
MC/DC0%0/3
$http_req and builtin::blessed($http_req) and $http_req->can("path")
$http_req builtin::blessed($http_req) $http_req->can("path")
Truth table25%1/4
A and B and C
A= $http_reqB= builtin::blessed($http_req)C= $http_req->can("path")
ABCresult
0XX0
10X0
1100
1111
100 ? $http_req->path : undef;
101 # Capture auth headers for passthrough, like the OpenAI and Anthropic
102 # parsers: a Handler::Passthrough in the chain forwards them to an
103 # authenticated remote Ollama (k49), one pair per line (k60). Knarr takes
104 # its own key out.
105 28 my $fwd = $self->_forward_headers( $http_req, qw( authorization ) );
106 28 my @msgs;
107 28 ▶ if ( $data->{messages} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($data->{'messages'}) { } 25 3 28
elsif (defined $data->{'prompt'}) { } 3 0 3
108 25 @msgs = @{ Langertha::Knarr::Image::ollama_messages( $data->{messages} ) };
109 }
110 elsif ( defined $data->{prompt} ) {
111 3 my %msg = ( role => 'user', content => $data->{prompt} );
112 # /api/generate carries images on the request, not a message (k34).
113 # They go onto the user message in Ollama's message shape: translated
114 # like chat images, or as sent on an older core.
115 $msg{images} = $data->{images}
116 3 ▶ if ref $data->{images} eq 'ARRAY' && @{ $data->{images} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $data->{"images"} eq "ARRAY" and @{$data->{"images"};} 3 0 3
Condition33%1/3
ref $data->{"images"} eq "ARRAY" and @{$data->{"images"};}
!ll&&!rl&&r
003
MC/DC0%0/2
ref $data->{"images"} eq "ARRAY" and @{$data->{"images"};}
ref $data->{"images"} eq "ARRAY" @{$data->{"images"};}
Truth table33%1/3
A and B
A= ref $data->{"images"} eq "ARRAY"B= @{$data->{"images"};}
ABresult
0X0
100
111
117 3 @msgs = @{ Langertha::Knarr::Image::ollama_messages( [ \%msg ] ) };
118 }
119 return Langertha::Knarr::Request->new(
120 protocol => 'ollama',
121 raw => $data,
122 model => $data->{model},
123 messages => \@msgs,
124 stream => exists $data->{stream} ? ( $data->{stream} ? 1 : 0 ) : 1, # Ollama defaults to stream
125 temperature => $data->{options}{temperature},
126 seed => $data->{options}{seed},
127 reasoning_effort => scalar $self->reasoning->from_ollama( $data->{think}, $data->{reasoning_effort} ),
128 tools => $data->{tools},
129 response_format => $data->{format},
130 28 ▶ extra => { forward_headers => $fwd, defined $path ? ( path => $path ) : () },
Branch: 3 branches
BranchTrueFalseTotal
exists $data->{'stream'} ? : 9 19 28
$data->{'stream'} ? : 0 9 9
defined $path ? : 0 28 28
131 );
132 }
133  
134 # Ollama's done_reason vocabulary is stop / length (plus load / unload for
135 # model-management answers, which carry no generation). Tool calls end with
136 # stop on Ollama's own wire. Every other reason -- tool_calls, end_turn,
137 # content_filter, Gemini SAFETY, ... -- has no Ollama counterpart and
138 # becomes stop.
139 my %DONE_REASON = (
140 6 ( map { $_ => $_ } qw( stop length load unload ) ),
141 max_tokens => 'length',
142 );
143  
144 8 ▶sub _done_reason {
Subroutine _done_reason: called CC=3 SCAR=11.1
145 8 my ($finish_reason) = @_;
146 8 ▶ return 'stop' unless defined $finish_reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $finish_reason 7 1 8
147 1 ▶ return $DONE_REASON{ lc $finish_reason } // 'stop';
Condition50%1/2
$DONE_REASON{lc $finish_reason} // "stop"
l!l
01
MC/DC0%0/1
$DONE_REASON{lc $finish_reason} // "stop"
$DONE_REASON{lc $finish_reason}
Truth table50%1/2
A
A= $DONE_REASON{lc $finish_reason}
Aresult
11
00
148 }
149  
150 8 ▶sub format_chat_response {
Subroutine format_chat_response: called CC=7 SCAR=19.7
Pod documented
151 8 my ($self, $response, $request) = @_;
152 8 my $r = Langertha::Knarr::Response->coerce($response);
153 8 ▶ my $payload = {
Branch: 1 branch
BranchTrueFalseTotal
$r->has_tool_calls ? : 1 7 8
Condition60%3/5
($r->model // $request->model) // "unknown"
l!l
80
$r->model // $request->model
l!l&&r!l&&!r
620
MC/DC0%0/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
154 model => $r->model // $request->model // 'unknown',
155 created_at => _ts(),
156 $self->_text_fields( $request, $r->content, $r->has_tool_calls ? $r->tool_calls : [] ),
157 done => JSON::MaybeXS::true(),
158 done_reason => _done_reason( $r->finish_reason ),
159 };
160 8 ▶ if ( $r->usage && $r->usage->can('to_ollama_format') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->usage and $r->usage->can("to_ollama_format")) 7 1 8
Condition66%2/3
$r->usage and $r->usage->can("to_ollama_format")
!ll&&!rl&&r
107
MC/DC50%1/2
$r->usage and $r->usage->can("to_ollama_format")
$r->usage $r->usage->can("to_ollama_format")
Truth table66%2/3
A and B
A= $r->usageB= $r->usage->can("to_ollama_format")
ABresult
0X0
100
111
161 7 my $u = $r->usage->to_ollama_format;
162 7 $payload->{$_} = $u->{$_} for keys %$u;
163 }
164 8 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
165 }
166  
167  
168 0 ▶sub format_models_response {
Subroutine format_models_response: not called CC=2 SCAR=17.9
Pod undocumented
169 0 my ($self, $models) = @_;
170 my @data = map {
171 0 ▶ my $id = ref $_ eq 'HASH' ? $_->{id} : "$_";
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 0 0
172 0 { name => $id, model => $id, modified_at => _ts(), size => 0 }
173 } @$models;
174 0 return ( 200, { 'Content-Type' => 'application/json' },
175 $self->_json->encode({ models => \@data }) );
176 }
177  
178 # GET /api/version (k27). Ollama clients read this as the server's Ollama
179 # version and may gate features on it, so it carries the Ollama version
180 # Knarr's endpoints are compatible with, never Knarr's own version.
181 0 ▶sub format_version_response {
Subroutine format_version_response: not called CC=1 SCAR=6.9
Pod undocumented
182 0 my ($self, $version) = @_;
183 0 return ( 200, { 'Content-Type' => 'application/json' },
184 $self->_json->encode({ version => "$version" }) );
185 }
186  
187  
188 0 ▶sub format_error_response {
Subroutine format_error_response: not called CC=1 SCAR=6.9
Pod documented
189 0 my ($self, $status, $message) = @_;
190 0 return ( $status, { 'Content-Type' => 'application/json' },
191 $self->_json->encode({ error => "$message" }) );
192 }
193  
194  
195 0 ▶sub format_show_response {
Subroutine format_show_response: not called CC=3 SCAR=24.8
Pod documented
196 0 my ($self, $model, $info) = @_;
197 0 my %model_info;
198 0 ▶ if ( defined $info->{context_length} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $info->{"context_length"}) 0 0 0
199 %model_info = (
200 'general.architecture' => 'knarr',
201 0 'knarr.context_length' => $info->{context_length} + 0,
202 );
203 }
204 my $payload = {
205 modified_at => _ts(),
206 0 ▶ capabilities => [ @{ $info->{capabilities} || [] } ],
Condition0%0/2
$info->{'capabilities'} || []
l!l
00
MC/DC0%0/1
$info->{'capabilities'} || []
$info->{'capabilities'}
Truth table0%0/2
A
A= $info->{'capabilities'}
Aresult
11
00
207 details => {
208 parent_model => '',
209 format => '',
210 family => '',
211 families => [],
212 parameter_size => '',
213 quantization_level => '',
214 },
215 model_info => \%model_info,
216 template => '',
217 parameters => '',
218 license => '',
219 };
220 0 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
221 }
222  
223 0 ▶sub format_stream_chunk {
Subroutine format_stream_chunk: not called CC=2 SCAR=17.9
Pod undocumented
224 0 my ($self, $delta_text, $request) = @_;
225 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
226 model => $request->model // 'unknown',
227 created_at => _ts(),
228 $self->_text_fields( $request, $delta_text ),
229 done => JSON::MaybeXS::false(),
230 };
231 0 return $self->_json->encode($payload) . "\n";
232 }
233  
234 0 ▶sub stream_content_type { 'application/x-ndjson' }
Subroutine stream_content_type: not called CC=1 SCAR=6.9
Pod undocumented
235  
236 # Ollama ends a failed stream with an {"error":"..."} line.
237 0 ▶sub format_stream_error {
Subroutine format_stream_error: not called CC=1 SCAR=6.9
Pod undocumented
238 0 my ($self, $status, $message) = @_;
239 0 return $self->_json->encode({ error => "$message" }) . "\n";
240 }
241  
242 # The routed stream carries the backend's tool calls complete; Ollama's own
243 # wire sends message.tool_calls whole, so they ride on the done line (k19),
244 # and so do the usage counters, as Ollama's own done line has them.
245 0 ▶sub format_stream_done {
Subroutine format_stream_done: not called CC=5 SCAR=34.0
Pod undocumented
246 0 my ($self, $request, $finish_reason, $tool_calls, $usage) = @_;
247 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
248 model => $request->model // 'unknown',
249 created_at => _ts(),
250 $self->_text_fields( $request, '', $tool_calls ),
251 done => JSON::MaybeXS::true(),
252 done_reason => _done_reason($finish_reason),
253 };
254 0 ▶ if ( $usage && $usage->can('to_ollama_format') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage and $usage->can("to_ollama_format")) 0 0 0
Condition0%0/3
$usage and $usage->can("to_ollama_format")
!ll&&!rl&&r
000
MC/DC0%0/2
$usage and $usage->can("to_ollama_format")
$usage $usage->can("to_ollama_format")
Truth table0%0/3
A and B
A= $usageB= $usage->can("to_ollama_format")
ABresult
0X0
100
111
255 0 my $u = $usage->to_ollama_format;
256 0 $payload->{$_} = $u->{$_} for keys %$u;
257 }
258 0 return $self->_json->encode($payload) . "\n";
259 }
260  
261 6 __PACKAGE__->meta->make_immutable;
262 6 1;
263  
264 __END__
« blib/lib/Langertha/Knarr/Role/UpstreamHTTP.pm ↑ Summary blib/lib/Langertha/Knarr/RequestLog.pm »