blib/lib/Langertha/Knarr/Stream.pm

filter: Statementstmt 97.5% 121 / 124 Branchbran 89.7% 61 / 68 Conditioncond 62.7% 27 / 43 MC/DCmcdc 44.4% 12 / 27 Subroutinesub 100% 25 / 25 Podpod 90.0% 9 / 10 totaltotal 85.8% 255 / 297 CC 50 SCAR 14.3
CC
50
Cov
89%
usage
7.0
tool_calls
6.0
__ANON__
6.0
CRAP 4.2
« blib/lib/Langertha/Knarr/Protocol/AGUI.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/Anthropic.pm »
1 package Langertha::Knarr::Stream;
2 # ABSTRACT: Async chunk iterator returned by streaming Knarr handlers
3 92 our $VERSION = '1.102';
4 92 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 92 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 92 ▶use Scalar::Util qw( blessed weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 92 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9  
10 85 ▶sub from_callback {
Subroutine from_callback: called CC=1 SCAR=0.1
Pod documented
11 85 my ($class, $setup) = @_;
12 85 my @queue;
13 my $pending;
14 85 my $finished = 0;
15 85 my @error;
16  
17 185 ▶ my $deliver = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
18 185 my ($v) = @_;
19 185 ▶ if ( $pending ) { my $p = $pending; $pending = undef; $p->done($v) }
Branch: 1 branch
BranchTrueFalseTotal
if ($pending) { } 24 161 185
20 161 else { push @queue, $v }
21 85 };
22  
23 227 ▶ my $emit = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
24 227 my ($chunk) = @_;
25 227 ▶ return unless defined $chunk && length $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk and length $chunk 114 113 227
Condition66%2/3
defined $chunk and length $chunk
!ll&&!rl&&r
0114113
MC/DC50%1/2
defined $chunk and length $chunk
defined $chunk length $chunk
Truth table66%2/3
A and B
A= defined $chunkB= length $chunk
ABresult
0X0
100
111
26 113 $deliver->($chunk);
27 85 };
28 85 ▶ my $done = sub { $finished = 1; $deliver->(undef) };
Subroutine __ANON__: called CC=1 SCAR=0.0
29 # The whole failure is kept, not just its message: a timeout's category
30 # (the second value, k36) has to reach the protocol. A read already
31 # waiting gets the failure too, not an undef that would end the stream
32 # as if it were complete.
33 13 ▶ my $fail = sub {
Subroutine __ANON__: called CC=4 SCAR=15.5
34 13 ▶ @error = ( $_[0] // 'unknown error', @_[ 1 .. $#_ ] );
Condition50%1/2
$_[0] // "unknown error"
l!l
130
MC/DC0%0/1
$_[0] // "unknown error"
$_[0]
Truth table50%1/2
A
A= $_[0]
Aresult
11
00
35 13 $finished = 1;
36 13 ▶ if ( $pending && $error[0] ) { my $p = $pending; $pending = undef; $p->fail(@error) }
Branch: 1 branch
BranchTrueFalseTotal
if ($pending and $error[0]) { } 13 0 13
Condition33%1/3
$pending and $error[0]
!ll&&!rl&&r
0013
MC/DC0%0/2
$pending and $error[0]
$pending $error[0]
Truth table33%1/3
A and B
A= $pendingB= $error[0]
ABresult
0X0
100
111
37 0 else { $deliver->(undef) }
38 85 };
39  
40 my $stream = $class->new(
41 198 ▶ source => sub {
Subroutine __ANON__: called CC=4 SCAR=15.2
42 198 ▶ if ( @queue ) { return Future->done( shift @queue ) }
Branch: 1 branch
BranchTrueFalseTotal
if (@queue) 161 37 198
43 37 ▶ if ( $finished ) { return $error[0] ? Future->fail(@error) : Future->done(undef) }
Branch: 2 branches
BranchTrueFalseTotal
if ($finished) 0 37 37
$error[0] ? : 0 0 0
44 37 $pending = Future->new;
45 37 return $pending;
46 },
47 85 );
48  
49 # The producer may outlive a consumer that dropped the stream; it must
50 # not keep the stream alive for it.
51 85 my $weak = $stream;
52 85 weaken $weak;
53 68 ▶ my $finish = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
54 68 my ($reason) = @_;
55 68 ▶ $weak->finish_reason($reason) if $weak && defined $reason;
Branch: 1 branch
BranchTrueFalseTotal
if $weak and defined $reason 66 2 68
Condition66%2/3
$weak and defined $reason
!ll&&!rl&&r
0266
MC/DC50%1/2
$weak and defined $reason
$weak defined $reason
Truth table66%2/3
A and B
A= $weakB= defined $reason
ABresult
0X0
100
111
56 85 };
57 36 ▶ my $tool_call = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
58 36 my @calls = grep { defined } @_;
59 36 ▶ $weak->tool_calls( [ @{ $weak->_tool_calls // [] }, @calls ] ) if $weak && @calls;
Branch: 1 branch
BranchTrueFalseTotal
if $weak and @calls 35 1 36
Condition80%4/5
$weak and @calls
!ll&&!rl&&r
0135
$weak->_tool_calls // []
l!l
1718
MC/DC50%1/2
$weak and @calls
$weak @calls
MC/DC100%1/1
$weak->_tool_calls // []
$weak->_tool_calls
Truth table66%2/3
A and B
A= $weakB= @calls
ABresult
0X0
100
111
Truth table100%2/2
A
A= $weak->_tool_calls
Aresult
11
00
60 85 };
61 # Every dialect reports cumulative usage, the last report being the
62 # stream's totals -- not always on the final chunk: OpenAI's include_usage
63 # frame comes after it.
64 30 ▶ my $usage = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
65 30 my ($u) = @_;
66 30 ▶ $weak->usage($u) if $weak && $weak->_usable_usage($u);
Branch: 1 branch
BranchTrueFalseTotal
if $weak and $weak->_usable_usage($u) 28 2 30
Condition66%2/3
$weak and $weak->_usable_usage($u)
!ll&&!rl&&r
0228
MC/DC50%1/2
$weak and $weak->_usable_usage($u)
$weak $weak->_usable_usage($u)
Truth table66%2/3
A and B
A= $weakB= $weak->_usable_usage($u)
ABresult
0X0
100
111
67 85 };
68  
69 70 ▶ my $model = sub {
Subroutine __ANON__: called CC=4 SCAR=17.9
70 70 my ($name) = @_;
71 70 ▶ $weak->upstream_model($name) if $weak && defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
if $weak and defined $name and length $name 70 0 70
Condition33%2/6
$weak and defined $name and length $name
!ll&&!rl&&r
0070
$weak and defined $name
!ll&&!rl&&r
0070
MC/DC0%0/3
$weak and defined $name and length $name
$weak defined $name length $name
Truth table25%1/4
A and B and C
A= $weakB= defined $nameC= length $name
ABCresult
0XX0
10X0
1100
1111
72 85 };
73  
74 85 $setup->($emit, $done, $fail, $finish, $tool_call, $usage, $model);
75  
76 85 return $stream;
77 }
78  
79 # Two ways to construct:
80 # 1) generator => sub { ... } — sync coderef returning next string or undef
81 # 2) source => sub { ... } — coderef returning a Future[string|undef]
82 92 has generator => ( is => 'ro', isa => 'Maybe[CodeRef]' );
83 92 has source => ( is => 'ro', isa => 'Maybe[CodeRef]' );
84 92 has upstream => ( is => 'ro', isa => 'Maybe[Object]' );
85  
86 92 has _finish_reason => (
87 is => 'rw',
88 isa => 'Maybe[Str]',
89 init_arg => 'finish_reason',
90 );
91  
92 393 ▶sub finish_reason {
Subroutine finish_reason: called CC=5 SCAR=16.1
Pod documented
93 393 my $self = shift;
94 393 ▶ return $self->_finish_reason(@_) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 128 265 393
95 265 my $own = $self->_finish_reason;
96 265 ▶ return $own if defined $own;
Branch: 1 branch
BranchTrueFalseTotal
if defined $own 87 178 265
97 178 my $up = $self->upstream;
98 178 ▶ return $up && $up->can('finish_reason') ? $up->finish_reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
$up && $up->can('finish_reason') ? : 24 154 178
Condition66%2/3
$up and $up->can("finish_reason")
!ll&&!rl&&r
154024
MC/DC50%1/2
$up and $up->can("finish_reason")
$up $up->can("finish_reason")
Truth table66%2/3
A and B
A= $upB= $up->can("finish_reason")
ABresult
0X0
100
111
99 }
100  
101 92 has _tool_calls => (
102 is => 'rw',
103 isa => 'Maybe[ArrayRef]',
104 init_arg => 'tool_calls',
105 );
106  
107 391 ▶sub tool_calls {
Subroutine tool_calls: called CC=6 SCAR=17.9
Pod documented
108 391 my $self = shift;
109 391 ▶ return $self->_tool_calls(@_) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 68 323 391
110 323 my $own = $self->_tool_calls;
111 323 ▶ return $own if $own && @$own;
Branch: 1 branch
BranchTrueFalseTotal
if $own and @$own 38 285 323
Condition100%3/3
$own and @$own
!ll&&!rl&&r
2652038
MC/DC100%2/2
$own and @$own
$own @$own
Truth table100%3/3
A and B
A= $ownB= @$own
ABresult
0X0
100
111
112 285 my $up = $self->upstream;
113 285 ▶ return $up->tool_calls if $up && $up->can('tool_calls');
Branch: 1 branch
BranchTrueFalseTotal
if $up and $up->can("tool_calls") 25 260 285
Condition66%2/3
$up and $up->can("tool_calls")
!ll&&!rl&&r
260025
MC/DC50%1/2
$up and $up->can("tool_calls")
$up $up->can("tool_calls")
Truth table66%2/3
A and B
A= $upB= $up->can("tool_calls")
ABresult
0X0
100
111
114 260 return [];
115 }
116  
117 43 ▶sub has_tool_calls { scalar @{ $_[0]->tool_calls } > 0 }
Subroutine has_tool_calls: called CC=1 SCAR=0.0
Pod documented
118  
119 92 has _usage => (
120 is => 'rw',
121 isa => 'Maybe[Object]',
122 init_arg => undef,
123 );
124  
125 352 ▶sub usage {
Subroutine usage: called CC=7 SCAR=19.5
Pod documented
126 352 my $self = shift;
127 352 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 34 318 352
128 34 my ($u) = @_;
129 34 ▶ return $self->_usage( ref $u eq 'HASH' ? ( %$u ? Langertha::Usage->from_hash($u) : undef ) : $u );
Branch: 2 branches
BranchTrueFalseTotal
ref $u eq 'HASH' ? : 33 1 34
%$u ? : 32 1 33
130 }
131 318 my $own = $self->_usage;
132 318 ▶ return $own if $own;
Branch: 1 branch
BranchTrueFalseTotal
if $own 44 274 318
133 274 my $up = $self->upstream;
134 274 ▶ return $up && $up->can('usage') ? $up->usage : undef;
Branch: 1 branch
BranchTrueFalseTotal
$up && $up->can('usage') ? : 24 250 274
Condition66%2/3
$up and $up->can("usage")
!ll&&!rl&&r
250024
MC/DC50%1/2
$up and $up->can("usage")
$up $up->can("usage")
Truth table66%2/3
A and B
A= $upB= $up->can("usage")
ABresult
0X0
100
111
135 }
136  
137 92 has _model => (
138 is => 'rw',
139 isa => 'Maybe[Str]',
140 init_arg => 'model',
141 );
142  
143 103 ▶sub model {
Subroutine model: called CC=5 SCAR=16.1
Pod documented
144 103 my $self = shift;
145 103 ▶ return $self->_model(@_) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 63 40 103
146 40 my $own = $self->_model;
147 40 ▶ return $own if defined $own;
Branch: 1 branch
BranchTrueFalseTotal
if defined $own 25 15 40
148 15 my $up = $self->upstream;
149 15 ▶ return $up && $up->can('model') ? $up->model : undef;
Branch: 1 branch
BranchTrueFalseTotal
$up && $up->can('model') ? : 1 14 15
Condition66%2/3
$up and $up->can("model")
!ll&&!rl&&r
1401
MC/DC50%1/2
$up and $up->can("model")
$up $up->can("model")
Truth table66%2/3
A and B
A= $upB= $up->can("model")
ABresult
0X0
100
111
150 }
151  
152 92 has _upstream_model => (
153 is => 'rw',
154 isa => 'Maybe[Str]',
155 init_arg => 'upstream_model',
156 );
157  
158 133 ▶sub upstream_model {
Subroutine upstream_model: called CC=5 SCAR=16.1
Pod documented
159 133 my $self = shift;
160 133 ▶ return $self->_upstream_model(@_) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 93 40 133
161 40 my $own = $self->_upstream_model;
162 40 ▶ return $own if defined $own;
Branch: 1 branch
BranchTrueFalseTotal
if defined $own 15 25 40
163 25 my $up = $self->upstream;
164 25 ▶ return $up && $up->can('upstream_model') ? $up->upstream_model : undef;
Branch: 1 branch
BranchTrueFalseTotal
$up && $up->can('upstream_model') ? : 1 24 25
Condition66%2/3
$up and $up->can("upstream_model")
!ll&&!rl&&r
2401
MC/DC50%1/2
$up and $up->can("upstream_model")
$up $up->can("upstream_model")
Truth table66%2/3
A and B
A= $upB= $up->can("upstream_model")
ABresult
0X0
100
111
165 }
166  
167 30 ▶sub _usable_usage {
Subroutine _usable_usage: called CC=4 SCAR=13.9
168 30 my ($self, $u) = @_;
169 30 ▶ return ref $u eq 'HASH' ? ( %$u ? 1 : 0 ) : blessed($u) ? 1 : 0;
Branch: 3 branches
BranchTrueFalseTotal
ref $u eq 'HASH' ? : 29 1 30
%$u ? : 28 1 29
builtin::blessed($u) ? : 0 1 1
170 }
171  
172 400 ▶sub BUILD {
Subroutine BUILD: called CC=2 SCAR=6.9
Pod undocumented
173 400 my ($self, $args) = @_;
174 400 ▶ $self->usage( $args->{usage} ) if defined $args->{usage};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"usage"} 5 395 400
175 }
176  
177 857 ▶sub next_chunk_f {
Subroutine next_chunk_f: called CC=3 SCAR=11.2
Pod documented
178 857 my ($self) = @_;
179 857 ▶ if ( my $g = $self->generator ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $g = $self->generator) 377 480 857
180 377 my $v = $g->();
181 377 return Future->done($v);
182 }
183 480 ▶ if ( my $s = $self->source ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $s = $self->source) 480 0 480
184 480 return $s->();
185 }
186 0 return Future->done(undef);
187 }
188  
189 # Convenience: build a stream from a fixed list of chunks
190 26 ▶sub from_list {
Subroutine from_list: called CC=1 SCAR=0.0
Pod documented
191 26 my ($class, @chunks) = @_;
192 26 my @queue = @chunks;
193 26 ▶ return $class->new( generator => sub { @queue ? shift @queue : undef } );
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
@queue ? : 23 23 46
194 }
195  
196 92 __PACKAGE__->meta->make_immutable;
197 92 1;
198  
199 __END__
200  
201 =pod
202  
203 =encoding UTF-8
204  
205 =head1 NAME
206  
207 Langertha::Knarr::Stream - Async chunk iterator returned by streaming Knarr handlers
208  
209 =head1 VERSION
210  
211 version 1.102
212  
213 =head1 SYNOPSIS
214  
215 use Langertha::Knarr::Stream;
216  
217 # From a fixed list of strings
218 my $stream = Langertha::Knarr::Stream->from_list('hel', 'lo');
219  
220 # From a sync generator
221 my @parts = ('hel', 'lo');
222 my $stream = Langertha::Knarr::Stream->new(
223 generator => sub { @parts ? shift @parts : undef },
224 );
225  
226 # From a future-yielding source (real async)
227 my $stream = Langertha::Knarr::Stream->new(
228 source => sub { $next_chunk_future },
229 );
230  
231 # Drain it
232 while ( defined( my $chunk = $stream->next_chunk_f->get ) ) {
233 print $chunk;
234 }
235  
236 =head1 DESCRIPTION
237  
238 The chunk iterator that streaming Knarr handlers return. Supports two
239 construction modes: a sync C<generator> coderef that returns the next
240 chunk string each call (or C<undef> for end), or a C<source> coderef
241 that returns a L<Future> resolving to the next chunk string. The
242 Future form is the one real async backends like L<Net::Async::HTTP>
243 use; the generator form is for tests and simple cases.
244  
245 =head2 generator
246  
247 Optional. CodeRef returning the next chunk synchronously.
248  
249 =head2 source
250  
251 Optional. CodeRef returning a L<Future> that resolves to the next
252 chunk.
253  
254 =head2 finish_reason
255  
256 Optional. The backend's terminal finish reason, verbatim (C<stop>,
257 C<length>, C<tool_calls>, C<end_turn>, C<MAX_TOKENS>, ...), or C<undef>
258 when the backend reported none. Known once the stream is exhausted; the
259 protocol maps it into its own vocabulary when it closes the stream.
260 Settable, since a producer learns it only at the end. A stream that
261 wraps another (see L</upstream>) and has none of its own answers with
262 its upstream's.
263  
264 =head2 tool_calls
265  
266 ArrayRef of complete L<Langertha::ToolCall> objects the backend emitted,
267 empty when it emitted none. Like L</finish_reason> it is known once the
268 stream is exhausted: the protocol emits the calls in its own framing when
269 it closes the stream. Settable; a stream that wraps another and has none
270 of its own answers with its upstream's.
271  
272 =head2 has_tool_calls
273  
274 True when L</tool_calls> holds at least one call.
275  
276 =head2 usage
277  
278 The backend's token usage for the whole stream as a L<Langertha::Usage>, or
279 C<undef> when it reported none. Like L</finish_reason> it is known once the
280 stream is exhausted: the protocol puts it on its terminal frames and the
281 tracing and request-log decorators record it. Settable; a provider usage
282 HashRef (OpenAI C<prompt_tokens>, Anthropic C<input_tokens>, Ollama
283 C<prompt_eval_count>, ...) is upgraded through
284 L<Langertha::Usage/from_hash>, an empty one is no usage. A stream that wraps
285 another and has none of its own answers with its upstream's.
286  
287 =head2 model
288  
289 Optional. The model name a handler routes the stream to, as the
290 non-streaming L<Langertha::Knarr::Response/model>:
291 L<Langertha::Knarr::Handler::Router> sets the model of the config entry.
292 Settable; a stream that wraps another and has none of its own answers with
293 its upstream's.
294  
295 =head2 upstream_model
296  
297 The model the backend reported on its stream chunks, or C<undef> when it
298 reported none. Known once the stream is exhausted; the tracing decorator
299 records it as the generation's model. Settable; a stream that wraps another
300 and has none of its own answers with its upstream's.
301  
302 =head2 upstream
303  
304 Optional. The stream this one wraps, as the tracing and request-log
305 decorators do. Only consulted by L</finish_reason>, L</tool_calls>,
306 L</usage>, L</model> and L</upstream_model>.
307  
308 =head2 next_chunk_f
309  
310 Returns a L<Future> resolving to the next chunk string, or C<undef>
311 when the stream is exhausted.
312  
313 =head2 from_list
314  
315 my $stream = Langertha::Knarr::Stream->from_list(@chunks);
316  
317 Convenience constructor that builds a stream from a fixed list of
318 chunk strings.
319  
320 =head2 from_callback
321  
322 my $stream = Langertha::Knarr::Stream->from_callback( sub {
323 my ($emit, $done, $fail, $finish, $tool_call, $usage, $model) = @_;
324 my $f = $engine->simple_chat_stream_realtime_f(
325 sub {
326 $emit->( $_[0]->content );
327 $finish->( $_[0]->finish_reason ) if $_[0]->has_finish_reason;
328 $tool_call->( @{ $_[0]->tool_calls } ) if $_[0]->has_tool_calls;
329 $usage->( $_[0]->usage ) if $_[0]->has_usage;
330 $model->( $_[0]->model ) if $_[0]->has_model;
331 },
332 @messages,
333 );
334 $f->on_done( $done );
335 $f->on_fail( $fail );
336 $f->retain;
337 });
338  
339 Builds a stream backed by a callback-driven producer. The setup sub
340 receives seven callbacks — C<$emit-E<gt>($chunk)>, C<$done-E<gt>()>,
341 C<$fail-E<gt>($err)>, C<$finish-E<gt>($finish_reason)>,
342 C<$tool_call-E<gt>(@tool_calls)>, C<$usage-E<gt>($usage)>,
343 C<$model-E<gt>($model)> — and is expected to wire them to the underlying
344 async source. C<$finish> sets L</finish_reason>; an C<undef> reason is
345 ignored, a later one wins. C<$tool_call> appends complete
346 L<Langertha::ToolCall> objects to L</tool_calls>. C<$usage> sets L</usage>;
347 streamed usage is cumulative, so a later report wins, and an C<undef> or
348 empty one is ignored. C<$model> sets L</upstream_model>; an C<undef> or
349 empty name is ignored, a later one wins. Internally maintains a queue and
350 pending Future so the consumer side can sit on C<next_chunk_f> without
351 polling.
352  
353 This is the canonical replacement for the queue/pending/finished/error
354 pump that engine-backed handlers used to inline.
355  
356 =head1 SUPPORT
357  
358 =head2 Issues
359  
360 Please report bugs and feature requests on GitHub at
361 L<https://github.com/Getty/langertha-knarr/issues>.
362  
363 =head2 IRC
364  
365 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
366  
367 =head1 CONTRIBUTING
368  
369 Contributions are welcome! Please fork the repository and submit a pull request.
370  
371 =head1 AUTHOR
372  
373 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
374  
375 =head1 COPYRIGHT AND LICENSE
376  
377 This software is copyright (c) 2026 by Torsten Raudssus.
378  
379 This is free software; you can redistribute it and/or modify it under
380 the same terms as the Perl 5 programming language system itself.
381  
382 =cut
« blib/lib/Langertha/Knarr/Protocol/AGUI.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/Anthropic.pm »