blib/lib/Langertha/Knarr/Router.pm

filter: Statementstmt 98.2% 229 / 233 Branchbran 85.2% 116 / 136 Conditioncond 66.6% 62 / 93 MC/DCmcdc 40.0% 22 / 55 Subroutinesub 100% 29 / 29 Podpod 100% 5 / 5 totaltotal 84.0% 463 / 551 CC 111 SCAR 26.1
CC
111
Cov
88%
probe_capabilities_f
25.8
_get_engine
21.2
_discover_models
18.1
CRAP 13.6
« blib/lib/Langertha/Knarr/Tracing.pm ↑ Summary blib/lib/Langertha/Knarr/Manifest.pm »
1 package Langertha::Knarr::Router;
2 50 our $VERSION = '1.102';
3 # ABSTRACT: Model name to Langertha engine routing with caching
4 50 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 50 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 50 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 50 ▶use Scalar::Util qw( blessed refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 50 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 50 ▶use Future::Utils qw( fmap_void );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 50 ▶use Langertha ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 50 ▶use Langertha::Knarr::Handler::Passthrough;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 # Keys of a model config that describe that one model and therefore never
15 # pass to the models discovered through it (k31). Everything else is
16 # endpoint-level and inherited; see the POD above.
17 50 my @MODEL_SPECIFIC_KEYS = qw( model context_size );
18  
19 50 has config => (
20 is => 'ro',
21 required => 1,
22 );
23  
24  
25 has _engine_cache => (
26 is => 'ro',
27 86 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
28 50 );
29  
30 has _discovered_models => (
31 is => 'rw',
32 86 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
33 50 );
34  
35 50 has _discovery_done => (
36 is => 'rw',
37 default => 0,
38 );
39  
40 # Engine instances a capability probe was started on (k37), by refaddr: each
41 # cached instance is probed once, whether the probe succeeded or not.
42 has _probed => (
43 is => 'ro',
44 86 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
45 50 );
46  
47 # What a whole-catalogue probe learned, by endpoint key (k38): an instance
48 # that turns up on that endpoint later imports it instead of asking again.
49 has _catalogue_learned => (
50 is => 'ro',
51 86 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
52 50 );
53  
54 50 has capabilities_generation => (
55 is => 'rw',
56 default => 0,
57 );
58  
59  
60  
61 1652 ▶sub resolve {
Subroutine resolve: called CC=15 SCAR=27.1
Pod documented
62 1652 my ($self, $model_name, %opts) = @_;
63 1652 ▶ my $named = defined $model_name && length $model_name ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $model_name && length $model_name ? : 1598 54 1652
Condition100%3/3
defined $model_name and length $model_name
!ll&&!rl&&r
5131598
MC/DC100%2/2
defined $model_name and length $model_name
defined $model_name length $model_name
Truth table100%3/3
A and B
A= defined $model_nameB= length $model_name
ABresult
0X0
100
111
64 1652 my $def;
65  
66 1652 ▶ if ($named) {
Branch: 1 branch
BranchTrueFalseTotal
if ($named) 1598 54 1652
67 # Check explicit config first
68 1598 $def = $self->config->models->{$model_name};
69  
70 # Check discovered models
71 1598 ▶ unless ($def) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($def) 1274 324 1598
72 1274 ▶ $self->_discover_models unless $self->_discovery_done;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_discovery_done 10 1264 1274
73 1274 $def = $self->_discovered_models->{$model_name};
74 }
75 }
76  
77 # Fall back to default engine (skip_default allows caller to try passthrough first)
78 1652 ▶ unless ($def) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($def) 189 1463 1652
79 189 ▶ return () if $opts{skip_default};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"skip_default"} 136 53 189
80 53 $def = $self->config->default_engine;
81 53 ▶ croak "No model specified" unless $named || $def;
Branch: 1 branch
BranchTrueFalseTotal
unless $named or $def 3 50 53
Condition100%3/3
$named or $def
l!l&&r!l&&!r
21293
MC/DC100%2/2
$named or $def
$named $def
Truth table100%3/3
A or B
A= $namedB= $def
ABresult
1X1
011
000
82 # A named model replaces the default engine's model:; a request without
83 # one (A2A, ...) gets the default engine as configured (k42).
84 50 ▶ $def = { %$def, model => $model_name } if $def && $named;
Branch: 1 branch
BranchTrueFalseTotal
if $def and $named 20 30 50
Condition100%3/3
$def and $named
!ll&&!rl&&r
12920
MC/DC100%2/2
$def and $named
$def $named
Truth table100%3/3
A and B
A= $defB= $named
ABresult
0X0
100
111
85 }
86  
87 1513 ▶ croak "Model '$model_name' not configured and no default engine" unless $def;
Branch: 1 branch
BranchTrueFalseTotal
unless $def 1 1512 1513
88  
89 1512 my $engine = $self->_get_engine($def, $model_name);
90 1486 ▶ my $resolved_model = $def->{model} // $model_name;
Condition100%3/3
$def->{"model"} // $model_name
l!l&&r!l&&!r
14571712
MC/DC100%2/2
$def->{"model"} // $model_name
$def->{"model"} $model_name
Truth table100%3/3
A // B
A= $def->{"model"}B= $model_name
ABresult
1X1
011
000
91 # No model: key means the engine was built without a model and the
92 # provider default answers; $resolved_model is only the alias then (k22).
93 1486 ▶ my $alias_only = defined $def->{model} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $def->{'model'} ? : 1457 29 1486
94  
95 1486 return ($engine, $resolved_model, $alias_only);
96 }
97  
98 1648 ▶sub _get_engine {
Subroutine _get_engine: called CC=21 SCAR=30.6
99 1648 my ($self, $def, $model_name) = @_;
100  
101 1648 my $engine_class = $def->{engine};
102 1648 my $cache_key = $self->_engine_cache_key($def);
103  
104 1648 ▶ if (my $cached = $self->_engine_cache->{$cache_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->_engine_cache->{$cache_key}) 1107 541 1648
105 1107 return $cached;
106 }
107  
108 541 my $full_class = Langertha->resolve_engine_class($engine_class);
109  
110 541 my %args;
111  
112 # API key from env var if specified
113 541 ▶ if ($def->{api_key_env}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($def->{'api_key_env'}) { } 37 504 541
elsif ($def->{'api_key'}) { } 343 161 504
114 $args{api_key} = $ENV{$def->{api_key_env}}
115 37 ▶ // croak "Environment variable $def->{api_key_env} not set for engine $engine_class";
Condition100%3/3
$ENV{$def->{"api_key_env"}} // croak(qq[Environment variable $def->{"api_key_env"} not set for engine $engine_class])
l!l&&r!l&&!r
11818
MC/DC0%0/2
$ENV{$def->{"api_key_env"}} // croak(qq[Environment variable $def->{"api_key_env"} not set for engine $engine_class])
$ENV{$def->{"api_key_env"}} croak(qq[Environment variable $def->{"api_key_env"} not set for engine $engine_class])
Truth table33%1/3
A // B
A= $ENV{$def->{"api_key_env"}}B= croak(qq[Environment variable $def->{"api_key_env"} not set for engine $engine_class])
ABresult
1X1
011
000
116 } elsif ($def->{api_key}) {
117 343 $args{api_key} = $def->{api_key};
118 }
119  
120 515 ▶ $args{url} = $def->{url} if $def->{url};
Branch: 1 branch
BranchTrueFalseTotal
if $def->{"url"} 484 31 515
121 515 ▶ $args{model} = $def->{model} if $def->{model};
Branch: 1 branch
BranchTrueFalseTotal
if $def->{"model"} 385 130 515
122 515 ▶ $args{system_prompt} = $def->{system_prompt} if $def->{system_prompt};
Branch: 1 branch
BranchTrueFalseTotal
if $def->{"system_prompt"} 2 513 515
123 515 ▶ $args{temperature} = $def->{temperature} if defined $def->{temperature};
Branch: 1 branch
BranchTrueFalseTotal
if defined $def->{"temperature"} 2 513 515
124 515 ▶ $args{response_size} = $def->{response_size} if defined $def->{response_size};
Branch: 1 branch
BranchTrueFalseTotal
if defined $def->{"response_size"} 2 513 515
125 # context_size is operator intent: engines composing core's
126 # Role::ContextSize take it (and put it on their wire, e.g. Ollama's
127 # num_ctx); Config warned once at load about engines that cannot (k30).
128 $args{context_size} = $def->{context_size}
129 515 ▶ if defined $def->{context_size} && $full_class->can('context_size');
Branch: 1 branch
BranchTrueFalseTotal
if defined $def->{"context_size"} and $full_class->can("context_size") 3 512 515
Condition100%3/3
defined $def->{"context_size"} and $full_class->can("context_size")
!ll&&!rl&&r
51023
MC/DC100%2/2
defined $def->{"context_size"} and $full_class->can("context_size")
defined $def->{"context_size"} $full_class->can("context_size")
Truth table100%3/3
A and B
A= defined $def->{"context_size"}B= $full_class->can("context_size")
ABresult
0X0
100
111
130  
131 # A hanging upstream must not hold the client's request open forever
132 # (k35): the model config's own user_agent_timeout, else the global
133 # upstream_timeout. 0 leaves the engine without one.
134 515 ▶ my $timeout = $def->{user_agent_timeout} // $self->config->upstream_timeout;
Condition66%2/3
$def->{"user_agent_timeout"} // $self->config->upstream_timeout
l!l&&r!l&&!r
35120
MC/DC0%0/2
$def->{"user_agent_timeout"} // $self->config->upstream_timeout
$def->{"user_agent_timeout"} $self->config->upstream_timeout
Truth table66%2/3
A // B
A= $def->{"user_agent_timeout"}B= $self->config->upstream_timeout
ABresult
1X1
011
000
135 515 ▶ $args{user_agent_timeout} = $timeout
Branch: 1 branch
BranchTrueFalseTotal
if $timeout and $timeout > 0 and $full_class->can("user_agent_timeout") 369 146 515
Condition83%5/6
$timeout and $timeout > 0 and $full_class->can("user_agent_timeout")
!ll&&!rl&&r
1145369
$timeout and $timeout > 0
!ll&&!rl&&r
10514
MC/DC66%2/3
$timeout and $timeout > 0 and $full_class->can("user_agent_timeout")
$timeout $timeout > 0 $full_class->can("user_agent_timeout")
Truth table75%3/4
A and B and C
A= $timeoutB= $timeout > 0C= $full_class->can("user_agent_timeout")
ABCresult
0XX0
10X0
1100
1111
136 if $timeout && $timeout > 0 && $full_class->can('user_agent_timeout');
137  
138 # Langfuse config from global config
139 515 my $langfuse = $self->config->langfuse;
140 515 ▶ if ($langfuse && %$langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse and %$langfuse) 9 506 515
Condition66%2/3
$langfuse and %$langfuse
!ll&&!rl&&r
05069
MC/DC50%1/2
$langfuse and %$langfuse
$langfuse %$langfuse
Truth table66%2/3
A and B
A= $langfuseB= %$langfuse
ABresult
0X0
100
111
141 9 ▶ $args{langfuse_public_key} = $langfuse->{public_key} if $langfuse->{public_key};
Branch: 1 branch
BranchTrueFalseTotal
if $langfuse->{"public_key"} 9 0 9
142 9 ▶ $args{langfuse_secret_key} = $langfuse->{secret_key} if $langfuse->{secret_key};
Branch: 1 branch
BranchTrueFalseTotal
if $langfuse->{"secret_key"} 9 0 9
143 9 ▶ $args{langfuse_url} = $langfuse->{url} if $langfuse->{url};
Branch: 1 branch
BranchTrueFalseTotal
if $langfuse->{"url"} 9 0 9
144 }
145  
146 515 $log->debugf("Creating engine %s for model %s", $full_class, $model_name);
147 515 my $engine = $full_class->new(%args);
148  
149 515 $self->_engine_cache->{$cache_key} = $engine;
150 515 return $engine;
151 }
152  
153 1648 ▶sub _engine_cache_key {
Subroutine _engine_cache_key: called CC=2 SCAR=6.9
154 1648 my ($self, $def) = @_;
155 # The model is part of the key: chat_model is read-only on an engine, and
156 # core evaluates model-scoped capabilities against it, so each model needs
157 # its own instance (k20). context_size is read-only on the engine too, so
158 # two aliases of one model with different windows need two instances (k30);
159 # so is user_agent_timeout (k35).
160 return join('|', $self->_endpoint_key($def),
161 1648 ▶ map { $def->{$_} // '' } qw( model context_size user_agent_timeout ));
Condition100%2/2
$def->{$_} // ""
l!l
15263418
MC/DC100%1/1
$def->{$_} // ""
$def->{$_}
Truth table100%2/2
A
A= $def->{$_}
Aresult
11
00
162 }
163  
164 # One upstream endpoint: engine, url and API key variable. Discovery runs
165 # once per endpoint (k23).
166 2099 ▶sub _endpoint_key {
Subroutine _endpoint_key: called CC=2 SCAR=6.9
167 2099 my ($self, $def) = @_;
168 2099 ▶ return join('|', map { $def->{$_} // '' } qw( engine url api_key_env ));
Condition100%2/2
$def->{$_} // ""
l!l
40952202
MC/DC100%1/1
$def->{$_} // ""
$def->{$_}
Truth table100%2/2
A
A= $def->{$_}
Aresult
11
00
169 }
170  
171 68 ▶sub _discover_models {
Subroutine _discover_models: called CC=17 SCAR=28.9
172 68 my ($self) = @_;
173 68 ▶ return if $self->_discovery_done;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_discovery_done 0 68 68
174 68 $self->_discovery_done(1);
175  
176 68 ▶ return unless $self->config->auto_discover;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->config->auto_discover 28 40 68
177  
178 40 my $models = $self->config->models;
179 40 my %seen_endpoints;
180  
181 # One model config per endpoint, in a fixed order: an id several endpoints
182 # list belongs to the first (k55). Endpoints that are a passthrough
183 # upstream come first -- their models may pass through as the client sent
184 # them -- then the others, each group by model config name.
185 40 my ( @upstream, @other );
186 40 for my $name (sort keys %$models) {
187 142 my $def = $models->{$name};
188 142 ▶ next if $seen_endpoints{ $self->_endpoint_key($def) }++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_endpoints{$self->_endpoint_key($def)}++ 6 136 142
189 136 my $engine = eval { $self->_get_engine($def, $name) };
190 136 ▶ unless ($engine) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($engine) 0 136 136
191 0 $log->debugf("Model discovery skipped for %s: %s", $def->{engine}, $@);
192 0 next;
193 }
194 136 ▶ push @{ $self->_is_passthrough_upstream($engine) ? \@upstream : \@other },
Branch: 1 branch
BranchTrueFalseTotal
$self->_is_passthrough_upstream($engine) ? : 21 115 136
195 [ $name, $def, $engine ];
196 }
197  
198 40 my %owner;
199 40 for my $endpoint (@upstream, @other) {
200 136 my ($name, $def, $engine) = @$endpoint;
201 136 my $engine_class = $def->{engine};
202 136 eval {
203 136 ▶ if ($engine->can('list_models')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->can("list_models")) 136 0 136
204 136 $log->debugf("Discovering models from %s", $engine_class);
205 136 my $model_ids = $engine->list_models;
206 136 for my $id (@$model_ids) {
207 439 ▶ next if $models->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $models->{$id} 2 437 439
208 437 ▶ if ( my $first = $owner{$id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $first = $owner{$id}) 85 352 437
209 85 ▶ $log->debugf("Discovered model %s also listed by %s, stays with %s",
Branch: 1 branch
BranchTrueFalseTotal
if $first ne $name 85 0 85
210 $id, $name, $first) if $first ne $name;
211 85 next;
212 }
213 352 ▶ next if $self->_discovered_models->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $self->_discovered_models->{$id} 0 352 352
214 352 $owner{$id} = $name;
215 352 my %inherited = %$def;
216 352 delete @inherited{@MODEL_SPECIFIC_KEYS};
217 352 ▶ $self->_discovered_models->{$id} = {
Branch: 1 branch
BranchTrueFalseTotal
$engine->can('url') && defined $engine->url ? : 348 4 352
Condition66%2/3
$engine->can("url") and defined $engine->url
!ll&&!rl&&r
40348
MC/DC50%1/2
$engine->can("url") and defined $engine->url
$engine->can("url") defined $engine->url
Truth table66%2/3
A and B
A= $engine->can("url")B= defined $engine->url
ABresult
0X0
100
111
218 %inherited,
219 model => $id,
220 discovered => 1,
221 # Where the model was listed: its passthrough upstream may
222 # serve it as is (k47).
223 ( $engine->can('url') && defined $engine->url
224 ? ( discovered_url => $engine->url ) : () ),
225 };
226 352 $log->debugf("Discovered model: %s (via %s)", $id, $engine_class);
227 }
228 }
229 };
230 136 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 136 136
231 0 $log->debugf("Model discovery skipped for %s: %s", $engine_class, $@);
232 }
233 }
234 }
235  
236 # The class that knows when two URLs are the same upstream (k54).
237 69 ▶sub _passthrough_class { 'Langertha::Knarr::Handler::Passthrough' }
Subroutine _passthrough_class: called CC=1 SCAR=0.0
238  
239 # True when the engine's URL is the passthrough upstream of some protocol.
240 136 ▶sub _is_passthrough_upstream {
Subroutine _is_passthrough_upstream: called CC=7 SCAR=19.6
241 136 my ($self, $engine) = @_;
242 136 ▶ my $url = $engine->can('url') ? $engine->url : undef;
Branch: 1 branch
BranchTrueFalseTotal
$engine->can('url') ? : 133 3 136
243 136 ▶ return 0 unless defined $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url 3 133 136
244 133 ▶ my $upstreams = $self->config->can('passthrough') ? $self->config->passthrough : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->config->can('passthrough') ? : 133 0 133
245 133 ▶ return 0 unless ref $upstreams eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $upstreams eq "HASH" 0 133 133
246 133 for my $base ( values %$upstreams ) {
247 69 ▶ return 1 if $self->_passthrough_class->same_upstream( $base, $url );
Branch: 1 branch
BranchTrueFalseTotal
if $self->_passthrough_class->same_upstream($base, $url) 21 48 69
248 }
249 112 return 0;
250 }
251  
252  
253 99 ▶sub list_models {
Subroutine list_models: called CC=7 SCAR=19.9
Pod documented
254 99 my ($self) = @_;
255  
256 99 ▶ $self->_discover_models unless $self->_discovery_done;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_discovery_done 30 69 99
257  
258 99 my $configured = $self->config->models;
259 99 my $discovered = $self->_discovered_models;
260 99 my @models;
261  
262 99 for my $name (sort keys %$configured) {
263 push @models, {
264 id => $name,
265 engine => $configured->{$name}{engine},
266 539 ▶ model => $configured->{$name}{model} // $name,
Condition66%2/3
$configured->{$name}{"model"} // $name
l!l&&r!l&&!r
520190
MC/DC0%0/2
$configured->{$name}{"model"} // $name
$configured->{$name}{"model"} $name
Truth table66%2/3
A // B
A= $configured->{$name}{"model"}B= $name
ABresult
1X1
011
000
267 source => 'configured',
268 };
269 }
270  
271 99 for my $name (sort keys %$discovered) {
272 653 ▶ next if $configured->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $configured->{$name} 0 653 653
273 push @models, {
274 id => $name,
275 engine => $discovered->{$name}{engine},
276 653 ▶ model => $discovered->{$name}{model} // $name,
Condition33%1/3
$discovered->{$name}{"model"} // $name
l!l&&r!l&&!r
65300
MC/DC0%0/2
$discovered->{$name}{"model"} // $name
$discovered->{$name}{"model"} $name
Truth table33%1/3
A // B
A= $discovered->{$name}{"model"}B= $name
ABresult
1X1
011
000
277 source => 'discovered',
278 };
279 }
280  
281 99 return \@models;
282 }
283  
284  
285 46 ▶sub probe_capabilities_f {
Subroutine probe_capabilities_f: called CC=23 SCAR=32.5
Pod documented
286 46 my ($self, %args) = @_;
287 46 my $config = $self->config;
288 46 ▶ return Future->done(0)
Branch: 1 branch
BranchTrueFalseTotal
unless not $config->can("probe_capabilities") or $config->probe_capabilities 6 40 46
Condition66%2/3
not $config->can("probe_capabilities") or $config->probe_capabilities
l!l&&r!l&&!r
0406
MC/DC50%1/2
not $config->can("probe_capabilities") or $config->probe_capabilities
not $config->can("probe_capabilities") $config->probe_capabilities
Truth table66%2/3
not(A) or B
A= not $config->can("probe_capabilities")B= $config->probe_capabilities
ABresult
1X1
011
000
289 unless !$config->can('probe_capabilities') || $config->probe_capabilities;
290 40 my $loop = $args{loop};
291 my $timeout = $args{timeout}
292 40 ▶ // ( $config->can('probe_timeout') ? $config->probe_timeout : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$config->can('probe_timeout') ? : 40 0 40
Condition33%1/3
$args{"timeout"} // ($config->can("probe_timeout") ? $config->probe_timeout : 0)
l!l&&r!l&&!r
0400
MC/DC0%0/2
$args{"timeout"} // ($config->can("probe_timeout") ? $config->probe_timeout : 0)
$args{"timeout"} ($config->can("probe_timeout") ? $config->probe_timeout : 0)
Truth table33%1/3
A // B
A= $args{"timeout"}B= ($config->can("probe_timeout") ? $config->probe_timeout : 0)
ABresult
1X1
011
000
293  
294 40 my ( @targets, %endpoint, @endpoint_order );
295 40 my $imported = 0;
296 40 for my $row (@{ $self->list_models }) {
297 803 my ($engine, $model, $alias_only) = eval { $self->resolve( $row->{id}, skip_default => 1 ) };
298 next unless blessed $engine && $engine->can('probe_model_capabilities_f')
299 && $engine->can('model_metadata_format')
300 803 ▶ && defined eval { $engine->model_metadata_format };
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($engine) and $engine->can("probe_model_capabilities_f") and $engine->can("model_metadata_format") and defined eval { do { $engine->model_metadata_format } } 123 680 803
Condition88%8/9
builtin::blessed($engine) and $engine->can("probe_model_capabilities_f") and $engine->can("model_metadata_format") and defined eval {
!ll&&!rl&&r
4281680
builtin::blessed($engine) and $engine->can("probe_model_capabilities_f") and $engine->can("model_metadata_format")
!ll&&!rl&&r
420761
builtin::blessed($engine) and $engine->can("probe_model_capabilities_f")
!ll&&!rl&&r
1923761
MC/DC75%3/4
builtin::blessed($engine) and $engine->can("probe_model_capabilities_f") and $engine->can("model_metadata_format") and defined eval { do { $engine->model_metadata_format } }
builtin::blessed($engine) $engine->can("probe_model_capabilities_f") $engine->can("model_metadata_format") defined eval { do { $engine->model_metadata_format } }
Truth table80%4/5
A and B and C and D
A= builtin::blessed($engine)B= $engine->can("probe_model_capabilities_f")C= $engine->can("model_metadata_format")D= defined eval { do { $engine->model_metadata_format } }
ABCDresult
0XXX0
10XX0
110X0
11100
11111
301 680 ▶ next if $self->_probed->{ refaddr $engine };
Branch: 1 branch
BranchTrueFalseTotal
if $self->_probed->{builtin::refaddr($engine)} 358 322 680
302 # An alias without model: key asks about the engine's own default (k22).
303 322 ▶ my $upstream = $alias_only ? eval { $engine->chat_model } : $model;
Branch: 1 branch
BranchTrueFalseTotal
$alias_only ? : 0 322 322
304 322 ▶ next unless defined $upstream && !ref $upstream && length $upstream;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $upstream and not ref $upstream and length $upstream 0 322 322
Condition33%2/6
defined $upstream and not ref $upstream and length $upstream
!ll&&!rl&&r
00322
defined $upstream and not ref $upstream
!ll&&!rl&&r
00322
MC/DC0%0/3
defined $upstream and not ref $upstream and length $upstream
defined $upstream not ref $upstream length $upstream
Truth table25%1/4
A and not(B) and C
A= defined $upstreamB= not ref $upstreamC= length $upstream
ABCresult
0XX0
10X0
1100
1111
305 322 $self->_probed->{ refaddr $engine } = 1;
306  
307 # A catalogue answers for every model of its endpoint: one request per
308 # endpoint, imported into the endpoint's other instances (k38).
309 322 ▶ my $def = $config->models->{ $row->{id} } // $self->_discovered_models->{ $row->{id} };
Condition66%2/3
$config->models->{$row->{"id"}} // $self->_discovered_models->{$row->{"id"}}
l!l&&r!l&&!r
203020
MC/DC0%0/2
$config->models->{$row->{"id"}} // $self->_discovered_models->{$row->{"id"}}
$config->models->{$row->{"id"}} $self->_discovered_models->{$row->{"id"}}
Truth table66%2/3
A // B
A= $config->models->{$row->{"id"}}B= $self->_discovered_models->{$row->{"id"}}
ABresult
1X1
011
000
310 322 ▶ if ( $def && $self->_shares_catalogue($engine) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($def and $self->_shares_catalogue($engine)) 309 13 322
Condition66%2/3
$def and $self->_shares_catalogue($engine)
!ll&&!rl&&r
013309
MC/DC50%1/2
$def and $self->_shares_catalogue($engine)
$def $self->_shares_catalogue($engine)
Truth table66%2/3
A and B
A= $defB= $self->_shares_catalogue($engine)
ABresult
0X0
100
111
311 309 my $key = $self->_endpoint_key($def);
312 309 ▶ if ( my $learned = $self->_catalogue_learned->{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $learned = $self->_catalogue_learned->{$key}) 1 308 309
313 1 $engine->import_learned_capabilities($learned);
314 1 $imported++;
315 1 next;
316 }
317 308 ▶ push @endpoint_order, $key unless $endpoint{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $endpoint{$key} 6 302 308
318 308 push @{ $endpoint{$key} }, [ $engine, $upstream, $row->{id} ];
319 308 next;
320 }
321 13 push @targets, [ $engine, $upstream, $row->{id} ];
322 }
323 40 ▶ $self->capabilities_generation( $self->capabilities_generation + 1 ) if $imported;
Branch: 1 branch
BranchTrueFalseTotal
if $imported 1 39 40
324 40 my $covered = $imported + @targets;
325 40 $covered += @{ $endpoint{$_} } for @endpoint_order;
326 40 push @targets, map { [ $endpoint{$_}, undef, $_ ] } @endpoint_order;
327 40 ▶ return Future->done($covered) unless @targets;
Branch: 1 branch
BranchTrueFalseTotal
unless @targets 32 8 40
328  
329 19 ▶ return ( fmap_void {
Subroutine __ANON__: called CC=9 SCAR=22.6
330 # Per model: [ $engine, $upstream, $id ]; per endpoint: [ \@members, undef, $key ].
331 19 my ($target, $upstream, $id) = @{ $_[0] };
332 19 my $shared = ref $target eq 'ARRAY';
333 19 ▶ my ($engine, @rest) = $shared ? map { $_->[0] } @$target : ( $target );
Branch: 1 branch
BranchTrueFalseTotal
$shared ? : 6 13 19
334 19 ▶ my $what = $shared ? "the catalogue behind $target->[0][2]" : "$id ($upstream)";
Branch: 1 branch
BranchTrueFalseTotal
$shared ? : 6 13 19
335 19 ▶ my $probe = eval { $engine->probe_model_capabilities_f(
Branch: 1 branch
BranchTrueFalseTotal
$shared ? : 6 13 19
Condition20%1/5
eval { // "Future"->fail($@ || "probe did not start")
l!l&&r!l&&!r
1900
$@ || 'probe did not start'
l!l
00
MC/DC0%0/2
eval { do { $engine->probe_model_capabilities_f("models", $shared ? "all" : [$upstream]) } } // "Future"->fail($@ || "probe did not start")
eval { do { $engine->probe_model_capabilities_f("models", $shared ? "all" : [$upstream]) } } "Future"->fail($@ || "probe did not start")
MC/DC0%0/1
$@ || 'probe did not start'
$@
Truth table33%1/3
A // B
A= eval { do { $engine->probe_model_capabilities_f("models", $shared ? "all" : [$upstream]) } }B= "Future"->fail($@ || "probe did not start")
ABresult
1X1
011
000
Truth table0%0/2
A
A= $@
Aresult
11
00
336 models => ( $shared ? 'all' : [ $upstream ] ) ) }
337 // Future->fail( $@ || 'probe did not start' );
338 19 ▶ $probe = Future->wait_any( $probe,
Branch: 1 branch
BranchTrueFalseTotal
if $loop and $timeout and $timeout > 0 19 0 19
Condition33%2/6
$loop and $timeout and $timeout > 0
!ll&&!rl&&r
0019
$loop and $timeout
!ll&&!rl&&r
0019
MC/DC0%0/3
$loop and $timeout and $timeout > 0
$loop $timeout $timeout > 0
Truth table25%1/4
A and B and C
A= $loopB= $timeoutC= $timeout > 0
ABCresult
0XX0
10X0
1100
1111
339 $loop->delay_future( after => $timeout )
340 ->then_fail("capability probe timed out after ${timeout}s") )
341 if $loop && $timeout && $timeout > 0;
342 10 ▶ $probe->then(sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
343 10 my ($learned) = @_;
344 10 ▶ if ($shared) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shared) 4 6 10
345 4 $self->_catalogue_learned->{$id} = $learned;
346 4 $_->import_learned_capabilities($learned) for @rest;
347 $log->debugf( "Capability probe for %s: %d models learned, %d instances taught",
348 4 ▶ $what, scalar keys %{ $learned || {} }, 1 + @rest );
Condition50%1/2
$learned || {}
l!l
40
MC/DC0%0/1
$learned || {}
$learned
Truth table50%1/2
A
A= $learned
Aresult
11
00
349 4 return Future->done;
350 }
351 $log->debugf( "Capability probe for %s: %s", $what,
352 7 join( ', ', map { my $m = $_; map { "$m $_=$learned->{$m}{$_}" } sort keys %{ $learned->{$m} } }
353 6 ▶ sort keys %{ $learned || {} } ) || 'nothing learned' );
Condition75%3/4
join(', ', map({my $m = $_; || 'nothing learned'
l!l
51
$learned || {}
l!l
60
MC/DC100%1/1
join(', ', map({my $m = $_; map {"$m $_=$learned->{$m}{$_}";} sort(keys %{$$learned{$m};});} sort(keys %{$learned or {};}))) || 'nothing learned'
join(', ', map({my $m = $_; map {"$m $_=$learned->{$m}{$_}";} sort(keys %{$$learned{$m};});} sort(keys %{$learned or {};})))
MC/DC0%0/1
$learned || {}
$learned
Truth table100%2/2
A
A= join(', ', map({my $m = $_; map {"$m $_=$learned->{$m}{$_}";} sort(keys %{$$learned{$m};});} sort(keys %{$learned or {};})))
Aresult
11
00
Truth table50%1/2
A
A= $learned
Aresult
11
00
354 6 Future->done;
355 9 ▶ })->else(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
356 9 my ($err) = @_;
357 9 ( my $text = "$err" ) =~ s/\s+\z//;
358 9 $log->warnf( "Capability probe for %s failed: %s", $what, $text );
359 9 Future->done;
360 19 ▶ })->on_ready(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
361 19 $self->capabilities_generation( $self->capabilities_generation + 1 );
362 19 });
363 } foreach => [ @targets ], concurrent => 4 ) # fmap consumes the array it is given
364 8 ▶ ->then(sub { Future->done($covered) });
Subroutine __ANON__: called CC=1 SCAR=0.0
365 }
366  
367 # True when the engine's metadata document is a catalogue AND the core can
368 # hand learned facts to another instance (k38). Either missing: per-instance
369 # probing as before (k37).
370 322 ▶sub _shares_catalogue {
Subroutine _shares_catalogue: called CC=4 SCAR=13.9
371 322 my ($self, $engine) = @_;
372 322 ▶ return 0 unless $engine->can('import_learned_capabilities');
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->can("import_learned_capabilities") 2 320 322
373 320 ▶ return 0 unless eval { require Langertha::ModelProbe; Langertha::ModelProbe->can('is_catalogue') };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { require Langertha::ModelProbe; "Langertha::ModelProbe"->can("is_catalogue") } } 0 320 320
374 320 ▶ return eval { Langertha::ModelProbe->is_catalogue( $engine->model_metadata_format ) } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { 'Langertha::ModelProbe'->is_catalogue($engine->model_metadata_format) } } ? : 309 11 320
375 }
376  
377 223 ▶sub is_passthrough_model {
Subroutine is_passthrough_model: called CC=4 SCAR=14.5
Pod documented
378 223 my ($self, $model) = @_;
379 223 ▶ return 0 unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 0 223 223
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
00223
MC/DC0%0/2
defined $model and length $model
defined $model length $model
Truth table33%1/3
A and B
A= defined $modelB= length $model
ABresult
0X0
100
111
380 223 my @r = eval { $self->resolve($model, skip_default => 1) };
381 223 ▶ return @r ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
@r ? : 158 65 223
382 }
383  
384  
385 120 ▶sub discovered_url {
Subroutine discovered_url: called CC=6 SCAR=18.7
Pod documented
386 120 my ($self, $model) = @_;
387 120 ▶ return unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 0 120 120
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
00120
MC/DC0%0/2
defined $model and length $model
defined $model length $model
Truth table33%1/3
A and B
A= defined $modelB= length $model
ABresult
0X0
100
111
388 120 ▶ return if $self->config->models->{$model};
Branch: 1 branch
BranchTrueFalseTotal
if $self->config->models->{$model} 6 114 120
389 114 ▶ $self->_discover_models unless $self->_discovery_done;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_discovery_done 28 86 114
390 114 ▶ my $def = $self->_discovered_models->{$model} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $def = $self->_discovered_models->{$model} or return 114 0 114
391 114 return $def->{discovered_url};
392 }
393  
394  
395  
396 50 1;
397  
398 __END__
399  
400 =pod
401  
402 =encoding UTF-8
403  
404 =head1 NAME
405  
406 Langertha::Knarr::Router - Model name to Langertha engine routing with caching
407  
408 =head1 VERSION
409  
410 version 1.102
411  
412 =head1 SYNOPSIS
413  
414 use Langertha::Knarr::Router;
415  
416 my $router = Langertha::Knarr::Router->new(config => $config);
417  
418 my ($engine, $model) = $router->resolve('gpt-5.6-terra');
419 my $result = $engine->simple_chat(@messages);
420  
421 my $models = $router->list_models;
422  
423 =head1 DESCRIPTION
424  
425 Resolves a model name to a Langertha engine instance and canonical model
426 identifier. Engine instances are cached per engine, URL, API key variable,
427 model and C<context_size>, and reused across requests to avoid repeated construction overhead. Two
428 models on the same endpoint get two instances, each carrying its own model.
429  
430 Engine classes are resolved from both C<Langertha::Engine::*> and
431 C<LangerthaX::Engine::*>.
432  
433 When C<auto_discover> is enabled in the config, the router queries each
434 configured endpoint (engine, URL and API key variable) for its full model list on first use, making all discovered
435 models available as routing targets.
436  
437 A model id several endpoints list belongs to one of them, the same one on
438 every run: an endpoint that is the passthrough upstream of some protocol
439 (L<Langertha::Knarr::Config/passthrough>, compared with
440 L<Langertha::Knarr::Handler::Passthrough/same_upstream>) before any other,
441 then by model config name. The other endpoints listing it are logged at
442 debug level.
443  
444 A discovered model is routed with the config of the model entry it was
445 discovered through, minus the keys that describe that one model. The keys
446 split into two groups:
447  
448 =over
449  
450 =item * Endpoint-level, inherited: C<engine>, C<url>, C<api_key_env>,
451 C<api_key> (where and how to reach the upstream), and C<system_prompt>,
452 C<temperature>, C<response_size> (the operator's request policy for that
453 endpoint; a C<response_size> is a cap on the answer, not a property of the
454 model).
455  
456 =item * Model-specific, not inherited: C<model> (replaced by the discovered
457 id) and C<context_size> (a context window belongs to one model; another
458 model on the same endpoint may hold less, and on Ollama it sizes the
459 loaded model through C<num_ctx>). A discovered model gets no
460 C<context_size>, so the engine and upstream defaults apply.
461  
462 =back
463  
464 C<user_agent_timeout> is endpoint-level too: the seconds Langertha waits
465 for that upstream. A model config without one gets
466 L<Langertha::Knarr::Config/upstream_timeout> (default C<300>); C<0> in
467 either leaves the engine without a timeout.
468  
469 Any other key is inherited. A new per-model key belongs in the
470 model-specific group.
471  
472 =head2 config
473  
474 The L<Langertha::Knarr::Config> object. Required.
475  
476 =head2 capabilities_generation
477  
478 A counter that grows every time L</probe_capabilities_f> finishes probing an
479 engine instance. What an engine reports through C<supports()> may have
480 changed then, so anything that caches capabilities (the manifest) keys on it.
481  
482 =head2 resolve
483  
484 my ($engine, $model) = $router->resolve($model_name, %opts);
485 my ($engine, $model) = $router->resolve($model_name, skip_default => 1);
486  
487 Resolves C<$model_name> to a Langertha engine instance and the canonical model
488 string to use with that engine. The resolution order is:
489  
490 =over
491  
492 =item 1. Explicit model config in L<Langertha::Knarr::Config/models>
493  
494 =item 2. Auto-discovered models (if C<auto_discover> is enabled)
495  
496 =item 3. The default engine from L<Langertha::Knarr::Config/default_engine>
497 (skipped when C<skip_default =E<gt> 1> is passed)
498  
499 =back
500  
501 On the default engine a named model replaces the C<model> of the
502 C<default:> section, so the client's model reaches the provider as asked.
503 Without a model name (C<undef> or empty -- an A2A request never names one)
504 only the default engine can answer, and it answers as configured: with its
505 own C<model>, or with the provider's default when C<default:> names none
506 (the third return value is then true and the returned model C<undef>).
507  
508 The third return value is true when the matched model config has no
509 C<model> key: the engine is then built without a model, the provider's
510 default answers, and the returned model string is just the requested alias.
511 L<Langertha::Knarr::Handler::Router> uses it to report the model that
512 answered instead of the alias.
513  
514 my ($engine, $model, $alias_only) = $router->resolve($model_name);
515  
516 Croaks if the model cannot be resolved, and croaks C<No model specified>
517 when no model is named and there is no default engine. Pass
518 C<skip_default =E<gt> 1> to allow the caller to try passthrough before
519 falling back to the default engine; with it, an unresolved or missing model
520 name returns an empty list.
521  
522 =head2 list_models
523  
524 my $models = $router->list_models;
525  
526 Returns an ArrayRef of model hashrefs, each with keys C<id>, C<engine>,
527 C<model>, and C<source> (either C<configured> or C<discovered>). Triggers
528 auto-discovery if not already done. Used to build the model list responses
529 for C<GET /v1/models> and C<GET /api/tags>.
530  
531 =head2 probe_capabilities_f
532  
533 $router->probe_capabilities_f( loop => $loop )->get;
534  
535 Asks each routed engine instance once which capabilities its model has, from
536 the provider's own model metadata (Langertha core's
537 C<probe_model_capabilities_f>, ADR 0032; today that is C<image_input>). The
538 facts are stored on the very instance L</resolve> hands out, so
539 C<POST /api/show> (C<vision>) and the provider manifest (C<image_input>) pick
540 them up without further work.
541  
542 Every model L</list_models> shows is resolved (running auto-discovery first
543 when it is enabled and has not run yet), and every distinct engine instance
544 behind them is covered. An instance is skipped when the installed core has no
545 probe (Langertha 0.503), when its engine implements none
546 (C<model_metadata_format> is undefined: only OpenRouter, Mistral, LM Studio,
547 T-Systems, Ollama and llama.cpp read model metadata; the others would answer
548 C<{}> without a request anyway), when it has no model to ask about, or when
549 it was covered before. Calling the method again therefore covers only engine
550 instances that are new since the last call, such as the ones a later
551 discovery added.
552  
553 How an instance is covered depends on its metadata document:
554  
555 =over
556  
557 =item * A catalogue (OpenRouter, Mistral, LM Studio, T-Systems: one document
558 names every model; C<< Langertha::ModelProbe->is_catalogue >>) is fetched
559 once per endpoint (engine, URL and API key variable, the same key discovery
560 uses) with C<< models => 'all' >>, and what it taught is imported into every
561 other instance of that endpoint with C<import_learned_capabilities>, without
562 a request. A gateway with hundreds of discovered models costs one request.
563 Facts never cross endpoints: two OpenRouter entries with different URLs are
564 two catalogues. An instance that appears on an endpoint whose catalogue was
565 already learned imports it; after a failed catalogue probe the next call
566 asks again for the new instances only. A core without
567 C<import_learned_capabilities> probes every instance on its own, as below.
568  
569 =item * A per-model document (Ollama C</api/show>, llama.cpp) is asked once
570 per instance, for that instance's upstream model.
571  
572 =back
573  
574 The probes run concurrently, at most four at a time. A probe that fails or
575 takes longer than L<Langertha::Knarr::Config/probe_timeout> seconds (only
576 when C<loop> is given) is logged as a warning and not retried; the engines
577 it would have taught keep the capabilities they had. The returned Future
578 never fails and resolves to the number of engine instances covered (probed
579 or imported into). With L<Langertha::Knarr::Config/probe_capabilities> off
580 it resolves to C<0> at once.
581  
582 L<Langertha::Knarr/start> calls this once the server listens.
583  
584 =head2 is_passthrough_model
585  
586 next if $router->is_passthrough_model($model);
587  
588 True when the router cannot resolve C<$model> without the default engine:
589 neither configured nor auto-discovered.
590  
591 =head2 discovered_url
592  
593 my $url = $router->discovered_url($model);
594  
595 For a model known only through auto-discovery (not in
596 L<Langertha::Knarr::Config/models>), the base URL of the engine that listed
597 it; C<undef> for a configured or unknown model, or when the engine has no
598 C<url>. L<Langertha::Knarr> sends such a model to the raw passthrough when
599 it was listed by the passthrough upstream of the client's protocol and the
600 client sends its own provider key.
601  
602 =head1 SEE ALSO
603  
604 =over
605  
606 =item * L<Langertha::Knarr> — Main documentation; the routing order is described under L</resolve> above
607  
608 =item * L<Langertha::Knarr::Config> — Provides model and engine configuration
609  
610 =back
611  
612 =head1 SUPPORT
613  
614 =head2 Issues
615  
616 Please report bugs and feature requests on GitHub at
617 L<https://github.com/Getty/langertha-knarr/issues>.
618  
619 =head2 IRC
620  
621 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
622  
623 =head1 CONTRIBUTING
624  
625 Contributions are welcome! Please fork the repository and submit a pull request.
626  
627 =head1 AUTHOR
628  
629 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
630  
631 =head1 COPYRIGHT AND LICENSE
632  
633 This software is copyright (c) 2026 by Torsten Raudssus.
634  
635 This is free software; you can redistribute it and/or modify it under
636 the same terms as the Perl 5 programming language system itself.
637  
638 =cut
« blib/lib/Langertha/Knarr/Tracing.pm ↑ Summary blib/lib/Langertha/Knarr/Manifest.pm »