blib/lib/Langertha/Knarr/Handler/Router.pm

filter: Statementstmt 100% 93 / 93 Branchbran 91.6% 44 / 48 Conditioncond 71.4% 25 / 35 MC/DCmcdc 47.3% 9 / 19 Subroutinesub 100% 15 / 15 Podpod 0.0% 0 / 3 totaltotal 87.3% 186 / 213 CC 37 SCAR 20.4
CC
37
Cov
92%
__ANON__
15.3
_resolve
8.1
handle_chat_f
6.0
CRAP 7.7
« blib/lib/Langertha/Knarr/RequestLog.pm ↑ Summary blib/lib/Langertha/Knarr/Response.pm »
1 package Langertha::Knarr::Handler::Router;
2 # ABSTRACT: Knarr handler that resolves model names via Langertha::Knarr::Router and dispatches to engines
3 26 our $VERSION = '1.102';
4 26 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 26 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 26 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 26 ▶use Future::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 26 ▶use Langertha::Knarr::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 26 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 26 with 'Langertha::Knarr::Handler';
12  
13  
14 # Wraps a Langertha::Knarr::Router (which is Moo) and uses it to resolve
15 # incoming model names to Langertha engine instances. Also keeps the
16 # upstream Knarr::Config visible for the rest of the request lifecycle.
17  
18 26 has router => ( is => 'ro', required => 1 );
19  
20 # Optional Passthrough handler used as fallback when the router can't
21 # resolve a model. Allows mixed mode: configured models go via Langertha
22 # engines (with tracing/middleware support), unknown models tunnel straight
23 # to the upstream API the client thinks they're talking to.
24 has passthrough => (
25 is => 'ro',
26 isa => 'Maybe[Object]',
27 53 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
28 26 );
29  
30 # The engine for a request, or () when it goes to the passthrough. Unknown
31 # models go to the passthrough only when it can forward the client's
32 # protocol; otherwise to the default engine (k41). With neither, the
33 # failure carries the category 'model_not_found', which Knarr answers as a
34 # 404 in the client protocol's error shape.
35 #
36 # A request without a model (A2A never names one) is resolved as such, not
37 # as a placeholder name: the default engine then answers with its own
38 # configured model instead of being sent a model called 'default' (k42).
39 181 ▶sub _resolve {
Subroutine _resolve: called CC=8 SCAR=20.9
40 181 my ($self, $request) = @_;
41 181 my $model = $request->model;
42 181 my $router = $self->router;
43 181 ▶ if ( $self->_passthrough_serves( $request->protocol ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_passthrough_serves($request->protocol)) 98 83 181
44 # With passthrough: try without default engine first so unknown models
45 # go to passthrough instead of being routed to the default engine.
46 98 my @r = eval { $router->resolve($model, skip_default => 1) };
47 98 ▶ return @r if @r;
Branch: 1 branch
BranchTrueFalseTotal
if @r 79 19 98
48 19 return (); # not found or error → passthrough
49 }
50 83 my @r = $router->resolve($model, skip_default => 1);
51 82 ▶ return @r if @r;
Branch: 1 branch
BranchTrueFalseTotal
if @r 31 51 82
52 51 ▶ return $router->resolve($model) if $router->config->default_engine;
Branch: 1 branch
BranchTrueFalseTotal
if $router->config->default_engine 35 16 51
53 16 ▶ die Future::Exception->new(
Branch: 2 branches
BranchTrueFalseTotal
defined $model && length $model ? : 16 0 16
$self->passthrough ? : 8 8 16
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
0016
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
54 ( defined $model && length $model ? "Model '$model' is not configured" : 'The request names no model' )
55 . ' and there is no default engine'
56 . ( $self->passthrough ? ' (no passthrough upstream for '.$request->protocol.')' : '' ),
57 'model_not_found' );
58 }
59  
60 181 ▶sub _passthrough_serves {
Subroutine _passthrough_serves: called CC=3 SCAR=11.0
61 181 my ($self, $protocol) = @_;
62 181 ▶ my $pt = $self->passthrough or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $pt = $self->passthrough or return 0 129 52 181
63 129 ▶ return $pt->can('serves_protocol') ? $pt->serves_protocol($protocol) : 1;
Branch: 1 branch
BranchTrueFalseTotal
$pt->can('serves_protocol') ? : 127 2 129
64 }
65  
66 98 ▶async sub handle_chat_f {
Subroutine handle_chat_f: called CC=6 SCAR=17.9
Pod undocumented
67 98 my ($self, $session, $request) = @_;
68 98 my ($engine, $canonical_model, $alias_only) = $self->_resolve($request);
69 89 ▶ unless ( $engine ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($engine) 7 82 89
70 7 return Langertha::Knarr::Response->coerce(
71 await $self->passthrough->handle_chat_f( $session, $request )
72 );
73 }
74 82 my $response = await $engine->chat_f( $request->chat_f_args($engine) );
75 75 my $r = Langertha::Knarr::Response->coerce($response);
76 # An alias without a configured model: the provider default answered, so
77 # report the model that answered, never the alias (k22).
78 75 ▶ if ( $alias_only ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alias_only) 9 66 75
79 9 ▶ return $r if defined $r->model;
Branch: 1 branch
BranchTrueFalseTotal
if defined $r->model 4 5 9
80 5 ▶ my $chat_model = $engine->can('chat_model') ? $engine->chat_model : undef;
Branch: 1 branch
BranchTrueFalseTotal
$engine->can('chat_model') ? : 5 0 5
81 5 ▶ return defined $chat_model ? $r->clone_with( model => $chat_model ) : $r;
Branch: 1 branch
BranchTrueFalseTotal
defined $chat_model ? : 2 3 5
82 }
83 # The client sees the configured name, as /v1/models lists it; the model
84 # the upstream reported goes to the trace (k70).
85 66 return $r->clone_with( model => $canonical_model, upstream_model => $r->model );
86 26 }
87  
88 83 ▶async sub handle_stream_f {
Subroutine handle_stream_f: called CC=5 SCAR=16.1
Pod undocumented
89 83 my ($self, $session, $request) = @_;
90 83 my ($engine, $canonical_model, $alias_only) = $self->_resolve($request);
91  
92 75 ▶ unless ( $engine ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($engine) 12 63 75
93 12 return await $self->passthrough->handle_stream_f( $session, $request );
94 }
95  
96 63 ▶ unless ( _supports_streaming($engine) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_supports_streaming($engine)) 20 43 63
97 20 my $r = await $self->handle_chat_f($session, $request);
98 20 my $stream = Langertha::Knarr::Stream->from_list( $r->content );
99 20 $stream->finish_reason( $r->finish_reason );
100 20 $stream->tool_calls( $r->tool_calls );
101 20 ▶ $stream->usage( $r->usage ) if $r->usage;
Branch: 1 branch
BranchTrueFalseTotal
if $r->usage 0 20 20
102 20 $stream->model( $r->model );
103 20 $stream->upstream_model( $r->upstream_model );
104 20 return $stream;
105 }
106  
107 43 ▶ my $stream = Langertha::Knarr::Stream->from_callback( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
108 43 my ($emit, $done, $fail, $finish, $tool_call, $usage, $model) = @_;
109 92 ▶ my $cb = sub {
Subroutine __ANON__: called CC=15 SCAR=27.3
110 92 my ($chunk) = @_;
111 92 ▶ my $text = ref $chunk && $chunk->can('content') ? $chunk->content : "$chunk";
Branch: 1 branch
BranchTrueFalseTotal
ref $chunk && $chunk->can('content') ? : 86 6 92
Condition66%2/3
ref $chunk and $chunk->can("content")
!ll&&!rl&&r
6086
MC/DC50%1/2
ref $chunk and $chunk->can("content")
ref $chunk $chunk->can("content")
Truth table66%2/3
A and B
A= ref $chunkB= $chunk->can("content")
ABresult
0X0
100
111
112 92 $emit->($text);
113 # Langertha::Stream::Chunk carries the backend's finish_reason on the
114 # terminal chunk; the protocol maps it when it closes the stream.
115 92 ▶ $finish->( $chunk->finish_reason )
Branch: 1 branch
BranchTrueFalseTotal
if ref $chunk and $chunk->can("has_finish_reason") and $chunk->has_finish_reason 28 64 92
Condition83%5/6
ref $chunk and $chunk->can("has_finish_reason") and $chunk->has_finish_reason
!ll&&!rl&&r
65828
ref $chunk and $chunk->can("has_finish_reason")
!ll&&!rl&&r
6086
MC/DC66%2/3
ref $chunk and $chunk->can("has_finish_reason") and $chunk->has_finish_reason
ref $chunk $chunk->can("has_finish_reason") $chunk->has_finish_reason
Truth table75%3/4
A and B and C
A= ref $chunkB= $chunk->can("has_finish_reason")C= $chunk->has_finish_reason
ABCresult
0XX0
10X0
1100
1111
116 if ref $chunk && $chunk->can('has_finish_reason') && $chunk->has_finish_reason;
117 # Core assembles streamed tool-call fragments and attaches the finished
118 # Langertha::ToolCall objects to a chunk (Role::Chat::aggregate_tool_calls
119 # collects the same); a core whose parser attaches none yields none. The
120 # protocol emits them when it closes the stream (k19).
121 92 ▶ $tool_call->( @{ $chunk->tool_calls } )
Branch: 1 branch
BranchTrueFalseTotal
if ref $chunk and $chunk->can("has_tool_calls") and $chunk->has_tool_calls 2 90 92
Condition83%5/6
ref $chunk and $chunk->can("has_tool_calls") and $chunk->has_tool_calls
!ll&&!rl&&r
6842
ref $chunk and $chunk->can("has_tool_calls")
!ll&&!rl&&r
6086
MC/DC66%2/3
ref $chunk and $chunk->can("has_tool_calls") and $chunk->has_tool_calls
ref $chunk $chunk->can("has_tool_calls") $chunk->has_tool_calls
Truth table75%3/4
A and B and C
A= ref $chunkB= $chunk->can("has_tool_calls")C= $chunk->has_tool_calls
ABCresult
0XX0
10X0
1100
1111
122 if ref $chunk && $chunk->can('has_tool_calls') && $chunk->has_tool_calls;
123 # The token usage rides on a chunk too, cumulative (the last report is
124 # the stream's totals); the protocol puts it on its terminal frames and
125 # the tracing decorator on the generation.
126 92 ▶ $usage->( $chunk->usage )
Branch: 1 branch
BranchTrueFalseTotal
if ref $chunk and $chunk->can("has_usage") and $chunk->has_usage 20 72 92
Condition83%5/6
ref $chunk and $chunk->can("has_usage") and $chunk->has_usage
!ll&&!rl&&r
66620
ref $chunk and $chunk->can("has_usage")
!ll&&!rl&&r
6086
MC/DC66%2/3
ref $chunk and $chunk->can("has_usage") and $chunk->has_usage
ref $chunk $chunk->can("has_usage") $chunk->has_usage
Truth table75%3/4
A and B and C
A= ref $chunkB= $chunk->can("has_usage")C= $chunk->has_usage
ABCresult
0XX0
10X0
1100
1111
127 if ref $chunk && $chunk->can('has_usage') && $chunk->has_usage;
128 # The model the backend reports answering with, for the trace.
129 92 ▶ $model->( $chunk->model )
Branch: 1 branch
BranchTrueFalseTotal
if ref $chunk and $chunk->can("has_model") and $chunk->has_model 49 43 92
Condition83%5/6
ref $chunk and $chunk->can("has_model") and $chunk->has_model
!ll&&!rl&&r
63749
ref $chunk and $chunk->can("has_model")
!ll&&!rl&&r
6086
MC/DC66%2/3
ref $chunk and $chunk->can("has_model") and $chunk->has_model
ref $chunk $chunk->can("has_model") $chunk->has_model
Truth table75%3/4
A and B and C
A= ref $chunkB= $chunk->can("has_model")C= $chunk->has_model
ABCresult
0XX0
10X0
1100
1111
130 if ref $chunk && $chunk->can('has_model') && $chunk->has_model;
131 43 };
132 43 my $f = $engine->chat_stream_realtime_f( chunk_callback => $cb, $request->chat_f_args($engine) );
133 43 $f->on_done( $done );
134 43 $f->on_fail( $fail );
135 43 $f->retain;
136 43 });
137 # Labeled like the non-streaming answer: the configured model, unless the
138 # config names none and the provider default answers (k22).
139 43 ▶ $stream->model($canonical_model) unless $alias_only;
Branch: 1 branch
BranchTrueFalseTotal
unless $alias_only 40 3 43
140 43 return $stream;
141 26 }
142  
143 63 ▶sub _supports_streaming {
Subroutine _supports_streaming: called CC=3 SCAR=11.4
144 63 my ($engine) = @_;
145 63 ▶ return $engine->supports('streaming') if $engine->can('supports');
Branch: 1 branch
BranchTrueFalseTotal
if $engine->can("supports") 43 20 63
146 20 ▶ return $engine->can('simple_chat_stream_realtime_f') && $engine->can('chat_stream_request');
Condition33%1/3
$engine->can('simple_chat_stream_realtime_f') && $engine->can('chat_stream_request')
!ll&&!rl&&r
2000
MC/DC0%0/2
$engine->can('simple_chat_stream_realtime_f') && $engine->can('chat_stream_request')
$engine->can('simple_chat_stream_realtime_f') $engine->can('chat_stream_request')
Truth table33%1/3
A && B
A= $engine->can('simple_chat_stream_realtime_f')B= $engine->can('chat_stream_request')
ABresult
0X0
100
111
147 }
148  
149 1 ▶sub list_models {
Subroutine list_models: called CC=3 SCAR=11.3
Pod undocumented
150 1 my ($self) = @_;
151 1 my $models = $self->router->list_models;
152 1 ▶ return [ map { ref $_ eq 'HASH' ? $_ : { id => "$_", object => 'model' } } @{ $models || [] } ];
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 5 0 5
Condition50%1/2
$models || []
l!l
10
MC/DC0%0/1
$models || []
$models
Truth table50%1/2
A
A= $models
Aresult
11
00
153 }
154  
155 26 __PACKAGE__->meta->make_immutable;
156 26 1;
157  
158 __END__
159  
160 =pod
161  
162 =encoding UTF-8
163  
164 =head1 NAME
165  
166 Langertha::Knarr::Handler::Router - Knarr handler that resolves model names via Langertha::Knarr::Router and dispatches to engines
167  
168 =head1 VERSION
169  
170 version 1.102
171  
172 =head1 SYNOPSIS
173  
174 use Langertha::Knarr::Config;
175 use Langertha::Knarr::Router;
176 use Langertha::Knarr::Handler::Router;
177 use Langertha::Knarr::Handler::Passthrough;
178  
179 my $config = Langertha::Knarr::Config->new(file => 'knarr.yaml');
180 my $router = Langertha::Knarr::Router->new(config => $config);
181  
182 my $handler = Langertha::Knarr::Handler::Router->new(
183 router => $router,
184 passthrough => Langertha::Knarr::Handler::Passthrough->new(
185 upstreams => $config->passthrough,
186 ),
187 );
188  
189 =head1 DESCRIPTION
190  
191 Resolves incoming model names against a L<Langertha::Knarr::Router>
192 (which knows your C<knarr.yaml>) and dispatches to the matched
193 L<Langertha::Engine>. When a passthrough fallback handler is supplied,
194 unknown model names in a protocol it serves tunnel through to it instead
195 of falling back to the default engine — this preserves the classic Knarr
196 behaviour where configured models go via Langertha and everything else
197 passes straight to the upstream API.
198  
199 Non-streaming answers are labeled with the configured model. For a model
200 config without a C<model> key the provider's default answers, so the
201 response keeps the model the upstream reported, else the engine's
202 C<chat_model>; it is never relabeled with the alias.
203  
204 The client keeps seeing the configured name -- the id C</v1/models> lists
205 and the one it can ask for again -- even where the upstream reported a more
206 concrete one (C<gpt-4o> answering as C<gpt-4o-2024-08-06>). No protocol
207 requires otherwise: Ollama echoes the name asked for, and the C<model> of an
208 OpenAI or Anthropic answer, where the provider puts its concrete name, is
209 informational -- clients do not match it against the request. The
210 reported model is kept as L<Langertha::Knarr::Response/upstream_model> (on a
211 stream L<Langertha::Knarr::Stream/upstream_model>, the configured name as
212 its C<model>), and L<Langertha::Knarr::Handler::Tracing> records it as the
213 Langfuse generation's model, the configured name in its metadata.
214  
215 A request that names no model (A2A always; ACP without C<agent_name>, and
216 any other protocol whose body leaves the model out) goes to the default
217 engine with the C<model> configured under C<default:>, or with the
218 provider's default when none is configured -- see
219 L<Langertha::Knarr::Router/resolve>. A model the client does name reaches
220 the default engine as asked.
221  
222 Streaming responses are pumped via the engine's
223 C<chat_stream_realtime_f> for native token-by-token delivery, with the
224 same capability-filtered generation parameters as the non-streaming path.
225  
226 =head2 router
227  
228 Required. A L<Langertha::Knarr::Router> instance.
229  
230 =head2 passthrough
231  
232 Optional. Any L<Langertha::Knarr::Handler> consumer used as a fallback
233 when the router can't resolve a model. A handler with a C<serves_protocol>
234 method (L<Langertha::Knarr::Handler::Passthrough>) only gets requests in the
235 protocols it can forward; an unknown model in any other protocol goes to the
236 default engine instead.
237  
238 When the router can't resolve a model, no passthrough serves the request's
239 protocol and there is no default engine, the handler fails with the
240 category C<model_not_found>; L<Langertha::Knarr> answers that with a C<404>
241 in the client protocol's error shape.
242  
243 =head1 SUPPORT
244  
245 =head2 Issues
246  
247 Please report bugs and feature requests on GitHub at
248 L<https://github.com/Getty/langertha-knarr/issues>.
249  
250 =head2 IRC
251  
252 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
253  
254 =head1 CONTRIBUTING
255  
256 Contributions are welcome! Please fork the repository and submit a pull request.
257  
258 =head1 AUTHOR
259  
260 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
261  
262 =head1 COPYRIGHT AND LICENSE
263  
264 This software is copyright (c) 2026 by Torsten Raudssus.
265  
266 This is free software; you can redistribute it and/or modify it under
267 the same terms as the Perl 5 programming language system itself.
268  
269 =cut
« blib/lib/Langertha/Knarr/RequestLog.pm ↑ Summary blib/lib/Langertha/Knarr/Response.pm »