blib/lib/Langertha/Role/Capabilities.pm

filter: Statementstmt 98.7% 153 / 155 Branchbran 90.2% 65 / 72 Conditioncond 75.5% 34 / 45 MC/DCmcdc 58.3% 14 / 24 Subroutinesub 90.9% 20 / 22 Podpod 100% 10 / 10 totaltotal 90.2% 296 / 328 CC 63 SCAR 26.1
CC
63
Cov
93%
probe_model_capabilities_f
28.5
_apply_learned_model_capabilities
12.2
_apply_model_capability_corrections
9.0
CRAP 13.6
« blib/lib/Langertha/Role/ReasoningEffort.pm ↑ Summary blib/lib/Langertha/CachedContent.pm »
1 package Langertha::Role::Capabilities;
2 # ABSTRACT: Engine-capability registry derived from composed roles
3 180 our $VERSION = '0.503';
4 180 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 180 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 180 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 180 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 180 ▶use Langertha::ModelProbe;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10  
11 # Role-name => list of capability flag names that role contributes.
12 # Plus implicit:
13 # chat -> simple_chat works (Role::Chat is composed)
14 # streaming -> chat_stream_request is wired up (Role::Streaming)
15 # tools_native -> Role::Tools (the named flags below come too)
16 # tools_hermes -> Role::HermesTools
17 # ... see %ROLE_TO_CAPS below.
18 # Every Langertha::Role::* is on one of two axes (ADR 0016 decision 2):
19 # a capability (an entry here) or envelope/infrastructure (the allowlist
20 # in t/78_capability_registry.t). That guard fails on a role in neither,
21 # so a new role cannot quietly skip the decision.
22 180 my %ROLE_TO_CAPS = (
23 'Langertha::Role::Chat' => [qw( chat )],
24 'Langertha::Role::Streaming' => [qw( streaming )],
25 'Langertha::Role::Tools' => [qw(
26 tools_native tool_choice_auto tool_choice_any tool_choice_none tool_choice_named
27 )],
28 'Langertha::Role::HermesTools' => [qw( tools_hermes )],
29 'Langertha::Role::ResponseFormat' => [qw(
30 response_format_json_object response_format_json_schema
31 )],
32 'Langertha::Role::Embedding' => [qw( embedding )],
33 'Langertha::Role::Transcription' => [qw( transcription )],
34 'Langertha::Role::ImageGeneration' => [qw( image_generation )],
35 'Langertha::Role::Temperature' => [qw( temperature )],
36 'Langertha::Role::ReasoningEffort' => [qw( reasoning_effort )],
37 'Langertha::Role::PromptCache' => [qw( prompt_cache prompt_cache_key )],
38 'Langertha::Role::CachedContent' => [qw( cached_content )],
39 'Langertha::Role::Seed' => [qw( seed )],
40 'Langertha::Role::ContextSize' => [qw( context_size )],
41 'Langertha::Role::ResponseSize' => [qw( response_size )],
42 'Langertha::Role::SystemPrompt' => [qw( system_prompt )],
43 'Langertha::Role::KeepAlive' => [qw( keep_alive )],
44 'Langertha::Role::ParallelToolUse' => [qw( parallel_tool_use )],
45 'Langertha::Role::Runtime::MetricsPoll' => [qw( runtime_metrics )],
46 'Langertha::Role::RuntimeKnobs' => [qw( prefix_caching )],
47 'Langertha::Role::ServerTools' => [qw( server_tools )],
48 'Langertha::Role::ImageInput' => [qw( image_input )],
49 );
50  
51 8386 ▶sub engine_capabilities {
Subroutine engine_capabilities: called CC=4 SCAR=13.9
Pod documented
52 8386 my ($self) = @_;
53 8386 my %caps;
54 8386 for my $role ( keys %ROLE_TO_CAPS ) {
55 184492 ▶ next unless $self->does($role);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->does($role) 81921 102571 184492
56 102571 $caps{$_} = 1 for @{ $ROLE_TO_CAPS{$role} };
57 }
58 # Layer 3 (ADR 0002 amendment, ADR 0019): per-model refinement.
59 # The tool / structured-output wire reality is often per-MODEL, not
60 # per-engine (kimi-k3 forbids a forced named tool while its K2.x siblings
61 # allow it; deepseek-reasoner clamps differ from deepseek-chat). Engines
62 # declare a model-id/pattern -> {cap => 0|1} table in
63 # model_capability_corrections; it refines the role-derived base for the
64 # currently selected chat_model. Engine-WIDE corrections stay in
65 # `around engine_capabilities` (the outer endpoint-reality gate, layer 2).
66 # The wire set (layer 1) before any model-scoped refinement: a learned fact
67 # can re-assert only a flag the composed roles grant (ADR 0032).
68 8386 my %wire = %caps;
69 8386 $self->_apply_model_capability_corrections(\%caps);
70 # Learned layer (ADR 0032): facts the engine read from the provider's own
71 # model metadata (probe_model_capabilities_f), for this chat_model. They
72 # run after the static per-model table, so for a model the probe reported,
73 # the provider's statement beats the static default in both directions.
74 # Empty until the caller probes: supports() never does network I/O.
75 8386 $self->_apply_learned_model_capabilities( \%caps, \%wire );
76 8386 return \%caps;
77 }
78  
79 # Default: no per-model corrections. Engines override with a declarative,
80 # ordered list of ( $matcher => \%overrides ) pairs — see the =method below.
81 1880 ▶sub model_capability_corrections { return () }
Subroutine model_capability_corrections: called CC=1 SCAR=0.0
Pod documented
82  
83 8386 ▶sub _apply_model_capability_corrections {
Subroutine _apply_model_capability_corrections: called CC=9 SCAR=22.0
84 8386 my ( $self, $caps ) = @_;
85 8386 my @corrections = $self->model_capability_corrections;
86 8386 ▶ return unless @corrections;
Branch: 1 branch
BranchTrueFalseTotal
unless @corrections 1884 6502 8386
87 # chat_model is the model that actually carries tools / tool_choice /
88 # response_format on the wire (Role::Chat); guard for the rare consumer
89 # of engine_capabilities that has no model surface at all.
90 # An empty or undef chat_model is matched as '' rather than skipped, so a
91 # default-deny catch-all row (qr/\A/, Engine::MiniMax, ADR 0019 k209 Update)
92 # holds even for model => ''; every family row needs a real id to match.
93 6502 ▶ return unless $self->can('chat_model');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_model") 0 6502 6502
94 6502 ▶ my $model = $self->_capability_model // '';
Condition100%2/2
$self->_capability_model // ""
l!l
64993
MC/DC100%1/1
$self->_capability_model // ""
$self->_capability_model
Truth table100%2/2
A
A= $self->_capability_model
Aresult
11
00
95 6502 ▶ while ( @corrections >= 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@corrections >= 2) 34900 6502 41402
96 34900 my ( $matcher, $overrides ) = splice @corrections, 0, 2;
97 34900 ▶ my $hit = ref $matcher eq 'Regexp' ? ( $model =~ $matcher )
Branch: 1 branch
BranchTrueFalseTotal
ref $matcher eq 'Regexp' ? : 31714 3186 34900
98 : ( $model eq $matcher );
99 34900 ▶ next unless $hit;
Branch: 1 branch
BranchTrueFalseTotal
unless $hit 27835 7065 34900
100 # Later matching entries win on a shared flag. A true value asserts the
101 # capability, a false value clears it.
102 7065 for my $cap ( keys %$overrides ) {
103 8610 ▶ if ( $overrides->{$cap} ) { $caps->{$cap} = 1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($overrides->{$cap}) { } 1951 6659 8610
104 6659 else { delete $caps->{$cap} }
105 }
106 }
107 6502 return;
108 }
109  
110 # The model the capability picture is evaluated for. An engine without a
111 # default model (OpenRouter, OllamaOpenAI, Groq) croaks when chat_model is
112 # built with no model configured. For the capability picture that means "no
113 # model", which the table walk matches as '' (ADR 0019 k209 rule), not an
114 # error of supports() (ADR 0032).
115 6648 ▶sub _capability_model {
Subroutine _capability_model: called CC=3 SCAR=11.0
116 6648 my ( $self ) = @_;
117 6648 ▶ return undef unless $self->can('chat_model');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_model") 0 6648 6648
118 6648 my $model;
119 # supports() must not leave the chat_model croak behind in the caller's $@.
120 6648 local $@;
121 6648 my $ok = eval { $model = $self->chat_model; 1 };
122 6648 ▶ return $ok ? $model : undef;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 6644 4 6648
123 }
124  
125 has _learned_model_capabilities => (
126 is => 'ro',
127 isa => 'HashRef',
128 3917 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
129 180 writer => '_set_learned_model_capabilities',
130 init_arg => undef,
131 );
132  
133 8386 ▶sub _apply_learned_model_capabilities {
Subroutine _apply_learned_model_capabilities: called CC=11 SCAR=25.0
134 8386 my ( $self, $caps, $wire ) = @_;
135 8386 my $learned = $self->_learned_model_capabilities;
136 8386 ▶ return unless %$learned;
Branch: 1 branch
BranchTrueFalseTotal
unless %$learned 8327 59 8386
137 59 my $model = $self->_capability_model;
138 59 ▶ return unless defined $model && !ref $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and not ref $model and length $model 0 59 59
Condition33%2/6
defined $model and not ref $model and length $model
!ll&&!rl&&r
0059
defined $model and not ref $model
!ll&&!rl&&r
0059
MC/DC0%0/3
defined $model and not ref $model and length $model
defined $model not ref $model length $model
Truth table25%1/4
A and not(B) and C
A= defined $modelB= not ref $modelC= length $model
ABCresult
0XX0
10X0
1100
1111
139 # Exact id first, then the format's equivalent spellings (Ollama's implicit
140 # :latest tag, OpenRouter's :variant suffixes), see ModelProbe->lookup_ids.
141 59 my $format = $self->model_metadata_format;
142 59 ▶ my @ids = defined $format && Langertha::ModelProbe->is_known_format($format)
Branch: 1 branch
BranchTrueFalseTotal
defined $format && 'Langertha::ModelProbe'->is_known_format($format) ? : 59 0 59
Condition33%1/3
defined $format and "Langertha::ModelProbe"->is_known_format($format)
!ll&&!rl&&r
0059
MC/DC0%0/2
defined $format and "Langertha::ModelProbe"->is_known_format($format)
defined $format "Langertha::ModelProbe"->is_known_format($format)
Truth table33%1/3
A and B
A= defined $formatB= "Langertha::ModelProbe"->is_known_format($format)
ABresult
0X0
100
111
143 ? Langertha::ModelProbe->lookup_ids( $format, $model ) : ( $model );
144 59 my ($facts) = grep { ref $_ eq 'HASH' } map { $learned->{$_} } @ids;
145 59 ▶ return unless $facts;
Branch: 1 branch
BranchTrueFalseTotal
unless $facts 5 54 59
146 54 for my $cap ( keys %$facts ) {
147 54 ▶ if ( $facts->{$cap} ) { $caps->{$cap} = 1 if $wire->{$cap} }
Branch: 2 branches
BranchTrueFalseTotal
if ($facts->{$cap}) { } 40 14 54
if $wire->{$cap} 39 1 40
148 14 else { delete $caps->{$cap} }
149 }
150 54 return;
151 }
152  
153 87 ▶sub learned_model_capabilities {
Subroutine learned_model_capabilities: called CC=1 SCAR=0.0
Pod documented
154 87 my ( $self ) = @_;
155 87 my $learned = $self->_learned_model_capabilities;
156 87 return { map { $_ => { %{ $learned->{$_} } } } keys %$learned };
157 }
158  
159 1 ▶sub clear_learned_model_capabilities {
Subroutine clear_learned_model_capabilities: called CC=1 SCAR=0.0
Pod documented
160 1 my ( $self ) = @_;
161 1 $self->_set_learned_model_capabilities( {} );
162 1 return;
163 }
164  
165 # Engine hooks (ADR 0032). An engine that can read its provider's model
166 # metadata names the document format (a Langertha::ModelProbe tag) and its
167 # URL. The default is no probe: probe_model_capabilities_f resolves to {}
168 # without a request.
169 5 ▶sub model_metadata_format { return undef }
Subroutine model_metadata_format: called CC=1 SCAR=0.0
Pod documented
170 0 ▶sub model_metadata_url { return undef }
Subroutine model_metadata_url: not called CC=1 SCAR=6.9
Pod documented
171  
172 65 ▶async sub probe_model_capabilities_f {
Subroutine probe_model_capabilities_f: called CC=28 SCAR=33.5
Pod documented
173 65 my ( $self, %args ) = @_;
174 65 my $format = $self->model_metadata_format;
175 65 ▶ return {} unless defined $format;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format 3 62 65
176 62 my $url = $self->model_metadata_url;
177 62 ▶ croak ref($self) . ": model_metadata_format '$format' without a model_metadata_url"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 0 62 62
Condition33%1/3
defined $url and length $url
!ll&&!rl&&r
0062
MC/DC0%0/2
defined $url and length $url
defined $url length $url
Truth table33%1/3
A and B
A= defined $urlB= length $url
ABresult
0X0
100
111
178 unless defined $url && length $url;
179  
180 62 my @models;
181 62 ▶ if ( exists $args{models} && !ref $args{models} && ( $args{models} // '' ) eq 'all' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $args{'models'} and not ref $args{'models'} and ($args{'models'} // '') eq 'all') { } 7 55 62
elsif (exists $args{'models'}) { } 16 39 55
Condition87%7/8
exists $args{"models"} and not ref $args{"models"} and ($args{"models"} // "") eq "all"
!ll&&!rl&&r
5417
exists $args{"models"} and not ref $args{"models"}
!ll&&!rl&&r
39158
$args{"models"} // ""
l!l
80
MC/DC66%2/3
exists $args{"models"} and not ref $args{"models"} and ($args{"models"} // "") eq "all"
exists $args{"models"} not ref $args{"models"} $args{"models"}
Truth table75%3/4
A and not(B) and C
A= exists $args{"models"}B= not ref $args{"models"}C= $args{"models"}
ABCresult
0XX0
10X0
1100
1111
182 # The whole catalogue (k282): only a document that names its models can
183 # answer "every model"; the others need ids to key their fact by.
184 7 ▶ croak ref($self) . ": probe_model_capabilities_f models => 'all' needs a catalogue"
Branch: 1 branch
BranchTrueFalseTotal
unless "Langertha::ModelProbe"->is_catalogue($format) 2 5 7
185 . " document; model_metadata_format '$format' does not name its models"
186 unless Langertha::ModelProbe->is_catalogue($format);
187 }
188 elsif ( exists $args{models} ) {
189 croak ref($self) . q{: probe_model_capabilities_f models must be an ArrayRef or 'all'}
190 16 ▶ unless ref $args{models} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args{"models"} eq "ARRAY" 1 15 16
191 15 ▶ @models = grep { defined && !ref && length } @{ $args{models} };
Condition100%6/6
defined $_ && !ref($_) && length $_
!ll&&!rl&&r
3122
defined $_ and not ref $_
!ll&&!rl&&r
1223
MC/DC100%3/3
defined $_ && !ref($_) && length $_
defined $_ not ref $_ length $_
Truth table100%4/4
A and not(B) && C
A= defined $_B= not ref $_C= length $_
ABCresult
0XX0
10X0
1100
1111
192 }
193 else {
194 39 my $model = $self->_capability_model;
195 39 ▶ @models = ( $model ) if defined $model && !ref $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
if defined $model and not ref $model and length $model 38 1 39
Condition66%4/6
defined $model and not ref $model and length $model
!ll&&!rl&&r
1038
defined $model and not ref $model
!ll&&!rl&&r
1038
MC/DC33%1/3
defined $model and not ref $model and length $model
defined $model not ref $model length $model
Truth table50%2/4
A and not(B) and C
A= defined $modelB= not ref $modelC= length $model
ABCresult
0XX0
10X0
1100
1111
196 }
197  
198 59 my $probe = 'Langertha::ModelProbe';
199 59 my $method = $probe->http_method($format);
200 59 my $per_model = $probe->per_model($format);
201 # A per-model document (Ollama /api/show) takes one request per model and
202 # needs a model; a server-wide document is one request whatever was asked.
203 59 ▶ my @batches = $per_model ? ( map { [ $_ ] } @models ) : ( [ @models ] );
Branch: 1 branch
BranchTrueFalseTotal
$per_model ? : 15 44 59
204 59 my %allowed = map { $_ => 1 } $probe->probed_capabilities;
205  
206 59 my %learned;
207 59 for my $batch (@batches) {
208 0 ▶ my $request = $self->generate_http_request( $method, $url, sub { $_[0] },
Subroutine __ANON__: not called CC=1 SCAR=6.9
209 65 ▶ $per_model ? ( model => $batch->[0] ) : () );
Branch: 1 branch
BranchTrueFalseTotal
$per_model ? : 21 44 65
210 65 my $response = await $self->_async_do_request_f( request => $request );
211 # A per-model document that does not know the model (Ollama /api/show
212 # answers 404 "model not found") gives no fact for that model; the other
213 # models of the call are still learned. Every other failure fails loud.
214 65 ▶ next if $per_model && $response->code == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $per_model and $response->code == 404 1 64 65
Condition100%3/3
$per_model and $response->code == 404
!ll&&!rl&&r
44201
MC/DC100%2/2
$per_model and $response->code == 404
$per_model $response->code == 404
Truth table100%3/3
A and B
A= $per_modelB= $response->code == 404
ABresult
0X0
100
111
215 64 ▶ unless ( $response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 4 60 64
216 4 ▶ my $body = $self->can('_error_response_body') ? $self->_error_response_body($response) : '';
Branch: 1 branch
BranchTrueFalseTotal
$self->can('_error_response_body') ? : 4 0 4
217 4 ▶ croak ref($self) . ' model metadata probe failed: ' . $response->status_line
Branch: 1 branch
BranchTrueFalseTotal
length $body ? : 4 0 4
218 . ( length $body ? " - $body" : '' );
219 }
220 60 my $data;
221 {
222 60 local $@;
223 croak ref($self) . ' model metadata probe: response from ' . $request->uri->path
224 . ' is not JSON'
225 60 ▶ unless eval { $data = $self->json->decode( $response->content ); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $data = $self->json->decode($response->content); 1 } } 1 59 60
226 }
227 59 my $facts = $probe->extract( $format, $data, $batch );
228 59 for my $model ( grep { length } keys %$facts ) {
229 102 for my $cap ( grep { $allowed{$_} } keys %{ $facts->{$model} } ) {
230 102 ▶ $learned{$model}{$cap} = $facts->{$model}{$cap} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$facts->{$model}{$cap} ? : 60 42 102
231 }
232 }
233 }
234  
235 54 $self->_merge_learned_model_capabilities( \%learned );
236 54 return \%learned;
237 180 }
238  
239 # Merge facts into the store; a later fact for the same model and capability
240 # wins. A new HashRef, never a mutation in place: clone_object
241 # (Manifest::Builder) shares the slot, and a clone that probes or imports must
242 # not write into its source.
243 70 ▶sub _merge_learned_model_capabilities {
Subroutine _merge_learned_model_capabilities: called CC=3 SCAR=11.0
244 70 my ( $self, $learned ) = @_;
245 70 my $current = $self->learned_model_capabilities;
246 70 for my $model ( keys %$learned ) {
247 131 ▶ $current->{$model} = { %{ $current->{$model} // {} }, %{ $learned->{$model} } };
Condition100%2/2
$current->{$model} // {}
l!l
7124
MC/DC100%1/1
$current->{$model} // {}
$current->{$model}
Truth table100%2/2
A
A= $current->{$model}
Aresult
11
00
248 }
249 70 $self->_set_learned_model_capabilities($current);
250 70 return;
251 }
252  
253 32 ▶sub _is_fact_value {
Subroutine _is_fact_value: called CC=4 SCAR=13.9
254 32 my ( $value ) = @_;
255 32 ▶ return 0 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 31 32
256 31 ▶ return 1 unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 28 3 31
257 3 ▶ return blessed($value) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($value) ? : 2 1 3
258 }
259  
260 19 ▶sub import_learned_capabilities {
Subroutine import_learned_capabilities: called CC=8 SCAR=20.8
Pod documented
261 19 my ( $self, $map ) = @_;
262 19 ▶ croak ref($self) . ': import_learned_capabilities needs a HashRef of { $model_id => { $capability => 0|1 } }'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $map eq "HASH" 3 16 19
263 unless ref $map eq 'HASH';
264 16 my %allowed = map { $_ => 1 } Langertha::ModelProbe->probed_capabilities;
265 16 my %import;
266 16 for my $model ( keys %$map ) {
267 # Hash keys are always strings; an empty key is never a model id.
268 34 ▶ next unless length $model && ref $map->{$model} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless length $model and ref $map->{$model} eq "HASH" 2 32 34
Condition100%3/3
length $model and ref $map->{$model} eq "HASH"
!ll&&!rl&&r
1132
MC/DC100%2/2
length $model and ref $map->{$model} eq "HASH"
length $model ref $map->{$model} eq "HASH"
Truth table100%3/3
A and B
A= length $modelB= ref $map->{$model} eq "HASH"
ABresult
0X0
100
111
269 32 my $facts = $map->{$model};
270 # A fact is a defined plain scalar or a JSON boolean (a map that went
271 # through a JSON store); undef or an unblessed reference is no fact.
272 32 ▶ for my $cap ( grep { $allowed{$_} && _is_fact_value( $facts->{$_} ) } keys %$facts ) {
Condition100%3/3
$allowed{$_} && _is_fact_value($facts->{$_})
!ll&&!rl&&r
1230
MC/DC100%2/2
$allowed{$_} && _is_fact_value($facts->{$_})
$allowed{$_} _is_fact_value($facts->{$_})
Truth table100%3/3
A && B
A= $allowed{$_}B= _is_fact_value($facts->{$_})
ABresult
0X0
100
111
273 30 ▶ $import{$model}{$cap} = $facts->{$cap} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$facts->{$cap} ? : 16 14 30
274 }
275 }
276 16 $self->_merge_learned_model_capabilities( \%import );
277 16 return \%import;
278 }
279  
280 59 ▶sub probe_model_capabilities {
Subroutine probe_model_capabilities: called CC=1 SCAR=0.0
Pod documented
281 59 my ( $self, %args ) = @_;
282 # ->get drives the loop the pending future belongs to, or returns at once
283 # on the synchronous fallback (ADR 0027), as poll_metrics does.
284 59 return $self->probe_model_capabilities_f(%args)->get;
285 }
286  
287  
288  
289  
290 7924 ▶sub supports {
Subroutine supports: called CC=1 SCAR=0.0
Pod documented
291 7924 my ( $self, $cap ) = @_;
292 7924 return !!$self->engine_capabilities->{$cap};
293 }
294  
295  
296 180 1;
297  
298 __END__
299  
300 =pod
301  
302 =encoding UTF-8
303  
304 =head1 NAME
305  
306 Langertha::Role::Capabilities - Engine-capability registry derived from composed roles
307  
308 =head1 VERSION
309  
310 version 0.503
311  
312 =head1 SYNOPSIS
313  
314 if ( $engine->supports('tool_choice_named') ) { ... }
315  
316 my $caps = $engine->engine_capabilities;
317 for my $cap ( sort keys %$caps ) {
318 say "$cap" if $caps->{$cap};
319 }
320  
321 # Engine-level override for a wire reality the role inventory
322 # cannot express (e.g. provider only accepts string tool_choice):
323 around engine_capabilities => sub {
324 my ( $orig, $self, @rest ) = @_;
325 my $caps = $self->$orig(@rest);
326 delete $caps->{tool_choice_named};
327 return $caps;
328 };
329  
330 =head1 DESCRIPTION
331  
332 Composed by L<Langertha::Role::Chat> (and therefore present on every
333 engine), this role provides the C<engine_capabilities> method plus the
334 C<supports> helper. The default implementation derives the flag set
335 from which capability-bearing roles the engine composes — no per-role
336 plumbing required, the registry below is the single source of truth.
337  
338 Engines override (via C<around>) when the wire reality differs from
339 the role inventory — for example to clear C<tool_choice_named> on a
340 provider that only accepts string forms of C<tool_choice>.
341  
342 The mapping from role to flag is intentionally kept inside this one
343 module so adding a new capability is a single-file change. The role
344 itself does not need to know about C<engine_capabilities>.
345  
346 =head2 probe_model_capabilities_f
347  
348 my $learned = await $engine->probe_model_capabilities_f;
349 my $learned = await $engine->probe_model_capabilities_f( models => [ 'llava', 'llama3.3' ] );
350 # { 'llava' => { image_input => 1 }, 'llama3.3' => { image_input => 0 } }
351  
352 $engine->supports('image_input'); # now answers from the learned fact
353  
354 Asks the provider's own model metadata endpoint which capabilities a model has
355 and stores the answer on this engine instance (ADR 0032). It is the only way
356 facts enter the learned layer: C<supports> and L</engine_capabilities> never
357 send a request.
358  
359 Without C<models>, the probe asks about C<chat_model> (nothing when no model is
360 configured). Endpoints that describe every model in one document (OpenRouter,
361 Mistral, LM Studio, TSystems) are fetched once and every model they describe is learned;
362 Ollama's C</api/show> is asked once per model; llama.cpp's C</props> describes
363 the one loaded model, so its fact is stored for every id that was asked about.
364  
365 C<< models => 'all' >> asks for the whole catalogue and does not fall back to
366 C<chat_model>: every model the document names is learned from one request.
367 It croaks on a format whose document does not name its models (Ollama,
368 llama.cpp; see L<Langertha::ModelProbe/is_catalogue>). Use it to probe an
369 endpoint once and hand the result to the other engine instances on the same
370 endpoint with L</import_learned_capabilities>.
371  
372 Resolves to C<< { $model_id => { $capability => 0|1 } } >>, the facts learned by
373 this call, exactly as they were merged into the engine's store (a fresh
374 HashRef the caller owns, ready for L</import_learned_capabilities>). Only the capabilities in
375 L<Langertha::ModelProbe/probed_capabilities> are learned (C<image_input>). A
376 model the document does not describe, or describes without the field, gets no
377 fact and keeps its static answer.
378  
379 Engines that implement a probe: L<Langertha::Engine::OpenRouter>,
380 L<Langertha::Engine::Mistral>, L<Langertha::Engine::Ollama>,
381 L<Langertha::Engine::OllamaOpenAI>, L<Langertha::Engine::LMStudio>,
382 L<Langertha::Engine::LMStudioOpenAI>, L<Langertha::Engine::LlamaCpp> and
383 L<Langertha::Engine::TSystems> (documentation-derived, not live-verified). On
384 every other engine the method exists and resolves to an empty HashRef without
385 a request.
386  
387 Only non-empty plain strings count as model ids; anything else in C<models>
388 is ignored. When C<chat_model> is looked up in the store, the exact id wins,
389 then the format's equivalent spelling (L<Langertha::ModelProbe/lookup_ids>):
390 on Ollama a missing tag means C<:latest> (C<llava> finds C<llava:latest> and
391 back), on OpenRouter a routing variant such as C<:online> or C<:free> falls
392 back to its base id when the variant itself is not listed.
393  
394 On Ollama a model the server does not have (C</api/show> answers 404) gives
395 no fact, and the other models of the call are still learned. Any other
396 non-success answer fails the future with C<< <engine> model metadata probe
397 failed: <status> - <body> >>, a success answer that is not JSON with C<<
398 <engine> model metadata probe: response from <path> is not JSON >>; in both
399 cases nothing from the call is stored.
400  
401 =head2 probe_model_capabilities
402  
403 my $learned = $engine->probe_model_capabilities;
404  
405 Synchronous wrapper around L</probe_model_capabilities_f> (blocks with
406 C<< ->get >>).
407  
408 =head2 learned_model_capabilities
409  
410 my $learned = $engine->learned_model_capabilities;
411 # { 'openai/gpt-4o' => { image_input => 1 }, ... }
412  
413 A copy of every fact probed or imported so far on this instance, per model id.
414 It has the shape L</import_learned_capabilities> takes.
415  
416 =head2 import_learned_capabilities
417  
418 # One metadata fetch for a whole endpoint, shared by every instance on it:
419 my $learned = await $probe_engine->probe_model_capabilities_f( models => 'all' );
420 $_->import_learned_capabilities($learned) for @other_engines;
421  
422 Merges C<< { $model_id => { $capability => 0|1 } } >> into this instance's
423 learned store, as if this instance had probed it: the facts take the same
424 place in L</engine_capabilities> (after the static per-model table, under the
425 layer-1 and layer-2 wire gates), and a later fact for the same model and
426 capability replaces the earlier one. The map is the result of
427 L</probe_model_capabilities_f> or L</learned_model_capabilities> of another
428 instance; nothing is fetched (ADR 0032).
429  
430 Only the capabilities in L<Langertha::ModelProbe/probed_capabilities> are
431 taken; other names are ignored. An empty model id, a model whose facts are not
432 a HashRef, and a fact value that is C<undef> or an unblessed reference are
433 skipped; any other value is stored as C<1> or C<0> by truth (a JSON boolean
434 works). Croaks unless the argument is a HashRef. Returns the facts it merged,
435 in the same shape.
436  
437 Facts are keyed by model id, not by endpoint: import only into instances that
438 talk to the endpoint the facts were read from.
439  
440 =head2 clear_learned_model_capabilities
441  
442 Forgets every probed or imported fact; L</engine_capabilities> answers from the static
443 layers again.
444  
445 =head2 model_metadata_format
446  
447 The L<Langertha::ModelProbe> format tag of this engine's model metadata, or
448 C<undef> (the default) when the engine has no probe.
449  
450 =head2 model_metadata_url
451  
452 The URL L</probe_model_capabilities_f> requests, or C<undef> (the default).
453  
454 =head2 engine_capabilities
455  
456 my $caps = $engine->engine_capabilities;
457  
458 Returns a HashRef of capability flags. The default derives the flag set in
459 three layers: (1) it scans the composed role inventory and sets flags from
460 the static role-to-flags map (ADR 0002); (2) an engine may correct the
461 whole-endpoint wire reality via C<around> (remove flags the wire cannot
462 deliver at all, or add an ad-hoc flag — the outer gate); (3) it applies the
463 engine's C<model_capability_corrections> for the currently selected
464 C<chat_model>, refining the base where the wire reality is per-model rather
465 than per-engine (ADR 0002 amendment, ADR 0019).
466  
467 After layer 3 comes the B<learned layer> (ADR 0032): facts that
468 L</probe_model_capabilities_f> read from the provider's own model metadata for
469 the current C<chat_model>. For a model the probe reported, the provider's
470 statement wins over the static table in both directions; a learned C<1> can
471 only re-assert a flag the composed roles grant (layer 1). The learned layer
472 runs inside the base method, so the engine's C<around> (layer 2) still has the
473 last word: a wire that cannot carry a field stays closed. The learned layer is
474 empty until the caller probes, so this method never sends a request.
475  
476 A capability flag means B<the wire accepts the field>, not that any given
477 model will honor it. For example C<reasoning_effort> being true says the
478 engine's API will accept a reasoning-effort field on the request; whether a
479 particular model supports reasoning is a separate runtime concern (every
480 reasoning field 400s on a non-reasoning model). Engines whose wire never
481 accepts the field clear the flag via C<around engine_capabilities>
482 (e.g. Perplexity), or per model via L</model_capability_corrections> (e.g.
483 MiniMax's OpenAI endpoint, where only C<MiniMax-M3> keeps it).
484  
485 Prompt caching is request-side-asymmetric, so it gets B<two> flags rather
486 than one: C<prompt_cache> means the wire accepts an explicit cache-enable
487 breakpoint (Anthropic's C<cache_control>), while C<prompt_cache_key> means the
488 wire accepts an OpenAI-style routing hint (caching itself is automatic there).
489 The single C<Langertha::Role::PromptCache> role contributes both; the
490 C<OpenAIBase> / C<AnthropicBase> base classes each clear the one that does not
491 apply to their wire, so the OpenAI family advertises only the key and the
492 Anthropic family only the enable breakpoint.
493  
494 C<prefix_caching> (from C<Langertha::Role::RuntimeKnobs>, composed on the
495 self-hosted vLLM / SGLang / llama.cpp engines) means B<the wire accepts
496 prefix-cache isolation/reuse controls> (C<cache_salt>, C<cache_prompt>,
497 C<n_cache_reuse>, C<id_slot>, C<priority>, C<return_cached_tokens_details>,
498 C<extra_key>) — B<not> that prefix caching is on. Whether the server actually
499 caches is launch state the client cannot observe (vLLM C<--enable-prefix-caching>,
500 SGLang C<--enable-mixed-prefill> / C<--enable-prefix-caching>, llama.cpp
501 C<--cache_prompt>); the flag only says the request body may carry the knobs.
502  
503 C<server_tools> (from C<Langertha::Role::ServerTools>) means B<the wire accepts
504 provider-native server-side tool entries in C<tools>> (C<web_search>,
505 C<file_search>, remote C<mcp>, ...; see L<Langertha::ServerTool>). It is one
506 flag on purpose: which tool types a model honors is a fast-moving provider
507 vocabulary, not a capability.
508  
509 C<image_input> (from C<Langertha::Role::ImageInput>) is the exception to the
510 wire-only contract: it means B<the selected model sees an image part>
511 (L<Langertha::Content::Image>), not merely that the wire accepts one. It is
512 resolved per model; engines whose model is unknown to the client (gateways,
513 self-hosted servers, shims) make no claim. The flag is advisory: nothing
514 blocks an image on an engine or model without it.
515  
516 =head2 model_capability_corrections
517  
518 sub model_capability_corrections {
519 return (
520 'kimi-k3' => { tool_choice_named => 0 }, # exact model id
521 qr/\Akimi-k2\./ => { tool_choice_any => 0 }, # a model family
522 );
523 }
524  
525 The per-model correction layer (layer 3 of C<engine_capabilities>).
526 Returns an B<ordered> list of C<< ( $matcher => \%overrides ) >> pairs.
527 C<$matcher> is either an exact model-id string (matched with C<eq>) or a
528 C<qr//> regex (matched against the engine's C<chat_model>) — model ids come
529 in families (C<gpt-5.6-*>, C<kimi-k2.7-*>), so both forms are supported.
530 C<\%overrides> maps a capability flag to C<1> (assert) or C<0> (clear);
531 later matching entries win on a shared flag.
532  
533 This is the sanctioned home for a wire reality that differs B<per model>
534 rather than per engine — for example a model that forbids a forced named
535 tool while its siblings allow it. Engine-B<wide> corrections (the whole
536 endpoint never accepts a field) belong in C<around engine_capabilities>
537 instead. The default returns an empty list, so engines that need no
538 per-model refinement pay nothing.
539  
540 =head2 supports
541  
542 if ( $engine->supports('tool_choice_named') ) { ... }
543  
544 Convenience wrapper that returns a true value when the named capability
545 is present and truthy in C<engine_capabilities>.
546  
547 =head1 SUPPORT
548  
549 =head2 Issues
550  
551 Please report bugs and feature requests on GitHub at
552 L<https://github.com/Getty/langertha/issues>.
553  
554 =head2 IRC
555  
556 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
557  
558 =head1 CONTRIBUTING
559  
560 Contributions are welcome! Please fork the repository and submit a pull request.
561  
562 =head1 AUTHOR
563  
564 Torsten Raudssus <getty@cpan.org>
565  
566 =head1 COPYRIGHT AND LICENSE
567  
568 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
569  
570 This is free software; you can redistribute it and/or modify it under
571 the same terms as the Perl 5 programming language system itself.
572  
573 =cut
« blib/lib/Langertha/Role/ReasoningEffort.pm ↑ Summary blib/lib/Langertha/CachedContent.pm »