blib/lib/Langertha/Role/Streaming.pm

filter: Statementstmt 98.3% 58 / 59 Branchbran 76.1% 32 / 42 Conditioncond 33.3% 3 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 100% 7 / 7 Podpod 100% 3 / 3 totaltotal 81.7% 103 / 126 CC 26 SCAR 24.9
CC
26
Cov
85%
process_stream_data
17.7
parse_sse_line
8.8
parse_ndjson_line
3.3
CRAP 12.0
« blib/lib/Langertha/HTTP/BoundedDecode.pm ↑ Summary blib/lib/Langertha/Tool.pm »
1 package Langertha::Role::Streaming;
2 # ABSTRACT: Role for streaming support
3 178 our $VERSION = '0.503';
4 178 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 178 requires qw(
7 json
8 parse_stream_chunk
9 stream_format
10 );
11  
12 178 ▶use Langertha::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 178 ▶use Langertha::Stream::Chunk;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 # Per-stream parse state for the dialect parsers that assemble a tool call
16 # from fragments spread over several events (Chat-Completions delta.tool_calls,
17 # Anthropic input_json_delta -- karr k221). Both stream paths hand
18 # parse_stream_chunk a fresh HashRef per stream as its third argument
19 # (process_stream_data below, Role::Chat::chat_stream_realtime_f), so two
20 # streams on one engine never share fragments. This engine-wide HashRef is only
21 # the fallback for a caller that invokes parse_stream_chunk (or
22 # _process_stream_buffer) directly without one.
23 has _stream_parse_state => (
24 is => 'ro',
25 isa => 'HashRef',
26 init_arg => undef,
27 3870 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
28 178 );
29  
30  
31 369 ▶sub parse_sse_line {
Subroutine parse_sse_line: called CC=8 SCAR=21.7
Pod documented
32 369 my ($self, $line) = @_;
33  
34 369 ▶ return undef if !defined $line || $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $line or $line eq "" 0 369 369
Condition33%1/3
not defined $line or $line eq ""
l!l&&r!l&&!r
00369
MC/DC0%0/2
not defined $line or $line eq ""
not defined $line $line eq ""
Truth table33%1/3
not(A) or B
A= not defined $lineB= $line eq ""
ABresult
1X1
011
000
35 369 ▶ return undef if $line =~ /^:\s*/; # SSE comment
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^:\s*/ 2 367 369
36  
37 367 ▶ if ($line =~ /^data:\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^data:\s*(.*)$/) 232 135 367
38 232 my $data = $1;
39 232 ▶ return { type => 'done' } if $data eq '[DONE]';
Branch: 1 branch
BranchTrueFalseTotal
if $data eq "[DONE]" 15 217 232
40 217 ▶ return undef if $data eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $data eq "" 0 217 217
41 217 return { type => 'data', data => $self->json->decode($data) };
42 }
43  
44 135 ▶ if ($line =~ /^event:\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^event:\s*(.*)$/) 135 0 135
45 135 return { type => 'event', event => $1 };
46 }
47  
48 0 return undef;
49 }
50  
51  
52 12 ▶sub parse_ndjson_line {
Subroutine parse_ndjson_line: called CC=3 SCAR=12.0
Pod documented
53 12 my ($self, $line) = @_;
54  
55 12 ▶ return undef if !defined $line || $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $line or $line eq "" 0 12 12
Condition33%1/3
not defined $line or $line eq ""
l!l&&r!l&&!r
0012
MC/DC0%0/2
not defined $line or $line eq ""
not defined $line $line eq ""
Truth table33%1/3
not(A) or B
A= not defined $lineB= $line eq ""
ABresult
1X1
011
000
56  
57 12 my $data = $self->json->decode($line);
58 12 return { type => 'data', data => $data };
59 }
60  
61  
62 49 ▶sub process_stream_data {
Subroutine process_stream_data: called CC=17 SCAR=28.7
Pod documented
63 49 my ($self, $data, $chunk_callback) = @_;
64  
65 49 my @chunks;
66 49 my $format = $self->stream_format;
67 49 my $buffer = '';
68 49 my $current_event = undef;
69 49 my %state; # this stream's parse state, see _stream_parse_state
70  
71 49 my @lines = split /\r?\n/, $data;
72  
73 49 for my $line (@lines) {
74 567 ▶ if ($format eq 'sse') {
Branch: 2 branches
BranchTrueFalseTotal
if ($format eq 'sse') { } 555 12 567
elsif ($format eq 'ndjson') { } 12 0 12
75 555 ▶ if ($line eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($line eq "") 186 369 555
76 # Empty line marks end of SSE event
77 186 next;
78 }
79  
80 369 my $parsed = $self->parse_sse_line($line);
81 369 ▶ next unless $parsed;
Branch: 1 branch
BranchTrueFalseTotal
unless $parsed 2 367 369
82  
83 367 ▶ if ($parsed->{type} eq 'event') {
Branch: 3 branches
BranchTrueFalseTotal
if ($parsed->{'type'} eq 'event') { } 135 232 367
elsif ($parsed->{'type'} eq 'done') { } 15 217 232
elsif ($parsed->{'type'} eq 'data') { } 217 0 217
84 135 $current_event = $parsed->{event};
85 } elsif ($parsed->{type} eq 'done') {
86 # Stream complete
87 15 last;
88 } elsif ($parsed->{type} eq 'data') {
89 217 my $chunk = $self->parse_stream_chunk($parsed->{data}, $current_event, \%state);
90 216 ▶ if ($chunk) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunk) 134 82 216
91 134 push @chunks, $chunk;
92 134 ▶ $chunk_callback->($chunk) if $chunk_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_callback 6 128 134
93 }
94 216 $current_event = undef;
95 }
96 } elsif ($format eq 'ndjson') {
97 12 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 12 12
98  
99 12 my $parsed = $self->parse_ndjson_line($line);
100 12 ▶ next unless $parsed && $parsed->{type} eq 'data';
Branch: 1 branch
BranchTrueFalseTotal
unless $parsed and $parsed->{"type"} eq "data" 0 12 12
Condition33%1/3
$parsed and $parsed->{"type"} eq "data"
!ll&&!rl&&r
0012
MC/DC0%0/2
$parsed and $parsed->{"type"} eq "data"
$parsed $parsed->{"type"} eq "data"
Truth table33%1/3
A and B
A= $parsedB= $parsed->{"type"} eq "data"
ABresult
0X0
100
111
101  
102 12 my $chunk = $self->parse_stream_chunk($parsed->{data}, undef, \%state);
103 12 ▶ if ($chunk) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunk) 12 0 12
104 12 push @chunks, $chunk;
105 12 ▶ $chunk_callback->($chunk) if $chunk_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_callback 0 12 12
106 }
107 }
108 }
109  
110 # The body is complete: let the dialect report what it could not finish.
111 48 ▶ $self->_finish_stream_state(\%state) if $self->can('_finish_stream_state');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_finish_stream_state") 25 23 48
112  
113 48 return \@chunks;
114 }
115  
116  
117  
118 178 1;
119  
120 __END__
121  
122 =pod
123  
124 =encoding UTF-8
125  
126 =head1 NAME
127  
128 Langertha::Role::Streaming - Role for streaming support
129  
130 =head1 VERSION
131  
132 version 0.503
133  
134 =head1 SYNOPSIS
135  
136 # Synchronous streaming via Role::HTTP
137 my $chunks = $engine->execute_streaming_request($request, sub {
138 my ($chunk) = @_;
139 print $chunk->content;
140 });
141  
142 # Streaming with iterator
143 my $stream = $engine->simple_chat_stream_iterator('Tell me a story');
144 while (my $chunk = $stream->next) {
145 print $chunk->content;
146 }
147  
148 =head1 DESCRIPTION
149  
150 Provides stream parsing for server-sent events (SSE) and newline-delimited JSON
151 (NDJSON) streaming responses from LLM APIs. Engines composing this role must
152 implement C<parse_stream_chunk> and C<stream_format>. Works together with
153 L<Langertha::Role::HTTP> for synchronous streaming and L<Langertha::Role::Chat>
154 for the higher-level streaming API.
155  
156 =head2 parse_sse_line
157  
158 my $parsed = $engine->parse_sse_line($line);
159  
160 Parses a single Server-Sent Events line. Returns C<undef> for empty lines and
161 SSE comments. Returns a HashRef with C<type> set to C<'done'>, C<'data'>, or
162 C<'event'>. Data lines have their JSON decoded under the C<data> key.
163  
164 =head2 parse_ndjson_line
165  
166 my $parsed = $engine->parse_ndjson_line($line);
167  
168 Parses a single newline-delimited JSON line. Returns C<undef> for empty lines.
169 Returns a HashRef with C<type =E<gt> 'data'> and the decoded C<data>.
170  
171 =head2 process_stream_data
172  
173 my $chunks = $engine->process_stream_data($raw_body, $chunk_callback);
174 my $chunks = $engine->process_stream_data($raw_body);
175  
176 Parses a complete streaming response body according to the engine's
177 C<stream_format> (C<'sse'> or C<'ndjson'>). Calls
178 C<parse_stream_chunk($data, $event, \%state)> on each data event, with one
179 fresh C<%state> for the whole body, in which a parser assembles tool-call
180 fragments and optionally calls C<$chunk_callback> with each resulting
181 L<Langertha::Stream::Chunk>. Returns an ArrayRef of all chunks.
182  
183 =head1 SEE ALSO
184  
185 =over
186  
187 =item * L<Langertha::Role::Chat> - Chat streaming methods (uses this role)
188  
189 =item * L<Langertha::Role::HTTP> - HTTP execution of streaming requests
190  
191 =item * L<Langertha::Stream> - Stream iterator object
192  
193 =item * L<Langertha::Stream::Chunk> - Individual stream chunk
194  
195 =back
196  
197 =head1 SUPPORT
198  
199 =head2 Issues
200  
201 Please report bugs and feature requests on GitHub at
202 L<https://github.com/Getty/langertha/issues>.
203  
204 =head2 IRC
205  
206 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
207  
208 =head1 CONTRIBUTING
209  
210 Contributions are welcome! Please fork the repository and submit a pull request.
211  
212 =head1 AUTHOR
213  
214 Torsten Raudssus <getty@cpan.org>
215  
216 =head1 COPYRIGHT AND LICENSE
217  
218 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
219  
220 This is free software; you can redistribute it and/or modify it under
221 the same terms as the Perl 5 programming language system itself.
222  
223 =cut
« blib/lib/Langertha/HTTP/BoundedDecode.pm ↑ Summary blib/lib/Langertha/Tool.pm »