blib/lib/Langertha/Engine/Ollama.pm

filter: Statementstmt 83.5% 168 / 201 Branchbran 81.4% 145 / 178 Conditioncond 67.7% 42 / 62 MC/DCmcdc 51.4% 18 / 35 Subroutinesub 81.2% 39 / 48 Podpod 34.6% 9 / 26 totaltotal 76.5% 421 / 550 CC 115 SCAR 28.5
CC
115
Cov
80%
list_models
42.0
chat_stream_request
37.7
chat_request
28.6
CRAP 17.3
« blib/lib/Langertha/Role/HTTP.pm ↑ Summary blib/lib/Langertha/Engine/Gemini.pm »
1 package Langertha::Engine::Ollama;
2 # ABSTRACT: Ollama API
3 57 our $VERSION = '0.505';
4 57 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 57 ▶use File::ShareDir::ProjectDistDir qw( :all );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 57 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 57 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 57 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 57 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 57 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 57 ▶use Langertha::Reasoning;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 57 ▶use Langertha::Engine::OllamaOpenAI;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 57 extends 'Langertha::Engine::Remote';
16  
17 57 with map { 'Langertha::Role::'.$_ } qw(
18 OpenAPI
19 Models
20 Seed
21 Temperature
22 ContextSize
23 ResponseSize
24 SystemPrompt
25 KeepAlive
26 Chat
27 Embedding
28 ResponseFormat
29 Streaming
30 Tools
31 ImageInput
32 );
33  
34  
35 9 ▶sub openai {
Subroutine openai: called CC=7 SCAR=19.7
Pod documented
36 9 my ( $self, %args ) = @_;
37 return Langertha::Engine::OllamaOpenAI->new(
38 url => $self->url.'/v1',
39 model => $self->model,
40 defined $self->api_key ? ( api_key => $self->api_key ) : (),
41 # The pin carries over while the url stays on its host (karr k375).
42 9 ▶ $self->_connect_address_for( exists $args{url} ? $args{url} : $self->url.'/v1' ),
Branch: 6 branches
BranchTrueFalseTotal
defined $self->api_key ? : 1 8 9
exists $args{'url'} ? : 2 7 9
$self->embedding_model ? : 9 0 9
$self->chat_model ? : 9 0 9
$self->has_system_prompt ? : 1 8 9
$self->has_temperature ? : 1 8 9
43 $self->embedding_model ? ( embedding_model => $self->embedding_model ) : (),
44 $self->chat_model ? ( chat_model => $self->chat_model ) : (),
45 $self->has_system_prompt ? ( system_prompt => $self->system_prompt ) : (),
46 $self->has_temperature ? ( temperature => $self->temperature ) : (),
47 %args,
48 );
49 }
50  
51  
52 3 ▶sub new_openai {
Subroutine new_openai: called CC=5 SCAR=16.1
Pod documented
53 3 my ( $class, %args ) = @_;
54 3 ▶ my $tools = delete $args{tools} || [];
Condition100%2/2
delete $args{'tools'} || []
l!l
21
MC/DC100%1/1
delete $args{'tools'} || []
delete $args{'tools'}
Truth table100%2/2
A
A= delete $args{'tools'}
Aresult
11
00
55 3 my $self = $class->new(%args);
56 # openai() copies only a few settings from the native engine; every other
57 # argument meant for the returned engine is handed on directly (karr k335).
58 162 my %accepts = map { $_->init_arg => 1 }
59 3 grep { defined $_->init_arg } Langertha::Engine::OllamaOpenAI->meta->get_all_attributes;
60 3 ▶ my %pass = map { $_ => $args{$_} } grep { $accepts{$_} && $_ ne 'url' } keys %args;
Condition100%3/3
$accepts{$_} && $_ ne 'url'
!ll&&!rl&&r
3310
MC/DC100%2/2
$accepts{$_} && $_ ne 'url'
$accepts{$_} $_ ne 'url'
Truth table100%3/3
A && B
A= $accepts{$_}B= $_ ne 'url'
ABresult
0X0
100
111
61 3 ▶ $pass{mcp_servers} = [ @{ $pass{mcp_servers} // [] }, @$tools ] if @$tools;
Branch: 1 branch
BranchTrueFalseTotal
if @$tools 2 1 3
Condition100%2/2
$pass{"mcp_servers"} // []
l!l
11
MC/DC100%1/1
$pass{"mcp_servers"} // []
$pass{"mcp_servers"}
Truth table100%2/2
A
A= $pass{"mcp_servers"}
Aresult
11
00
62 3 return $self->openai(%pass);
63 }
64  
65  
66 3 ▶sub default_model { 'llama3.3' }
Subroutine default_model: called CC=1 SCAR=0.0
Pod undocumented
67 11 ▶sub default_embedding_model { 'mxbai-embed-large' }
Subroutine default_embedding_model: called CC=1 SCAR=0.0
Pod undocumented
68  
69 # api_key_env derives LANGERTHA_OLLAMA_API_KEY, the variable _build_api_key
70 # reads: it unlocks Ollama Cloud, a local server needs no credentials.
71 4 ▶sub api_key_required { 0 }
Subroutine api_key_required: called CC=1 SCAR=0.0
Pod documented
72  
73 57 has api_key => (
74 is => 'ro',
75 lazy_build => 1,
76 );
77  
78 102 ▶sub _build_api_key {
Subroutine _build_api_key: called CC=1 SCAR=0.0
79 102 return $ENV{LANGERTHA_OLLAMA_API_KEY};
80 }
81  
82  
83 148 ▶sub update_request {
Subroutine update_request: called CC=2 SCAR=6.9
Pod documented
84 148 my ( $self, $request ) = @_;
85 148 my $key = $self->api_key;
86 148 ▶ $request->header('Authorization', 'Bearer '.$key) if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 4 144 148
87 }
88  
89  
90 0 ▶sub openapi_file { yaml => dist_file('Langertha','ollama.yaml') };
Subroutine openapi_file: not called CC=1 SCAR=6.9
Pod undocumented
91  
92 88 ▶sub _build_openapi_operations {
Subroutine _build_openapi_operations: called CC=1 SCAR=0.0
93 88 return use_module('Langertha::Spec::Ollama')->data;
94 }
95  
96  
97 has json_format => (
98 isa => 'Bool',
99 is => 'ro',
100 149 ▶ default => sub {0},
Subroutine __ANON__: called CC=1 SCAR=0.0
101 57 );
102  
103  
104 9 ▶sub embedding_request {
Subroutine embedding_request: called CC=2 SCAR=6.9
Pod undocumented
105 9 my ( $self, $prompt, %extra ) = @_;
106 4 ▶ return $self->generate_request( embed => sub { $self->embedding_response(shift, $prompt) },
Subroutine __ANON__: called CC=1 SCAR=0.0
107 9 ▶ model => $self->embedding_model,
Branch: 1 branch
BranchTrueFalseTotal
defined $self->embedding_dimensions ? : 2 7 9
108 input => $prompt,
109 # /api/embed truncates and renormalizes to `dimensions` for any model (k319).
110 defined $self->embedding_dimensions ? ( dimensions => $self->embedding_dimensions ) : (),
111 %extra,
112 );
113 }
114  
115 7 ▶sub embedding_response {
Subroutine embedding_response: called CC=11 SCAR=24.1
Pod undocumented
116 7 my ( $self, $response, $input ) = @_;
117 7 my $data = $self->parse_response($response);
118 # /api/embed returns one vector per input, by position. An ArrayRef input is
119 # a batch and gets them all; a string input keeps getting one vector (k289).
120 7 ▶ my $embeddings = ref $data eq 'HASH' ? $data->{embeddings} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 7 0 7
121 # No vector is not a result: older Ollama answers some load errors with a
122 # 200 {"error":...}, and undef would be stored as a vector (k290).
123 7 ▶ unless ( ref $embeddings eq 'ARRAY' && @{$embeddings}
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $embeddings eq "ARRAY" and @{$embeddings;} and not grep({ref $_ ne "ARRAY" or not @{$_;};} @{$embeddings;})) 3 4 7
Condition100%6/6
ref $embeddings eq "ARRAY" and @{$embeddings;} and not grep({ref $_ ne "ARRAY" or not @{$_;};} @{$embeddings;})
!ll&&!rl&&r
214
ref $embeddings eq "ARRAY" and @{$embeddings;}
!ll&&!rl&&r
115
MC/DC100%3/3
ref $embeddings eq "ARRAY" and @{$embeddings;} and not grep({ref $_ ne "ARRAY" or not @{$_;};} @{$embeddings;})
ref $embeddings eq "ARRAY" @{$embeddings;} not grep({ref $_ ne "ARRAY" or not @{$_;};} @{$embeddings;})
Truth table100%4/4
A and B and not(C)
A= ref $embeddings eq "ARRAY"B= @{$embeddings;}C= not grep({ref $_ ne "ARRAY" or not @{$_;};} @{$embeddings;})
ABCresult
0XX0
10X0
1100
1111
124 8 ▶ && !grep { ref $_ ne 'ARRAY' || !@{$_} } @{$embeddings} ) {
Condition66%2/3
ref $_ ne 'ARRAY' || !@{$_;}
l!l&&r!l&&!r
107
MC/DC50%1/2
ref $_ ne 'ARRAY' || !@{$_;}
ref $_ ne 'ARRAY' !@{$_;}
Truth table66%2/3
A || not(B)
A= ref $_ ne 'ARRAY'B= !@{$_;}
ABresult
1X1
011
000
125 3 ▶ my $err = ref $data eq 'HASH' ? $data->{error} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 3 0 3
126 3 ▶ $err = $err->{message} if ref $err eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $err eq "HASH" 0 3 3
127 3 ▶ croak "".(ref $self)." embedding response contained no vector"
Branch: 1 branch
BranchTrueFalseTotal
defined $err ? : 1 2 3
128 .( defined $err ? " (error: $err)" : '' );
129 }
130 4 ▶ if ( ref $input eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input eq "ARRAY") 2 2 4
131 2 my $count = scalar @{$embeddings};
132 croak "".(ref $self)." embedding response returned $count vectors for "
133 1 .scalar(@{$input})." inputs"
134 2 ▶ unless $count == @{$input};
Branch: 1 branch
BranchTrueFalseTotal
unless $count == @{$input;} 1 1 2
135 1 return [ @{$embeddings} ];
136 }
137 2 return $embeddings->[0];
138 }
139  
140 # The per-request reasoning_effort / thinking_enabled controls (chat_f, karr
141 # #46 / k382) -> top-level `think` via Langertha::Reasoning->to_ollama, for both
142 # request builders. Ollama does not compose Role::ReasoningEffort, so there are
143 # no engine attributes to layer. thinking_enabled => 0 is effort none (think
144 # false; the GPT-OSS floor 'low'); a bare 1 is think true, except on GPT-OSS,
145 # which takes only levels: dropped with a carp once per engine. An undef
146 # control counts as not set. A contradicting pair croaks (Reasoning BUILD).
147 122 ▶sub _ollama_reasoning_kwargs {
Subroutine _ollama_reasoning_kwargs: called CC=9 SCAR=22.1
148 122 my ( $self, $controls ) = @_;
149 122 my $effort = $controls->{reasoning_effort};
150 122 my $enabled = $controls->{thinking_enabled};
151 122 ▶ return () unless defined $effort || defined $enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $effort or defined $enabled 105 17 122
Condition100%3/3
defined $effort or defined $enabled
l!l&&r!l&&!r
98105
MC/DC100%2/2
defined $effort or defined $enabled
defined $effort defined $enabled
Truth table100%3/3
A or B
A= defined $effortB= defined $enabled
ABresult
1X1
011
000
152 17 ▶ my $reasoning = Langertha::Reasoning->new(
Branch: 3 branches
BranchTrueFalseTotal
defined $effort ? : 9 8 17
defined $enabled ? : 10 7 17
defined $self->chat_model ? : 17 0 17
153 ( defined $effort ? ( effort => $effort ) : () ),
154 ( defined $enabled ? ( thinking_enabled => $enabled ) : () ),
155 ( defined $self->chat_model ? ( model => $self->chat_model ) : () ),
156 );
157 15 ▶ if ( $reasoning->drops_thinking_enabled_on('ollama') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($reasoning->drops_thinking_enabled_on("ollama")) 2 13 15
158 2 ▶ my $value = $reasoning->thinking_enabled ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$reasoning->thinking_enabled ? : 2 0 2
159 2 ▶ my $model = $self->chat_model // '';
Condition50%1/2
$self->chat_model // ""
l!l
20
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
160 2 $self->_langertha_carp( ( ref $self ) . ": dropping thinking_enabled => " . $value
161 . " -- model '" . $model . "' has no level-free think form for it; "
162 . "set reasoning_effort instead",
163 'thinking_enabled=' . $value . ' wire=ollama model=' . $model );
164 }
165 15 return $reasoning->to('ollama');
166 }
167  
168 83 ▶sub chat_request {
Subroutine chat_request: called CC=25 SCAR=33.5
Pod undocumented
169 83 my ( $self, $messages, %extra ) = @_;
170  
171 # Canonical per-request controls (chat_f, karr #46) beat the engine
172 # attributes on a per-key basis; the rest of %extra passes straight through.
173 83 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
1964
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
174 # No parallel knob on this wire (parallel_tool_use is cleared): a value the
175 # caller set is only dropped, with the shared carp (karr k241).
176 83 $self->_parallel_tool_calls_kwarg( \%extra, $controls );
177  
178 # /api/chat has no tool_choice field: the tool_choice_* flags are cleared
179 # below, so the shared rule drops it (none withholds the tools, a forced
180 # choice carps; karr k239).
181 83 $self->_gate_tool_choice(\%extra);
182  
183 # Translate response_format -> Ollama's format parameter. Ollama
184 # accepts either the literal string 'json' or a JSON-Schema HashRef.
185 # A per-request response_format (chat_f) beats the engine attribute,
186 # and is removed from the extras either way: Ollama has no
187 # response_format field and would silently ignore it. Fall back to the
188 # legacy json_format attribute when neither is set.
189 my $rf = exists $controls->{response_format}
190 ? delete $controls->{response_format}
191 : exists $extra{response_format}
192 ? delete $extra{response_format}
193 83 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 6 77 83
exists $extra{'response_format'} ? : 3 74 77
$self->has_response_format ? : 1 73 74
194 83 my $format;
195 83 ▶ if ( defined $rf ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rf) 10 73 83
196 10 ▶ my $type = ref($rf) eq 'HASH' ? ( $rf->{type} // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $rf eq 'HASH' ? : 10 0 10
Condition50%1/2
$$rf{"type"} // ""
l!l
100
MC/DC0%0/1
$$rf{"type"} // ""
$$rf{"type"}
Truth table50%1/2
A
A= $$rf{"type"}
Aresult
11
00
197 10 ▶ if ( $type eq 'json_object' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'json_object') { } 1 9 10
elsif ($type eq 'json_schema' and ref $$rf{'json_schema'} eq 'HASH' and ref $$rf{'json_schema'}{'schema'} eq 'HASH') { } 9 0 9
198 1 $format = 'json';
199 }
200 ▶ elsif ( $type eq 'json_schema'
Condition33%2/6
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
!ll&&!rl&&r
009
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH"
!ll&&!rl&&r
009
MC/DC0%0/3
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
$type eq "json_schema" ref $$rf{"json_schema"} eq "HASH" ref $$rf{"json_schema"}{"schema"} eq "HASH"
Truth table25%1/4
A and B and C
A= $type eq "json_schema"B= ref $$rf{"json_schema"} eq "HASH"C= ref $$rf{"json_schema"}{"schema"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
201 && ref( $rf->{json_schema} ) eq 'HASH'
202 && ref( $rf->{json_schema}{schema} ) eq 'HASH' ) {
203 9 $format = $rf->{json_schema}{schema};
204 }
205 }
206 83 ▶ $format = 'json' if !defined $format && $self->json_format;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $format and $self->json_format 1 82 83
Condition100%3/3
not defined $format and $self->json_format
!ll&&!rl&&r
10721
MC/DC100%2/2
not defined $format and $self->json_format
not defined $format $self->json_format
Truth table100%3/3
not(A) and B
A= not defined $formatB= $self->json_format
ABresult
0X0
100
111
207  
208 # reasoning_effort -> the TOP-LEVEL `think` field, a sibling of
209 # model/messages/stream — NOT under options. Live-probed 2026-09-17 via
210 # ollama.com gpt-oss:20b: `think` inside options is silently ignored (low and
211 # max both yield the default ~180-220 thinking chars), while top-level `think`
212 # grades cleanly (low ~25-47, max ~207-402). Ollama does not compose
213 # ReasoningEffort, so serialize directly via the value object rather than
214 # advertising the capability; to_ollama emits (think => <boolean|level>).
215 83 my @reasoning = $self->_ollama_reasoning_kwargs($controls);
216  
217 18 ▶ return $self->generate_request( chat => sub { $self->chat_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
218 model => $self->chat_model,
219 messages => $messages,
220 stream => JSON->false,
221 @reasoning,
222 defined $format ? ( format => $format ) : (),
223 defined $self->get_keep_alive ? ( keep_alive => $self->get_keep_alive ) : (),
224 options => {
225 exists $controls->{temperature}
226 ? ( temperature => $controls->{temperature} )
227 : ( $self->has_temperature ? ( temperature => $self->temperature ) : () ),
228 $self->has_context_size ? ( num_ctx => $self->get_context_size ) : (),
229 exists $controls->{max_tokens}
230 ? ( num_predict => $controls->{max_tokens} )
231 : ( $self->get_response_size ? ( num_predict => $self->get_response_size ) : () ),
232 exists $controls->{seed}
233 ? ( seed => $controls->{seed} )
234 : ( $self->has_seed ? ( seed => $self->seed )
235 : $self->randomize_seed ? ( seed => $self->random_seed ) : () ),
236 0 ▶ $extra{options} ? (%{delete $extra{options}}) : (),
Branch: 11 branches
BranchTrueFalseTotal
defined $format ? : 11 71 82
defined $self->get_keep_alive ? : 10 72 82
exists $$controls{'temperature'} ? : 4 78 82
$self->has_temperature ? : 1 77 78
$self->has_context_size ? : 1 81 82
exists $$controls{'max_tokens'} ? : 3 79 82
$self->get_response_size ? : 0 79 79
exists $$controls{'seed'} ? : 2 80 82
$self->has_seed ? : 0 80 80
$self->randomize_seed ? : 0 80 80
$extra{'options'} ? : 0 82 82
237 },
238 %extra,
239 );
240 }
241  
242 50 ▶sub chat_response {
Subroutine chat_response: called CC=19 SCAR=29.4
243 50 my ( $self, $response ) = @_;
244 50 my $data = $self->parse_response($response);
245 47 my $msg = $data->{message};
246  
247 47 my $usage = {};
248 47 ▶ $usage->{prompt_tokens} = $data->{prompt_eval_count} if $data->{prompt_eval_count};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{"prompt_eval_count"} 8 39 47
249 47 ▶ $usage->{completion_tokens} = $data->{eval_count} if $data->{eval_count};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{"eval_count"} 8 39 47
250 47 ▶ $usage = undef unless %$usage;
Branch: 1 branch
BranchTrueFalseTotal
unless %$usage 39 8 47
251  
252 47 my $timing = {};
253 47 for my $k (qw( total_duration load_duration prompt_eval_duration eval_duration )) {
254 188 ▶ $timing->{$k} = $data->{$k} if $data->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{$k} 28 160 188
255 }
256 # Ollama reports the four native durations in nanoseconds. Mirror them
257 # as *_seconds (Float, seconds) so Langertha::Response.ttft_seconds /
258 # total_seconds and downstream observability (Langfuse, Prometheus
259 # scrapers) have a consistent unit. The original *_duration keys are
260 # preserved verbatim for backward compatibility.
261 47 ▶ my $ns_to_s = sub { $_[0] * 1e-9 };
Subroutine __ANON__: called CC=1 SCAR=0.0
262 47 ▶ $timing->{total_seconds} = $ns_to_s->( $data->{total_duration} ) if $data->{total_duration};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{"total_duration"} 7 40 47
263 47 ▶ $timing->{load_seconds} = $ns_to_s->( $data->{load_duration} ) if $data->{load_duration};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{"load_duration"} 7 40 47
264 47 ▶ $timing->{prompt_eval_seconds} = $ns_to_s->( $data->{prompt_eval_duration} ) if $data->{prompt_eval_duration};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{"prompt_eval_duration"} 7 40 47
265 47 ▶ $timing->{eval_seconds} = $ns_to_s->( $data->{eval_duration} ) if $data->{eval_duration};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{"eval_duration"} 7 40 47
266 47 ▶ $timing = undef unless %$timing;
Branch: 1 branch
BranchTrueFalseTotal
unless %$timing 40 7 47
267  
268 # Ollama stamps every response with an RFC3339 string carrying nanoseconds
269 # ("2026-02-22T04:00:45.027209927Z"). It is handed over verbatim: normalizing
270 # it is Langertha::Moment->from_wire's job, reached through
271 # Langertha::Response's BUILDARGS, which also parses the epoch seconds some
272 # Ollama-compatible shims send instead and drops a stamp it cannot read (the
273 # "0001-01-01T00:00:00Z" zero-value sentinel included) rather than failing
274 # the whole response. The native string stays untouched under raw.created_at
275 # -- the same normalized-plus-native split the *_seconds timing keys use
276 # (ADR 0011). See karr #92 / #117 and GitHub issue #3.
277 47 my @tcs = Langertha::ToolCall->extract( $self->tool_wire_format, $data );
278 return Langertha::Response->new(
279 content => $msg->{content} // '',
280 raw => $data,
281 $data->{model} ? ( model => $data->{model} ) : (),
282 defined $data->{done_reason} ? ( finish_reason => $data->{done_reason} ) : (),
283 $usage ? ( usage => $usage ) : (),
284 $timing ? ( timing => $timing ) : (),
285 defined $data->{created_at} ? ( created => $data->{created_at} ) : (),
286 # Ollama's native /api/chat returns the model's chain-of-thought under
287 # message.thinking (think=true). Surface it onto Response.thinking so the
288 # non-streamed native route matches the OpenAI-compatible path. -- karr k129
289 47 ▶ defined $msg->{thinking} ? ( thinking => $msg->{thinking} ) : (),
Branch: 7 branches
BranchTrueFalseTotal
$$data{'model'} ? : 45 2 47
defined $$data{'done_reason'} ? : 21 26 47
$usage ? : 8 39 47
$timing ? : 7 40 47
defined $$data{'created_at'} ? : 20 27 47
defined $$msg{'thinking'} ? : 1 46 47
@tcs ? : 6 41 47
Condition50%1/2
$$msg{"content"} // ""
l!l
470
MC/DC0%0/1
$$msg{"content"} // ""
$$msg{"content"}
Truth table50%1/2
A
A= $$msg{"content"}
Aresult
11
00
290 @tcs ? ( tool_calls => [ @tcs ] ) : (),
291 );
292 }
293  
294 3 ▶sub tags { $_[0]->tags_request }
Subroutine tags: called CC=1 SCAR=0.0
Pod documented
295 3 ▶sub tags_request {
Subroutine tags_request: called CC=1 SCAR=0.4
Pod undocumented
296 3 my ( $self ) = @_;
297 0 ▶ return $self->generate_request( list => sub { $self->tags_response(shift) } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
298 }
299  
300  
301 0 ▶sub tags_response {
Subroutine tags_response: not called CC=1 SCAR=6.9
Pod undocumented
302 0 my ( $self, $response ) = @_;
303 0 my $data = $self->parse_response($response);
304 0 my @model_list = map { $_->{model} } @{$data->{models}};
305 0 $self->models(\@model_list);
306 0 return $data->{models};
307 }
308  
309 0 ▶sub simple_tags {
Subroutine simple_tags: not called CC=1 SCAR=6.9
Pod documented
310 0 my ( $self ) = @_;
311 0 my $request = $self->tags;
312 0 my $response = $self->user_agent->request($request);
313 0 return $request->response_call->($response);
314 }
315  
316  
317 2 ▶sub ps { $_[0]->ps_request }
Subroutine ps: called CC=1 SCAR=0.0
Pod documented
318 2 ▶sub ps_request {
Subroutine ps_request: called CC=1 SCAR=0.4
Pod undocumented
319 2 my ( $self ) = @_;
320 0 ▶ return $self->generate_request( ps => sub { $self->ps_response(shift) } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
321 }
322  
323  
324 0 ▶sub ps_response {
Subroutine ps_response: not called CC=1 SCAR=6.9
Pod undocumented
325 0 my ( $self, $response ) = @_;
326 0 my $data = $self->parse_response($response);
327 0 return $data->{models};
328 }
329  
330 0 ▶sub simple_ps {
Subroutine simple_ps: not called CC=1 SCAR=6.9
Pod documented
331 0 my ( $self ) = @_;
332 0 my $request = $self->ps;
333 0 my $response = $self->user_agent->request($request);
334 0 return $request->response_call->($response);
335 }
336  
337  
338 # Dynamic model listing (wrapper around simple_tags with caching)
339 0 ▶sub list_models {
Subroutine list_models: not called CC=6 SCAR=37.4
Pod documented
340 0 my ($self, %opts) = @_;
341  
342 # Check cache unless force_refresh requested
343 0 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 0 0 0
344 0 my $cache = $self->_models_cache;
345 0 ▶ if ($cache->{timestamp} && time - $cache->{timestamp} < $self->models_cache_ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl) 0 0 0
Condition0%0/3
$$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl
!ll&&!rl&&r
000
MC/DC0%0/2
$$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl
$$cache{"timestamp"} time - $$cache{"timestamp"} < $self->models_cache_ttl
Truth table0%0/3
A and B
A= $$cache{"timestamp"}B= time - $$cache{"timestamp"} < $self->models_cache_ttl
ABresult
0X0
100
111
346 0 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
347 }
348 }
349  
350 # Fetch from API via simple_tags
351 0 my $models = $self->simple_tags;
352  
353 # Extract IDs and update cache
354 0 my @model_ids = map { $_->{model} } @$models;
355 0 $self->_models_cache({
356 timestamp => time,
357 models => $models,
358 model_ids => \@model_ids,
359 });
360  
361 0 ▶ return $opts{full} ? $models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
362 }
363  
364  
365 9 ▶sub stream_format { 'ndjson' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod undocumented
366  
367 39 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=25 SCAR=36.3
Pod undocumented
368 39 my ( $self, $messages, %extra ) = @_;
369  
370 # Canonical per-request controls (chat_f, karr #46) beat the engine
371 # attributes on a per-key basis; the rest of %extra passes straight through.
372 39 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
831
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
373 # No parallel knob on this wire (parallel_tool_use is cleared): a value the
374 # caller set is only dropped, with the shared carp (karr k241).
375 39 $self->_parallel_tool_calls_kwarg( \%extra, $controls );
376  
377 # No tool_choice field, same rule as chat_request (karr k239).
378 39 $self->_gate_tool_choice(\%extra);
379  
380 # Translate response_format -> Ollama's format parameter, same wire as
381 # chat_request. Ollama accepts either the literal string 'json' or a
382 # JSON-Schema HashRef. A per-request response_format
383 # (chat_stream_realtime_f) beats the engine attribute, and is removed
384 # from the extras either way: Ollama has no response_format field and
385 # would silently ignore it. Fall back to the legacy json_format
386 # attribute when neither is set.
387 my $rf = exists $controls->{response_format}
388 ? delete $controls->{response_format}
389 : exists $extra{response_format}
390 ? delete $extra{response_format}
391 39 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 0 39 39
exists $extra{'response_format'} ? : 3 36 39
$self->has_response_format ? : 1 35 36
392 39 my $format;
393 39 ▶ if ( defined $rf ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rf) 4 35 39
394 4 ▶ my $type = ref($rf) eq 'HASH' ? ( $rf->{type} // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $rf eq 'HASH' ? : 4 0 4
Condition50%1/2
$$rf{"type"} // ""
l!l
40
MC/DC0%0/1
$$rf{"type"} // ""
$$rf{"type"}
Truth table50%1/2
A
A= $$rf{"type"}
Aresult
11
00
395 4 ▶ if ( $type eq 'json_object' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'json_object') { } 1 3 4
elsif ($type eq 'json_schema' and ref $$rf{'json_schema'} eq 'HASH' and ref $$rf{'json_schema'}{'schema'} eq 'HASH') { } 3 0 3
396 1 $format = 'json';
397 }
398 ▶ elsif ( $type eq 'json_schema'
Condition33%2/6
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
!ll&&!rl&&r
003
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH"
!ll&&!rl&&r
003
MC/DC0%0/3
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
$type eq "json_schema" ref $$rf{"json_schema"} eq "HASH" ref $$rf{"json_schema"}{"schema"} eq "HASH"
Truth table25%1/4
A and B and C
A= $type eq "json_schema"B= ref $$rf{"json_schema"} eq "HASH"C= ref $$rf{"json_schema"}{"schema"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
399 && ref( $rf->{json_schema} ) eq 'HASH'
400 && ref( $rf->{json_schema}{schema} ) eq 'HASH' ) {
401 3 $format = $rf->{json_schema}{schema};
402 }
403 }
404 39 ▶ $format = 'json' if !defined $format && $self->json_format;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $format and $self->json_format 1 38 39
Condition100%3/3
not defined $format and $self->json_format
!ll&&!rl&&r
4341
MC/DC100%2/2
not defined $format and $self->json_format
not defined $format $self->json_format
Truth table100%3/3
not(A) and B
A= not defined $formatB= $self->json_format
ABresult
0X0
100
111
405  
406 # reasoning_effort -> top-level `think`, same wire and placement as
407 # chat_request: a sibling of model/messages/stream, never under options
408 # (Ollama silently ignores options.think). Live-probed 2026-09-17 via
409 # ollama.com gpt-oss:20b (k175).
410 39 my @reasoning = $self->_ollama_reasoning_kwargs($controls);
411  
412 0 ▶ return $self->generate_request( chat => sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
413 model => $self->chat_model,
414 messages => $messages,
415 stream => JSON->true,
416 @reasoning,
417 defined $format ? ( format => $format ) : (),
418 defined $self->get_keep_alive ? ( keep_alive => $self->get_keep_alive ) : (),
419 options => {
420 exists $controls->{temperature}
421 ? ( temperature => $controls->{temperature} )
422 : ( $self->has_temperature ? ( temperature => $self->temperature ) : () ),
423 $self->has_context_size ? ( num_ctx => $self->get_context_size ) : (),
424 exists $controls->{max_tokens}
425 ? ( num_predict => $controls->{max_tokens} )
426 : ( $self->get_response_size ? ( num_predict => $self->get_response_size ) : () ),
427 exists $controls->{seed}
428 ? ( seed => $controls->{seed} )
429 : ( $self->has_seed ? ( seed => $self->seed )
430 : $self->randomize_seed ? ( seed => $self->random_seed ) : () ),
431 0 ▶ $extra{options} ? (%{delete $extra{options}}) : (),
Branch: 11 branches
BranchTrueFalseTotal
defined $format ? : 5 33 38
defined $self->get_keep_alive ? : 9 29 38
exists $$controls{'temperature'} ? : 0 38 38
$self->has_temperature ? : 0 38 38
$self->has_context_size ? : 0 38 38
exists $$controls{'max_tokens'} ? : 0 38 38
$self->get_response_size ? : 0 38 38
exists $$controls{'seed'} ? : 0 38 38
$self->has_seed ? : 0 38 38
$self->randomize_seed ? : 0 38 38
$extra{'options'} ? : 0 38 38
432 },
433 %extra,
434 );
435 }
436  
437 25 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=14 SCAR=26.6
Pod undocumented
438 25 my ( $self, $data ) = @_;
439  
440 # Ollama sends {"error":"..."} as an NDJSON line when the runner dies after
441 # the 200; it parsed to an empty, non-final chunk and the stream ended as a
442 # silent, truncated success. -- karr k378
443 25 ▶ if ( ref $data eq 'HASH' && defined $data->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH" and defined $$data{"error"}) 2 23 25
Condition66%2/3
ref $data eq "HASH" and defined $$data{"error"}
!ll&&!rl&&r
0232
MC/DC50%1/2
ref $data eq "HASH" and defined $$data{"error"}
ref $data eq "HASH" defined $$data{"error"}
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= defined $$data{"error"}
ABresult
0X0
100
111
444 croak "".(ref $self)." stream carried an error: "
445 2 ▶ .( $self->_body_error_text( $data->{error} ) // 'no error message' );
Condition50%1/2
$self->_body_error_text($$data{"error"}) // "no error message"
l!l
20
MC/DC0%0/1
$self->_body_error_text($$data{"error"}) // "no error message"
$self->_body_error_text($$data{"error"})
Truth table50%1/2
A
A= $self->_body_error_text($$data{"error"})
Aresult
11
00
446 }
447  
448 23 ▶ my $content = $data->{message}{content} // '';
Condition50%1/2
$$data{"message"}{"content"} // ""
l!l
230
MC/DC0%0/1
$$data{"message"}{"content"} // ""
$$data{"message"}{"content"}
Truth table50%1/2
A
A= $$data{"message"}{"content"}
Aresult
11
00
449 23 ▶ my $is_done = $data->{done} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$$data{'done'} ? : 8 15 23
450  
451 # Native /api/chat with think=true streams the chain-of-thought incrementally
452 # under message.thinking, parallel to message.content -- surface it onto the
453 # chunk so aggregate_thinking reconstructs the same text chat_response lifts on
454 # the non-streaming path. -- karr k129
455 23 my $thinking = $data->{message}{thinking};
456  
457 # Native /api/chat streams message.tool_calls whole, on the chunk where the
458 # call completes (not fragmented). Read it with the same ToolCall->extract
459 # chat_response uses. -- karr k221
460 23 my @tool_calls = Langertha::ToolCall->extract( $self->tool_wire_format, $data );
461  
462 23 require Langertha::Stream::Chunk;
463 return Langertha::Stream::Chunk->new(
464 content => $content,
465 raw => $data,
466 is_final => $is_done,
467 $data->{model} ? (model => $data->{model}) : (),
468 $is_done && $data->{done_reason} ? (finish_reason => $data->{done_reason}) : (),
469 $is_done ? (usage => {
470 $data->{eval_count} ? (completion_tokens => $data->{eval_count}) : (),
471 23 ▶ $data->{prompt_eval_count} ? (prompt_tokens => $data->{prompt_eval_count}) : (),
Branch: 7 branches
BranchTrueFalseTotal
$$data{'model'} ? : 11 12 23
$is_done && $$data{'done_reason'} ? : 8 15 23
$is_done ? : 8 15 23
$$data{'eval_count'} ? : 7 1 8
$$data{'prompt_eval_count'} ? : 4 4 8
defined $thinking ? : 5 18 23
@tool_calls ? : 1 22 23
Condition66%2/3
$is_done and $$data{"done_reason"}
!ll&&!rl&&r
1508
MC/DC50%1/2
$is_done and $$data{"done_reason"}
$is_done $$data{"done_reason"}
Truth table66%2/3
A and B
A= $is_doneB= $$data{"done_reason"}
ABresult
0X0
100
111
472 }) : (),
473 defined $thinking ? ( thinking => $thinking ) : (),
474 @tool_calls ? ( tool_calls => \@tool_calls ) : (),
475 );
476 }
477  
478 # Tool calling support (MCP) is the tag-driven default in Langertha::Role::Tools.
479 42 ▶sub _build_tool_wire_format { 'ollama' }
Subroutine _build_tool_wire_format: called CC=1 SCAR=0.0
480  
481 # Native /api/chat messages carry a string content plus a sibling images array
482 # of raw base64 (docs.ollama.com/api/chat): Role::Chat lifts Content::Image
483 # blocks there (karr k267).
484 36 ▶sub content_format { 'ollama' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod undocumented
485  
486 # Native /api/chat's ChatRequest (api/types.go, main 2026-09-24, v0.34.4) is
487 # model, messages, stream, format, keep_alive, tools, options, think, truncate,
488 # shift, logprobs, top_logprobs: no tool_choice and no parallel knob. The Go
489 # server binds without DisallowUnknownFields, so either field is accepted,
490 # IGNORED and answered 200 -- the caller would believe a tool was forced.
491 # Clear every tool_choice flag and parallel_tool_use (karr k239, k241; ADR
492 # 0002 layer 2); tools_native stays. With tool_choice_named gone, chat_f
493 # reroutes a forced named tool through format=<schema> (ADR 0005), which the
494 # grammar enforces. Mirrors OllamaOpenAI, the same server's /v1 face.
495 226 ▶around engine_capabilities => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
496 226 my ( $orig, $self, @rest ) = @_;
497 226 my $caps = $self->$orig(@rest);
498 226 delete @{$caps}{ qw(
499 tool_choice_auto tool_choice_any tool_choice_none tool_choice_named
500 parallel_tool_use
501 ) };
502 226 return $caps;
503 57 };
504  
505 # image_input (k266, ADR 0019): self-hosted: the served model is launch state
506 # the client cannot see, so no static claim. A layer-3 catch-all rather than a
507 # layer-2 delete, so a fact probed from /api/show can answer per model (ADR 0032).
508 226 ▶sub model_capability_corrections {
Subroutine model_capability_corrections: called CC=1 SCAR=0.0
Pod undocumented
509 226 return ( qr/\A/ => { image_input => 0 } );
510 }
511  
512 16 ▶sub model_metadata_format { 'ollama' }
Subroutine model_metadata_format: called CC=1 SCAR=0.0
Pod undocumented
513 11 ▶sub model_metadata_url {
Subroutine model_metadata_url: called CC=1 SCAR=0.0
Pod undocumented
514 11 my $url = $_[0]->url;
515 11 $url =~ s{/\z}{};
516 11 return $url . '/api/show';
517 }
518  
519 57 __PACKAGE__->meta->make_immutable;
520  
521  
522 57 1;
523  
524 __END__
« blib/lib/Langertha/Role/HTTP.pm ↑ Summary blib/lib/Langertha/Engine/Gemini.pm »