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

filter: Statementstmt 100% 101 / 101 Branchbran 93.7% 30 / 32 Conditioncond 71.4% 25 / 35 MC/DCmcdc 47.3% 9 / 19 Subroutinesub 100% 28 / 28 Podpod 23.0% 3 / 13 totaltotal 85.9% 196 / 228 CC 33 SCAR 15.8
CC
33
Cov
93%
parse_chat_request
12.2
format_chat_response
7.2
format_stream_done
5.1
CRAP 4.9
« blib/lib/Langertha/Knarr/Handler/Tracing.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/AGUI.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 46 our $VERSION = '1.102';
5 46 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 46 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 46 ▶use Time::HiRes qw( time );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 46 ▶use POSIX qw( strftime );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 46 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 46 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 46 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 46 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 46 ▶use Langertha::Knarr::Reasoning;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 46 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 121 ▶has _json => ( is => 'ro', default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
28  
29 46 has reasoning => (
30 is => 'ro',
31 isa => 'Langertha::Knarr::Reasoning',
32 lazy => 1,
33 builder => '_build_reasoning',
34 );
35  
36 42 ▶sub _build_reasoning { Langertha::Knarr::Reasoning->new }
Subroutine _build_reasoning: called CC=1 SCAR=0.0
37  
38  
39 37 ▶sub protocol_name { 'ollama' }
Subroutine protocol_name: called CC=1 SCAR=0.0
Pod undocumented
40  
41 91 ▶sub protocol_routes {
Subroutine protocol_routes: called CC=1 SCAR=0.0
Pod undocumented
42 return [
43 91 { 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 37 ▶sub manifest_endpoint {
Subroutine manifest_endpoint: called CC=1 SCAR=0.0
Pod undocumented
56 return {
57 37 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 342 ▶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 269 ▶sub _is_generate {
Subroutine _is_generate: called CC=3 SCAR=11.0
78 269 my ($self, $request) = @_;
79 269 ▶ return ( $request->extra->{path} // '' ) eq '/api/generate' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($request->extra->{'path'} // '') eq '/api/generate' ? : 64 205 269
Condition100%2/2
$request->extra->{"path"} // ""
l!l
23237
MC/DC100%1/1
$request->extra->{"path"} // ""
$request->extra->{"path"}
Truth table100%2/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 269 ▶sub _text_fields {
Subroutine _text_fields: called CC=4 SCAR=13.9
85 269 my ($self, $request, $text, $tool_calls) = @_;
86 269 ▶ return ( response => $text ) if $self->_is_generate($request);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_generate($request) 64 205 269
87 205 my $message = { role => 'assistant', content => $text };
88 205 ▶ $message->{tool_calls} = [ map { $_->to_ollama } @$tool_calls ]
Branch: 1 branch
BranchTrueFalseTotal
if $tool_calls and @$tool_calls 7 198 205
Condition100%3/3
$tool_calls and @$tool_calls
!ll&&!rl&&r
901087
MC/DC100%2/2
$tool_calls and @$tool_calls
$tool_calls @$tool_calls
Truth table100%3/3
A and B
A= $tool_callsB= @$tool_calls
ABresult
0X0
100
111
89 if $tool_calls && @$tool_calls;
90 205 return ( message => $message );
91 }
92  
93 207 ▶sub parse_chat_request {
Subroutine parse_chat_request: called CC=12 SCAR=25.0
Pod undocumented
94 207 my ($self, $http_req, $body_ref) = @_;
95 207 ▶ my $data = $self->_json->decode( $$body_ref || '{}' );
Condition50%1/2
$$body_ref || '{}'
l!l
2070
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 207 ▶ 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') ? : 176 31 207
Condition83%5/6
$http_req and builtin::blessed($http_req) and $http_req->can("path")
!ll&&!rl&&r
130176
$http_req and builtin::blessed($http_req)
!ll&&!rl&&r
10206
MC/DC66%2/3
$http_req and builtin::blessed($http_req) and $http_req->can("path")
$http_req builtin::blessed($http_req) $http_req->can("path")
Truth table75%3/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 207 my $fwd = $self->_forward_headers( $http_req, qw( authorization ) );
106 207 my @msgs;
107 207 ▶ if ( $data->{messages} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($data->{'messages'}) { } 156 51 207
elsif (defined $data->{'prompt'}) { } 51 0 51
108 156 @msgs = @{ Langertha::Knarr::Image::ollama_messages( $data->{messages} ) };
109 }
110 elsif ( defined $data->{prompt} ) {
111 51 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 51 ▶ if ref $data->{images} eq 'ARRAY' && @{ $data->{images} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $data->{"images"} eq "ARRAY" and @{$data->{"images"};} 3 48 51
Condition66%2/3
ref $data->{"images"} eq "ARRAY" and @{$data->{"images"};}
!ll&&!rl&&r
4803
MC/DC50%1/2
ref $data->{"images"} eq "ARRAY" and @{$data->{"images"};}
ref $data->{"images"} eq "ARRAY" @{$data->{"images"};}
Truth table66%2/3
A and B
A= ref $data->{"images"} eq "ARRAY"B= @{$data->{"images"};}
ABresult
0X0
100
111
117 51 @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 207 ▶ extra => { forward_headers => $fwd, defined $path ? ( path => $path ) : () },
Branch: 3 branches
BranchTrueFalseTotal
exists $data->{'stream'} ? : 151 56 207
$data->{'stream'} ? : 51 100 151
defined $path ? : 176 31 207
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 46 ( map { $_ => $_ } qw( stop length load unload ) ),
141 max_tokens => 'length',
142 );
143  
144 171 ▶sub _done_reason {
Subroutine _done_reason: called CC=3 SCAR=11.0
145 171 my ($finish_reason) = @_;
146 171 ▶ return 'stop' unless defined $finish_reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $finish_reason 81 90 171
147 90 ▶ return $DONE_REASON{ lc $finish_reason } // 'stop';
Condition100%2/2
$DONE_REASON{lc $finish_reason} // "stop"
l!l
7713
MC/DC100%1/1
$DONE_REASON{lc $finish_reason} // "stop"
$DONE_REASON{lc $finish_reason}
Truth table100%2/2
A
A= $DONE_REASON{lc $finish_reason}
Aresult
11
00
148 }
149  
150 93 ▶sub format_chat_response {
Subroutine format_chat_response: called CC=7 SCAR=19.7
Pod documented
151 93 my ($self, $response, $request) = @_;
152 93 my $r = Langertha::Knarr::Response->coerce($response);
153 93 ▶ my $payload = {
Branch: 1 branch
BranchTrueFalseTotal
$r->has_tool_calls ? : 2 91 93
Condition60%3/5
($r->model // $request->model) // "unknown"
l!l
930
$r->model // $request->model
l!l&&r!l&&!r
80130
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 93 ▶ if ( $r->usage && $r->usage->can('to_ollama_format') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->usage and $r->usage->can("to_ollama_format")) 13 80 93
Condition66%2/3
$r->usage and $r->usage->can("to_ollama_format")
!ll&&!rl&&r
80013
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 13 my $u = $r->usage->to_ollama_format;
162 13 $payload->{$_} = $u->{$_} for keys %$u;
163 }
164 93 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
165 }
166  
167  
168 20 ▶sub format_models_response {
Subroutine format_models_response: called CC=2 SCAR=7.0
Pod undocumented
169 20 my ($self, $models) = @_;
170 my @data = map {
171 20 ▶ my $id = ref $_ eq 'HASH' ? $_->{id} : "$_";
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 20 0 20
172 20 { name => $id, model => $id, modified_at => _ts(), size => 0 }
173 } @$models;
174 20 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 26 ▶sub format_version_response {
Subroutine format_version_response: called CC=1 SCAR=0.0
Pod undocumented
182 26 my ($self, $version) = @_;
183 26 return ( 200, { 'Content-Type' => 'application/json' },
184 $self->_json->encode({ version => "$version" }) );
185 }
186  
187  
188 29 ▶sub format_error_response {
Subroutine format_error_response: called CC=1 SCAR=0.0
Pod documented
189 29 my ($self, $status, $message) = @_;
190 29 return ( $status, { 'Content-Type' => 'application/json' },
191 $self->_json->encode({ error => "$message" }) );
192 }
193  
194  
195 53 ▶sub format_show_response {
Subroutine format_show_response: called CC=3 SCAR=11.0
Pod documented
196 53 my ($self, $model, $info) = @_;
197 53 my %model_info;
198 53 ▶ if ( defined $info->{context_length} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $info->{"context_length"}) 4 49 53
199 %model_info = (
200 'general.architecture' => 'knarr',
201 4 'knarr.context_length' => $info->{context_length} + 0,
202 );
203 }
204 my $payload = {
205 modified_at => _ts(),
206 53 ▶ capabilities => [ @{ $info->{capabilities} || [] } ],
Condition50%1/2
$info->{'capabilities'} || []
l!l
530
MC/DC0%0/1
$info->{'capabilities'} || []
$info->{'capabilities'}
Truth table50%1/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 53 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
221 }
222  
223 98 ▶sub format_stream_chunk {
Subroutine format_stream_chunk: called CC=2 SCAR=7.1
Pod undocumented
224 98 my ($self, $delta_text, $request) = @_;
225 98 ▶ my $payload = {
Condition50%1/2
$request->model // "unknown"
l!l
980
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table50%1/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 98 return $self->_json->encode($payload) . "\n";
232 }
233  
234 69 ▶sub stream_content_type { 'application/x-ndjson' }
Subroutine stream_content_type: called CC=1 SCAR=0.0
Pod undocumented
235  
236 # Ollama ends a failed stream with an {"error":"..."} line.
237 5 ▶sub format_stream_error {
Subroutine format_stream_error: called CC=1 SCAR=0.0
Pod undocumented
238 5 my ($self, $status, $message) = @_;
239 5 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 78 ▶sub format_stream_done {
Subroutine format_stream_done: called CC=5 SCAR=16.3
Pod undocumented
246 78 my ($self, $request, $finish_reason, $tool_calls, $usage) = @_;
247 78 ▶ my $payload = {
Condition50%1/2
$request->model // "unknown"
l!l
780
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table50%1/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 78 ▶ if ( $usage && $usage->can('to_ollama_format') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage and $usage->can("to_ollama_format")) 3 75 78
Condition66%2/3
$usage and $usage->can("to_ollama_format")
!ll&&!rl&&r
7503
MC/DC50%1/2
$usage and $usage->can("to_ollama_format")
$usage $usage->can("to_ollama_format")
Truth table66%2/3
A and B
A= $usageB= $usage->can("to_ollama_format")
ABresult
0X0
100
111
255 3 my $u = $usage->to_ollama_format;
256 3 $payload->{$_} = $u->{$_} for keys %$u;
257 }
258 78 return $self->_json->encode($payload) . "\n";
259 }
260  
261 46 __PACKAGE__->meta->make_immutable;
262 46 1;
263  
264 __END__
265  
266 =pod
267  
268 =encoding UTF-8
269  
270 =head1 NAME
271  
272 Langertha::Knarr::Protocol::Ollama - Ollama-compatible wire protocol (/api/chat, /api/generate, /api/tags, /api/version, /api/show) for Knarr
273  
274 =head1 VERSION
275  
276 version 1.102
277  
278 =head1 DESCRIPTION
279  
280 Implements the Ollama wire format on top of
281 L<Langertha::Knarr::Protocol>. Loaded by default.
282  
283 =over
284  
285 =item * C<POST /api/chat>, C<POST /api/generate> — chat with NDJSON streaming;
286 C</api/generate> answers in Ollama's generate shape, the text on C<response>
287 instead of C<message> (see L</format_chat_response>)
288  
289 =item * C<GET /api/tags> — model listing
290  
291 =item * C<GET /api/version> — version probe, answered with Ollama's shape
292 C<{"version":"x.y.z"}> and the Ollama version Knarr claims compatibility
293 with (L<Langertha::Knarr/ollama_compat_version>), not Knarr's own version
294  
295 =item * C<POST /api/show> — model details for a listed model (see
296 L</format_show_response>); C<model> or the legacy C<name> in the body,
297 C<400> without one, Ollama's C<404> C<{"error":"model 'x' not found"}> for
298 a model Knarr does not list
299  
300 =back
301  
302 The client's C<Authorization> header is kept as C<forward_headers>, like
303 the OpenAI and Anthropic protocols do, so a
304 L<Langertha::Knarr::Handler::Passthrough> in the handler chain reaches an
305 authenticated remote Ollama with it.
306  
307 Streaming uses newline-delimited JSON (NDJSON) rather than SSE — the
308 C<Content-Type> is C<application/x-ndjson> and each chunk is a single
309 JSON object per line. The final chunk has C<done: true>.
310  
311 =head2 reasoning
312  
313 The L<Langertha::Knarr::Reasoning> that maps the body's C<think> (a boolean
314 or a level string) onto the request's C<reasoning_effort>. Pass your own to
315 override the level C<think: true> maps to.
316  
317 =head2 format_chat_response
318  
319 my ($status, $headers, $body) = $proto->format_chat_response( $response, $request );
320  
321 The non-streaming answer: C<model>, C<created_at>, C<done>, C<done_reason>
322 and the usage counters (C<prompt_eval_count>, C<eval_count>, ...) when the
323 backend reported usage. A C</api/chat> request gets the text on C<message>
324 (with C<tool_calls>), a C</api/generate> request on C<response>, as Ollama
325 answers it -- streaming alike, where every chunk carries its piece on
326 C<message.content> or C<response> and the final C<{"done": true}> line an
327 empty one, with the usage counters when the backend reported usage.
328  
329 =head2 format_error_response
330  
331 my ($status, $headers, $body) = $proto->format_error_response( 404, "model 'x' not found" );
332  
333 Ollama's error answer: C<{"error":"..."}> with a plain string, not the
334 C<{"error":{"message":...}}> object of the OpenAI wire.
335  
336 =head2 format_show_response
337  
338 my ($status, $headers, $body) = $proto->format_show_response( $model, {
339 capabilities => [ 'completion', 'tools' ],
340 context_length => 131072, # optional
341 } );
342  
343 The C<POST /api/show> answer for a model Knarr serves (k29). Only what
344 Knarr knows is claimed: C<capabilities> as given, C<model_info> with
345 C<general.architecture> (C<knarr>) and C<knarr.context_length> when a
346 context length is known -- the pair VS Code Copilot reads, C<{}> otherwise
347 -- and empty C<details>, C<template> and C<parameters>, since there are no
348 local weights, template or Modelfile behind a routed model.
349  
350 =head1 SUPPORT
351  
352 =head2 Issues
353  
354 Please report bugs and feature requests on GitHub at
355 L<https://github.com/Getty/langertha-knarr/issues>.
356  
357 =head2 IRC
358  
359 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
360  
361 =head1 CONTRIBUTING
362  
363 Contributions are welcome! Please fork the repository and submit a pull request.
364  
365 =head1 AUTHOR
366  
367 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
368  
369 =head1 COPYRIGHT AND LICENSE
370  
371 This software is copyright (c) 2026 by Torsten Raudssus.
372  
373 This is free software; you can redistribute it and/or modify it under
374 the same terms as the Perl 5 programming language system itself.
375  
376 =cut
« blib/lib/Langertha/Knarr/Handler/Tracing.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/AGUI.pm »