blib/lib/Langertha/Engine/Ollama.pm

filter: Statementstmt 82.5% 156 / 189 Branchbran 80.2% 138 / 172 Conditioncond 67.3% 35 / 52 MC/DCmcdc 51.7% 15 / 29 Subroutinesub 80.8% 38 / 47 Podpod 34.6% 9 / 26 totaltotal 75.9% 391 / 515 CC 108 SCAR 29.5
CC
108
Cov
80%
list_models
42.0
chat_stream_request
41.6
chat_request
31.5
CRAP 19.2
« blib/lib/Langertha/HTTP/Redirect.pm ↑ Summary blib/lib/Langertha/Role/AnthropicCompatible.pm »
1 package Langertha::Engine::Ollama;
2 # ABSTRACT: Ollama API
3 53 our $VERSION = '0.503';
4 53 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 53 ▶use File::ShareDir::ProjectDistDir qw( :all );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 53 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 53 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 53 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 53 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 53 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 53 ▶use Langertha::Reasoning;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 53 ▶use Langertha::Engine::OllamaOpenAI;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 53 extends 'Langertha::Engine::Remote';
16  
17 53 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 159 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 53 has api_key => (
74 is => 'ro',
75 lazy_build => 1,
76 );
77  
78 96 ▶sub _build_api_key {
Subroutine _build_api_key: called CC=1 SCAR=0.0
79 96 return $ENV{LANGERTHA_OLLAMA_API_KEY};
80 }
81  
82  
83 140 ▶sub update_request {
Subroutine update_request: called CC=2 SCAR=6.9
Pod documented
84 140 my ( $self, $request ) = @_;
85 140 my $key = $self->api_key;
86 140 ▶ $request->header('Authorization', 'Bearer '.$key) if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 4 136 140
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 82 ▶sub _build_openapi_operations {
Subroutine _build_openapi_operations: called CC=1 SCAR=0.0
93 82 return use_module('Langertha::Spec::Ollama')->data;
94 }
95  
96  
97 has json_format => (
98 isa => 'Bool',
99 is => 'ro',
100 135 ▶ default => sub {0},
Subroutine __ANON__: called CC=1 SCAR=0.0
101 53 );
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 78 ▶sub chat_request {
Subroutine chat_request: called CC=27 SCAR=34.5
Pod undocumented
141 78 my ( $self, $messages, %extra ) = @_;
142  
143 # Canonical per-request controls (chat_f, karr #46) beat the engine
144 # attributes on a per-key basis; the rest of %extra passes straight through.
145 78 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
1464
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
146 # No parallel knob on this wire (parallel_tool_use is cleared): a value the
147 # caller set is only dropped, with the shared carp (karr k241).
148 78 $self->_parallel_tool_calls_kwarg( \%extra, $controls );
149  
150 # /api/chat has no tool_choice field: the tool_choice_* flags are cleared
151 # below, so the shared rule drops it (none withholds the tools, a forced
152 # choice carps; karr k239).
153 78 $self->_gate_tool_choice(\%extra);
154  
155 # Translate response_format -> Ollama's format parameter. Ollama
156 # accepts either the literal string 'json' or a JSON-Schema HashRef.
157 # A per-request response_format (chat_f) beats the engine attribute,
158 # and is removed from the extras either way: Ollama has no
159 # response_format field and would silently ignore it. Fall back to the
160 # legacy json_format attribute when neither is set.
161 my $rf = exists $controls->{response_format}
162 ? delete $controls->{response_format}
163 : exists $extra{response_format}
164 ? delete $extra{response_format}
165 78 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 6 72 78
exists $extra{'response_format'} ? : 3 69 72
$self->has_response_format ? : 1 68 69
166 78 my $format;
167 78 ▶ if ( defined $rf ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rf) 10 68 78
168 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
169 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
170 1 $format = 'json';
171 }
172 ▶ 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
173 && ref( $rf->{json_schema} ) eq 'HASH'
174 && ref( $rf->{json_schema}{schema} ) eq 'HASH' ) {
175 9 $format = $rf->{json_schema}{schema};
176 }
177 }
178 78 ▶ $format = 'json' if !defined $format && $self->json_format;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $format and $self->json_format 1 77 78
Condition100%3/3
not defined $format and $self->json_format
!ll&&!rl&&r
10671
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
179  
180 # reasoning_effort -> the TOP-LEVEL `think` field, a sibling of
181 # model/messages/stream — NOT under options. Live-probed 2026-09-17 via
182 # ollama.com gpt-oss:20b: `think` inside options is silently ignored (low and
183 # max both yield the default ~180-220 thinking chars), while top-level `think`
184 # grades cleanly (low ~25-47, max ~207-402). Ollama does not compose
185 # ReasoningEffort, so serialize directly via the value object rather than
186 # advertising the capability; to_ollama emits (think => <boolean|level>).
187 my @reasoning = exists $controls->{reasoning_effort}
188 ? Langertha::Reasoning->new(
189 effort => $controls->{reasoning_effort},
190 78 ▶ ( $self->can('chat_model') ? ( model => $self->chat_model ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
exists $$controls{'reasoning_effort'} ? : 5 73 78
$self->can('chat_model') ? : 5 0 5
191 )->to('ollama')
192 : ();
193  
194 18 ▶ return $self->generate_request( chat => sub { $self->chat_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
195 model => $self->chat_model,
196 messages => $messages,
197 stream => JSON->false,
198 @reasoning,
199 defined $format ? ( format => $format ) : (),
200 defined $self->get_keep_alive ? ( keep_alive => $self->get_keep_alive ) : (),
201 options => {
202 exists $controls->{temperature}
203 ? ( temperature => $controls->{temperature} )
204 : ( $self->has_temperature ? ( temperature => $self->temperature ) : () ),
205 $self->has_context_size ? ( num_ctx => $self->get_context_size ) : (),
206 exists $controls->{max_tokens}
207 ? ( num_predict => $controls->{max_tokens} )
208 : ( $self->get_response_size ? ( num_predict => $self->get_response_size ) : () ),
209 exists $controls->{seed}
210 ? ( seed => $controls->{seed} )
211 : ( $self->has_seed ? ( seed => $self->seed )
212 : $self->randomize_seed ? ( seed => $self->random_seed ) : () ),
213 78 ▶ $extra{options} ? (%{delete $extra{options}}) : (),
Branch: 11 branches
BranchTrueFalseTotal
defined $format ? : 11 67 78
defined $self->get_keep_alive ? : 10 68 78
exists $$controls{'temperature'} ? : 4 74 78
$self->has_temperature ? : 1 73 74
$self->has_context_size ? : 1 77 78
exists $$controls{'max_tokens'} ? : 3 75 78
$self->get_response_size ? : 0 75 75
exists $$controls{'seed'} ? : 2 76 78
$self->has_seed ? : 0 76 76
$self->randomize_seed ? : 0 76 76
$extra{'options'} ? : 0 78 78
214 },
215 %extra,
216 );
217 }
218  
219 50 ▶sub chat_response {
Subroutine chat_response: called CC=19 SCAR=29.4
220 50 my ( $self, $response ) = @_;
221 50 my $data = $self->parse_response($response);
222 47 my $msg = $data->{message};
223  
224 47 my $usage = {};
225 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
226 47 ▶ $usage->{completion_tokens} = $data->{eval_count} if $data->{eval_count};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{"eval_count"} 8 39 47
227 47 ▶ $usage = undef unless %$usage;
Branch: 1 branch
BranchTrueFalseTotal
unless %$usage 39 8 47
228  
229 47 my $timing = {};
230 47 for my $k (qw( total_duration load_duration prompt_eval_duration eval_duration )) {
231 188 ▶ $timing->{$k} = $data->{$k} if $data->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if $$data{$k} 28 160 188
232 }
233 # Ollama reports the four native durations in nanoseconds. Mirror them
234 # as *_seconds (Float, seconds) so Langertha::Response.ttft_seconds /
235 # total_seconds and downstream observability (Langfuse, Prometheus
236 # scrapers) have a consistent unit. The original *_duration keys are
237 # preserved verbatim for backward compatibility.
238 47 ▶ my $ns_to_s = sub { $_[0] * 1e-9 };
Subroutine __ANON__: called CC=1 SCAR=0.0
239 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
240 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
241 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
242 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
243 47 ▶ $timing = undef unless %$timing;
Branch: 1 branch
BranchTrueFalseTotal
unless %$timing 40 7 47
244  
245 # Ollama stamps every response with an RFC3339 string carrying nanoseconds
246 # ("2026-02-22T04:00:45.027209927Z"). It is handed over verbatim: normalizing
247 # it is Langertha::Moment->from_wire's job, reached through
248 # Langertha::Response's BUILDARGS, which also parses the epoch seconds some
249 # Ollama-compatible shims send instead and drops a stamp it cannot read (the
250 # "0001-01-01T00:00:00Z" zero-value sentinel included) rather than failing
251 # the whole response. The native string stays untouched under raw.created_at
252 # -- the same normalized-plus-native split the *_seconds timing keys use
253 # (ADR 0011). See karr #92 / #117 and GitHub issue #3.
254 47 my @tcs = Langertha::ToolCall->extract( $self->tool_wire_format, $data );
255 return Langertha::Response->new(
256 content => $msg->{content} // '',
257 raw => $data,
258 $data->{model} ? ( model => $data->{model} ) : (),
259 defined $data->{done_reason} ? ( finish_reason => $data->{done_reason} ) : (),
260 $usage ? ( usage => $usage ) : (),
261 $timing ? ( timing => $timing ) : (),
262 defined $data->{created_at} ? ( created => $data->{created_at} ) : (),
263 # Ollama's native /api/chat returns the model's chain-of-thought under
264 # message.thinking (think=true). Surface it onto Response.thinking so the
265 # non-streamed native route matches the OpenAI-compatible path. -- karr k129
266 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
267 @tcs ? ( tool_calls => [ @tcs ] ) : (),
268 );
269 }
270  
271 3 ▶sub tags { $_[0]->tags_request }
Subroutine tags: called CC=1 SCAR=0.0
Pod documented
272 3 ▶sub tags_request {
Subroutine tags_request: called CC=1 SCAR=0.4
Pod undocumented
273 3 my ( $self ) = @_;
274 3 ▶ return $self->generate_request( list => sub { $self->tags_response(shift) } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
275 }
276  
277  
278 0 ▶sub tags_response {
Subroutine tags_response: not called CC=1 SCAR=6.9
Pod undocumented
279 0 my ( $self, $response ) = @_;
280 0 my $data = $self->parse_response($response);
281 0 my @model_list = map { $_->{model} } @{$data->{models}};
282 0 $self->models(\@model_list);
283 0 return $data->{models};
284 }
285  
286 0 ▶sub simple_tags {
Subroutine simple_tags: not called CC=1 SCAR=6.9
Pod documented
287 0 my ( $self ) = @_;
288 0 my $request = $self->tags;
289 0 my $response = $self->user_agent->request($request);
290 0 return $request->response_call->($response);
291 }
292  
293  
294 2 ▶sub ps { $_[0]->ps_request }
Subroutine ps: called CC=1 SCAR=0.0
Pod documented
295 2 ▶sub ps_request {
Subroutine ps_request: called CC=1 SCAR=0.4
Pod undocumented
296 2 my ( $self ) = @_;
297 2 ▶ return $self->generate_request( ps => sub { $self->ps_response(shift) } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
298 }
299  
300  
301 0 ▶sub ps_response {
Subroutine ps_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 return $data->{models};
305 }
306  
307 0 ▶sub simple_ps {
Subroutine simple_ps: not called CC=1 SCAR=6.9
Pod documented
308 0 my ( $self ) = @_;
309 0 my $request = $self->ps;
310 0 my $response = $self->user_agent->request($request);
311 0 return $request->response_call->($response);
312 }
313  
314  
315 # Dynamic model listing (wrapper around simple_tags with caching)
316 0 ▶sub list_models {
Subroutine list_models: not called CC=6 SCAR=37.4
Pod documented
317 0 my ($self, %opts) = @_;
318  
319 # Check cache unless force_refresh requested
320 0 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 0 0 0
321 0 my $cache = $self->_models_cache;
322 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
323 0 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
324 }
325 }
326  
327 # Fetch from API via simple_tags
328 0 my $models = $self->simple_tags;
329  
330 # Extract IDs and update cache
331 0 my @model_ids = map { $_->{model} } @$models;
332 0 $self->_models_cache({
333 timestamp => time,
334 models => $models,
335 model_ids => \@model_ids,
336 });
337  
338 0 ▶ return $opts{full} ? $models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
339 }
340  
341  
342 7 ▶sub stream_format { 'ndjson' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod undocumented
343  
344 34 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=27 SCAR=37.3
Pod undocumented
345 34 my ( $self, $messages, %extra ) = @_;
346  
347 # Canonical per-request controls (chat_f, karr #46) beat the engine
348 # attributes on a per-key basis; the rest of %extra passes straight through.
349 34 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
331
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
350 # No parallel knob on this wire (parallel_tool_use is cleared): a value the
351 # caller set is only dropped, with the shared carp (karr k241).
352 34 $self->_parallel_tool_calls_kwarg( \%extra, $controls );
353  
354 # No tool_choice field, same rule as chat_request (karr k239).
355 34 $self->_gate_tool_choice(\%extra);
356  
357 # Translate response_format -> Ollama's format parameter, same wire as
358 # chat_request. Ollama accepts either the literal string 'json' or a
359 # JSON-Schema HashRef. A per-request response_format
360 # (chat_stream_realtime_f) beats the engine attribute, and is removed
361 # from the extras either way: Ollama has no response_format field and
362 # would silently ignore it. Fall back to the legacy json_format
363 # attribute when neither is set.
364 my $rf = exists $controls->{response_format}
365 ? delete $controls->{response_format}
366 : exists $extra{response_format}
367 ? delete $extra{response_format}
368 34 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 0 34 34
exists $extra{'response_format'} ? : 3 31 34
$self->has_response_format ? : 1 30 31
369 34 my $format;
370 34 ▶ if ( defined $rf ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rf) 4 30 34
371 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
372 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
373 1 $format = 'json';
374 }
375 ▶ 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
376 && ref( $rf->{json_schema} ) eq 'HASH'
377 && ref( $rf->{json_schema}{schema} ) eq 'HASH' ) {
378 3 $format = $rf->{json_schema}{schema};
379 }
380 }
381 34 ▶ $format = 'json' if !defined $format && $self->json_format;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $format and $self->json_format 1 33 34
Condition100%3/3
not defined $format and $self->json_format
!ll&&!rl&&r
4291
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
382  
383 # reasoning_effort -> top-level `think`, same wire and placement as
384 # chat_request: a sibling of model/messages/stream, never under options
385 # (Ollama silently ignores options.think). Live-probed 2026-09-17 via
386 # ollama.com gpt-oss:20b (k175).
387 my @reasoning = exists $controls->{reasoning_effort}
388 ? Langertha::Reasoning->new(
389 effort => $controls->{reasoning_effort},
390 34 ▶ ( $self->can('chat_model') ? ( model => $self->chat_model ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
exists $$controls{'reasoning_effort'} ? : 2 32 34
$self->can('chat_model') ? : 2 0 2
391 )->to('ollama')
392 : ();
393  
394 0 ▶ return $self->generate_request( chat => sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
395 model => $self->chat_model,
396 messages => $messages,
397 stream => JSON->true,
398 @reasoning,
399 defined $format ? ( format => $format ) : (),
400 defined $self->get_keep_alive ? ( keep_alive => $self->get_keep_alive ) : (),
401 options => {
402 exists $controls->{temperature}
403 ? ( temperature => $controls->{temperature} )
404 : ( $self->has_temperature ? ( temperature => $self->temperature ) : () ),
405 $self->has_context_size ? ( num_ctx => $self->get_context_size ) : (),
406 exists $controls->{max_tokens}
407 ? ( num_predict => $controls->{max_tokens} )
408 : ( $self->get_response_size ? ( num_predict => $self->get_response_size ) : () ),
409 exists $controls->{seed}
410 ? ( seed => $controls->{seed} )
411 : ( $self->has_seed ? ( seed => $self->seed )
412 : $self->randomize_seed ? ( seed => $self->random_seed ) : () ),
413 34 ▶ $extra{options} ? (%{delete $extra{options}}) : (),
Branch: 11 branches
BranchTrueFalseTotal
defined $format ? : 5 29 34
defined $self->get_keep_alive ? : 9 25 34
exists $$controls{'temperature'} ? : 0 34 34
$self->has_temperature ? : 0 34 34
$self->has_context_size ? : 0 34 34
exists $$controls{'max_tokens'} ? : 0 34 34
$self->get_response_size ? : 0 34 34
exists $$controls{'seed'} ? : 0 34 34
$self->has_seed ? : 0 34 34
$self->randomize_seed ? : 0 34 34
$extra{'options'} ? : 0 34 34
414 },
415 %extra,
416 );
417 }
418  
419 20 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=11 SCAR=24.1
Pod undocumented
420 20 my ( $self, $data ) = @_;
421  
422 20 ▶ my $content = $data->{message}{content} // '';
Condition50%1/2
$$data{"message"}{"content"} // ""
l!l
200
MC/DC0%0/1
$$data{"message"}{"content"} // ""
$$data{"message"}{"content"}
Truth table50%1/2
A
A= $$data{"message"}{"content"}
Aresult
11
00
423 20 ▶ my $is_done = $data->{done} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$$data{'done'} ? : 7 13 20
424  
425 # Native /api/chat with think=true streams the chain-of-thought incrementally
426 # under message.thinking, parallel to message.content -- surface it onto the
427 # chunk so aggregate_thinking reconstructs the same text chat_response lifts on
428 # the non-streaming path. -- karr k129
429 20 my $thinking = $data->{message}{thinking};
430  
431 # Native /api/chat streams message.tool_calls whole, on the chunk where the
432 # call completes (not fragmented). Read it with the same ToolCall->extract
433 # chat_response uses. -- karr k221
434 20 my @tool_calls = Langertha::ToolCall->extract( $self->tool_wire_format, $data );
435  
436 20 require Langertha::Stream::Chunk;
437 return Langertha::Stream::Chunk->new(
438 content => $content,
439 raw => $data,
440 is_final => $is_done,
441 $data->{model} ? (model => $data->{model}) : (),
442 $is_done && $data->{done_reason} ? (finish_reason => $data->{done_reason}) : (),
443 $is_done ? (usage => {
444 $data->{eval_count} ? (completion_tokens => $data->{eval_count}) : (),
445 20 ▶ $data->{prompt_eval_count} ? (prompt_tokens => $data->{prompt_eval_count}) : (),
Branch: 7 branches
BranchTrueFalseTotal
$$data{'model'} ? : 11 9 20
$is_done && $$data{'done_reason'} ? : 7 13 20
$is_done ? : 7 13 20
$$data{'eval_count'} ? : 7 0 7
$$data{'prompt_eval_count'} ? : 4 3 7
defined $thinking ? : 5 15 20
@tool_calls ? : 1 19 20
Condition66%2/3
$is_done and $$data{"done_reason"}
!ll&&!rl&&r
1307
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
446 }) : (),
447 defined $thinking ? ( thinking => $thinking ) : (),
448 @tool_calls ? ( tool_calls => \@tool_calls ) : (),
449 );
450 }
451  
452 # Tool calling support (MCP) is the tag-driven default in Langertha::Role::Tools.
453 40 ▶sub _build_tool_wire_format { 'ollama' }
Subroutine _build_tool_wire_format: called CC=1 SCAR=0.0
454  
455 # Native /api/chat messages carry a string content plus a sibling images array
456 # of raw base64 (docs.ollama.com/api/chat): Role::Chat lifts Content::Image
457 # blocks there (karr k267).
458 36 ▶sub content_format { 'ollama' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod undocumented
459  
460 # Native /api/chat's ChatRequest (api/types.go, main 2026-09-24, v0.34.4) is
461 # model, messages, stream, format, keep_alive, tools, options, think, truncate,
462 # shift, logprobs, top_logprobs: no tool_choice and no parallel knob. The Go
463 # server binds without DisallowUnknownFields, so either field is accepted,
464 # IGNORED and answered 200 -- the caller would believe a tool was forced.
465 # Clear every tool_choice flag and parallel_tool_use (karr k239, k241; ADR
466 # 0002 layer 2); tools_native stays. With tool_choice_named gone, chat_f
467 # reroutes a forced named tool through format=<schema> (ADR 0005), which the
468 # grammar enforces. Mirrors OllamaOpenAI, the same server's /v1 face.
469 216 ▶around engine_capabilities => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
470 216 my ( $orig, $self, @rest ) = @_;
471 216 my $caps = $self->$orig(@rest);
472 216 delete @{$caps}{ qw(
473 tool_choice_auto tool_choice_any tool_choice_none tool_choice_named
474 parallel_tool_use
475 ) };
476 216 return $caps;
477 53 };
478  
479 # image_input (k266, ADR 0019): self-hosted: the served model is launch state
480 # the client cannot see, so no static claim. A layer-3 catch-all rather than a
481 # layer-2 delete, so a fact probed from /api/show can answer per model (ADR 0032).
482 216 ▶sub model_capability_corrections {
Subroutine model_capability_corrections: called CC=1 SCAR=0.0
Pod undocumented
483 216 return ( qr/\A/ => { image_input => 0 } );
484 }
485  
486 16 ▶sub model_metadata_format { 'ollama' }
Subroutine model_metadata_format: called CC=1 SCAR=0.0
Pod undocumented
487 11 ▶sub model_metadata_url {
Subroutine model_metadata_url: called CC=1 SCAR=0.0
Pod undocumented
488 11 my $url = $_[0]->url;
489 11 $url =~ s{/\z}{};
490 11 return $url . '/api/show';
491 }
492  
493 53 __PACKAGE__->meta->make_immutable;
494  
495  
496 53 1;
497  
498 __END__
499  
500 =pod
501  
502 =encoding UTF-8
503  
504 =head1 NAME
505  
506 Langertha::Engine::Ollama - Ollama API
507  
508 =head1 VERSION
509  
510 version 0.503
511  
512 =head1 SYNOPSIS
513  
514 use Langertha::Engine::Ollama;
515  
516 my $ollama = Langertha::Engine::Ollama->new(
517 url => $ENV{OLLAMA_URL},
518 model => 'llama3.3',
519 system_prompt => 'You are a helpful assistant',
520 context_size => 2048,
521 temperature => 0.5,
522 );
523  
524 print $ollama->simple_chat('Say something nice');
525  
526 my $vector = $ollama->simple_embedding($content);
527 # async: await $ollama->simple_embedding_f($content)
528  
529 # Get OpenAI-compatible API access to Ollama
530 my $ollama_openai = $ollama->openai;
531  
532 # List available models
533 my $models = $ollama->simple_tags;
534  
535 # Show running models
536 my $running = $ollama->simple_ps;
537  
538 =head1 DESCRIPTION
539  
540 Provides access to Ollama, which runs large language models locally. Ollama
541 supports many popular open-source models including C<llama3.3> (default),
542 C<qwen2.5>, C<deepseek-coder-v2>, C<mixtral>, and C<mxbai-embed-large>
543 (default embedding model).
544  
545 Supports chat, embeddings, streaming, MCP tool calling (OpenAI-compatible
546 format), and an OpenAI-compatible API via L</openai>. Not all models support
547 tool calling; known working models include C<qwen3:8b> and C<llama3.2:3b>.
548  
549 Authentication is optional. A local server needs none; Ollama Cloud
550 (C<https://ollama.com>) serves the same native dialect but requires a
551 bearer token — set L</api_key> or C<LANGERTHA_OLLAMA_API_KEY>:
552  
553 my $cloud = Langertha::Engine::Ollama->new(
554 url => 'https://ollama.com',
555 api_key => $ENV{LANGERTHA_OLLAMA_API_KEY},
556 model => 'gpt-oss:120b',
557 );
558  
559 For Hermes-format tool calling in models without API-level tool support,
560 compose L<Langertha::Role::HermesTools>. See L<Langertha::Role::HermesTools>
561 for details.
562  
563 B<THIS API IS WORK IN PROGRESS>
564  
565 =head2 openai
566  
567 my $oai = $ollama->openai;
568 my $oai = $ollama->openai(model => 'different_model');
569  
570 Returns a L<Langertha::Engine::OllamaOpenAI> instance configured for Ollama's
571 C</v1> OpenAI-compatible endpoint, inheriting the current model, embedding
572 model, API key, system prompt, and temperature settings (and
573 L<Langertha::Role::HTTP/connect_address> while the url stays on its host). Supports streaming,
574 embeddings, and MCP tool calling.
575  
576 =head2 new_openai
577  
578 my $oai = Langertha::Engine::Ollama->new_openai(
579 url => 'http://localhost:11434',
580 model => 'llama3.3',
581 tools => [ $mcp ],
582 );
583  
584 Class method. Constructs a native Ollama engine and immediately returns an
585 L<Langertha::Engine::OllamaOpenAI> instance from its C<openai()> method.
586 Every argument the OllamaOpenAI engine accepts (C<mcp_servers>,
587 C<tool_max_iterations>, C<response_format>, C<reasoning_effort>, ...) is
588 passed on to it; C<url> gets the C</v1> suffix. The optional C<tools> list
589 names MCP clients and is added to C<mcp_servers>. Native-only arguments
590 (C<keep_alive>, C<seed>, C<context_size>) have no C</v1> counterpart and
591 are not passed on.
592  
593 =head2 api_key
594  
595 Optional bearer token. A local Ollama server needs none; Ollama Cloud
596 (C<https://ollama.com>) rejects unauthenticated requests with HTTP 401.
597 If not provided, reads from C<LANGERTHA_OLLAMA_API_KEY>. When undefined,
598 no C<Authorization> header is sent.
599  
600 =head2 update_request
601  
602 $ollama->update_request($http_request);
603  
604 Adds C<Authorization: Bearer {api_key}> to outgoing requests when an API
605 key is configured. Skipped entirely when C<api_key> is C<undef>, keeping
606 unauthenticated local servers working.
607  
608 =head2 json_format
609  
610 When set to a true value, passes C<format => 'json'> to the Ollama API,
611 requesting JSON-formatted output from the model. Defaults to C<0>.
612  
613 =head2 tags
614  
615 my $request = $ollama->tags;
616  
617 Returns an HTTP request object for the Ollama C<GET /api/tags> endpoint.
618 Execute it with C<simple_tags> or pass it to an async HTTP client.
619  
620 =head2 simple_tags
621  
622 my $models = $ollama->simple_tags;
623 # Returns: [{name => 'llama3.3', model => 'llama3.3', ...}, ...]
624  
625 Synchronously fetches and returns the list of locally available models from
626 the Ollama C</api/tags> endpoint. Also updates the engine's C<models> list.
627  
628 =head2 ps
629  
630 my $request = $ollama->ps;
631  
632 Returns an HTTP request object for the Ollama C<GET /api/ps> endpoint which
633 lists currently loaded (running) models.
634  
635 =head2 simple_ps
636  
637 my $running = $ollama->simple_ps;
638 # Returns: [{name => 'llama3.3', ...}, ...]
639  
640 Synchronously fetches and returns the list of models currently loaded in
641 Ollama's memory from the C</api/ps> endpoint.
642  
643 =head2 list_models
644  
645 my $model_ids = $ollama->list_models;
646 my $models = $ollama->list_models(full => 1);
647 my $models = $ollama->list_models(force_refresh => 1);
648  
649 Fetches locally available models from Ollama via L</simple_tags> with caching.
650 Returns an ArrayRef of model name strings by default, or full model objects
651 when C<full => 1> is passed. Results are cached for C<models_cache_ttl>
652 seconds (default: 3600).
653  
654 =head1 SEE ALSO
655  
656 =over
657  
658 =item * L<https://ollama.com/library> - Ollama model library
659  
660 =item * L<https://github.com/ollama/ollama> - Ollama project
661  
662 =item * L<Langertha::Engine::OllamaOpenAI> - OpenAI-compatible Ollama access via L</openai>
663  
664 =item * L<Langertha::Role::Tools> - MCP tool calling interface
665  
666 =item * L<Langertha::Role::Seed> - Seed for reproducible outputs (composed by this engine)
667  
668 =item * L<Langertha::Role::ContextSize> - Context window size (composed by this engine)
669  
670 =back
671  
672 =head1 SUPPORT
673  
674 =head2 Issues
675  
676 Please report bugs and feature requests on GitHub at
677 L<https://github.com/Getty/langertha/issues>.
678  
679 =head2 IRC
680  
681 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
682  
683 =head1 CONTRIBUTING
684  
685 Contributions are welcome! Please fork the repository and submit a pull request.
686  
687 =head1 AUTHOR
688  
689 Torsten Raudssus <getty@cpan.org>
690  
691 =head1 COPYRIGHT AND LICENSE
692  
693 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
694  
695 This is free software; you can redistribute it and/or modify it under
696 the same terms as the Perl 5 programming language system itself.
697  
698 =cut
« blib/lib/Langertha/HTTP/Redirect.pm ↑ Summary blib/lib/Langertha/Role/AnthropicCompatible.pm »