Langertha/Role/Chat.pm

filter: Statementstmt 46.7% 93 / 199 Branchbran 27.3% 23 / 84 Conditioncond 16.1% 10 / 62 MC/DCmcdc 6.4% 2 / 31 Subroutinesub 67.8% 19 / 28 Podpod 100% 12 / 12 totaltotal 38.2% 159 / 416 CC 71 SCAR 46.8
CC
71
Cov
37%
chat_f
304.1
_process_stream_buffer
210.0
simple_chat
42.0
CRAP 107.8
« Langertha/Raider.pm ↑ Summary Langertha/Engine/LMStudio.pm »
1 package Langertha::Role::Chat;
2 # ABSTRACT: Role for APIs with normal chat functionality
3 33 our $VERSION = '0.502';
4 33 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 33 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 33 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 33 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 33 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 33 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 33 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 33 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 33 ▶use Langertha::Role::Capabilities;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 33 requires qw(
15 chat_request
16 chat_response
17 );
18  
19  
20 2 ▶sub content_format { 'openai' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod documented
21  
22  
23 33 with 'Langertha::Role::Capabilities';
24  
25  
26 33 has chat_model => (
27 is => 'ro',
28 isa => 'Maybe[Str]',
29 lazy_build => 1,
30 );
31 sub _build_chat_model {
32 65 ▶ my ( $self ) = @_;
Subroutine _build_chat_model: called CC=3 SCAR=11.4
33 65 ▶ croak "".(ref $self)." can't handle models!" unless $self->does('Langertha::Role::Models');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->does("Langertha::Role::Models") 0 65 65
34 65 ▶ return $self->default_chat_model if $self->can('default_chat_model');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("default_chat_model") 0 65 65
35 65 return $self->model;
36 }
37  
38  
39 sub chat {
40 45 ▶ my ( $self, @messages ) = @_;
Subroutine chat: called CC=1 SCAR=0.0
Pod documented
41 45 return $self->chat_request($self->chat_messages(@messages));
42 }
43  
44  
45 sub chat_messages {
46 64 ▶ my ( $self, @messages ) = @_;
Subroutine chat_messages: called CC=4 SCAR=13.9
Pod documented
47 64 my @out;
48 64 ▶ push @out, { role => 'system', content => $self->system_prompt }
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_system_prompt 12 52 64
49 if $self->has_system_prompt;
50 64 for my $m (@messages) {
51 64 ▶ my $msg = ref $m ? $m : { role => 'user', content => $m };
Branch: 1 branch
BranchTrueFalseTotal
ref $m ? : 5 59 64
52 64 push @out, $self->_normalize_content_blocks($msg);
53 }
54 64 return \@out;
55 }
56  
57 sub _normalize_content_blocks {
58 64 ▶ my ( $self, $msg ) = @_;
Subroutine _normalize_content_blocks: called CC=14 SCAR=26.9
59 64 my $content = $msg->{content};
60 64 ▶ return $msg unless ref $content eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content eq "ARRAY" 60 4 64
61  
62 4 my $needs_convert = 0;
63 4 for my $b (@$content) {
64 7 ▶ if ( blessed($b) && $b->does('Langertha::Content') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($b) and $b->does("Langertha::Content")) 3 4 7
Condition66%2/3
builtin::blessed($b) and $b->does("Langertha::Content")
!ll&&!rl&&r
403
MC/DC50%1/2
builtin::blessed($b) and $b->does("Langertha::Content")
builtin::blessed($b) $b->does("Langertha::Content")
Truth table66%2/3
A and B
A= builtin::blessed($b)B= $b->does("Langertha::Content")
ABresult
0X0
100
111
65 3 $needs_convert = 1;
66 3 last;
67 }
68 }
69 4 ▶ return $msg unless $needs_convert;
Branch: 1 branch
BranchTrueFalseTotal
unless $needs_convert 1 3 4
70  
71 3 my $fmt = $self->content_format;
72 3 my $method = "to_$fmt";
73  
74 my @blocks = map {
75 3 ▶ if ( blessed($_) && $_->does('Langertha::Content') ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($_) and $_->does('Langertha::Content')) { } 3 3 6
elsif (not ref $_) { } 3 0 3
Condition66%2/3
builtin::blessed($_) and $_->does("Langertha::Content")
!ll&&!rl&&r
303
MC/DC50%1/2
builtin::blessed($_) and $_->does("Langertha::Content")
builtin::blessed($_) $_->does("Langertha::Content")
Truth table66%2/3
A and B
A= builtin::blessed($_)B= $_->does("Langertha::Content")
ABresult
0X0
100
111
76 3 $_->$method;
77 }
78 elsif ( !ref $_ ) {
79 3 ▶ $fmt eq 'gemini'
Branch: 1 branch
BranchTrueFalseTotal
$fmt eq 'gemini' ? : 1 2 3
80 ? { text => $_ }
81 : { type => 'text', text => $_ };
82 }
83 else {
84 0 $_;
85 }
86 } @$content;
87  
88 3 ▶ if ( $fmt eq 'gemini' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "gemini") 1 2 3
89 1 ▶ my $role = ( $msg->{role} // 'user' ) eq 'assistant' ? 'model' : ( $msg->{role} // 'user' );
Branch: 1 branch
BranchTrueFalseTotal
($$msg{'role'} // 'user') eq 'assistant' ? : 0 1 1
Condition50%2/4
$$msg{"role"} // "user"
l!l
10
$$msg{"role"} // "user"
l!l
10
MC/DC0%0/1
$$msg{"role"} // "user"
$$msg{"role"}
MC/DC0%0/1
$$msg{"role"} // "user"
$$msg{"role"}
Truth table50%1/2
A
A= $$msg{"role"}
Aresult
11
00
Truth table50%1/2
A
A= $$msg{"role"}
Aresult
11
00
90 1 return { role => $role, parts => \@blocks };
91 }
92 2 return { %$msg, content => \@blocks };
93 }
94  
95  
96 sub simple_chat {
97 0 ▶ my ( $self, @messages ) = @_;
Subroutine simple_chat: not called CC=6 SCAR=37.4
Pod documented
98 0 ▶ $log->debugf("[%s] simple_chat with %d message(s), model=%s",
Condition0%0/2
$self->chat_model // "default"
l!l
00
MC/DC0%0/1
$self->chat_model // "default"
$self->chat_model
Truth table0%0/2
A
A= $self->chat_model
Aresult
11
00
99 ref $self, scalar @messages, $self->chat_model // 'default');
100 0 my $request = $self->chat(@messages);
101 0 my $response = $self->user_agent->request($request);
102 0 my $result = $request->response_call->($response);
103 0 ▶ if ($self->can('has_rate_limit') && $self->has_rate_limit && ref $result && $result->isa('Langertha::Response')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")) 0 0 0
Condition0%0/9
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")
!ll&&!rl&&r
000
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result
!ll&&!rl&&r
000
$self->can("has_rate_limit") and $self->has_rate_limit
!ll&&!rl&&r
000
MC/DC0%0/4
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")
$self->can("has_rate_limit") $self->has_rate_limit ref $result $result->isa("Langertha::Response")
Truth table0%0/5
A and B and C and D
A= $self->can("has_rate_limit")B= $self->has_rate_limitC= ref $resultD= $result->isa("Langertha::Response")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
104 0 $result = $result->clone_with(rate_limit => $self->rate_limit);
105 }
106 0 return $result;
107 }
108  
109  
110 sub chat_stream {
111 8 ▶ my ( $self, @messages ) = @_;
Subroutine chat_stream: called CC=2 SCAR=7.1
Pod documented
112 8 ▶ croak "".(ref $self)." does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_stream_request") 0 8 8
113 unless $self->can('chat_stream_request');
114 8 return $self->chat_stream_request($self->chat_messages(@messages));
115 }
116  
117  
118 sub simple_chat_stream {
119 0 ▶ my ( $self, $callback, @messages ) = @_;
Subroutine simple_chat_stream: not called CC=2 SCAR=17.9
Pod documented
120 0 ▶ croak "simple_chat_stream requires a callback as first argument"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 0 0
121 unless ref $callback eq 'CODE';
122 0 $log->debugf("[%s] simple_chat_stream (%s format)", ref $self, $self->stream_format);
123 0 my $request = $self->chat_stream(@messages);
124 0 my $chunks = $self->execute_streaming_request($request, $callback);
125 0 $log->debugf("[%s] Stream completed: %d chunks", ref $self, scalar @$chunks);
126 0 return join('', map { $_->content } @$chunks);
127 }
128  
129  
130 sub simple_chat_stream_iterator {
131 0 ▶ my ( $self, @messages ) = @_;
Subroutine simple_chat_stream_iterator: not called CC=1 SCAR=6.9
Pod documented
132 0 require Langertha::Stream;
133 0 my $request = $self->chat_stream(@messages);
134 0 my $chunks = $self->execute_streaming_request($request);
135 0 return Langertha::Stream->new(chunks => $chunks);
136 }
137  
138  
139 # Future-based async methods
140  
141 33 has _async_loop => (
142 is => 'ro',
143 lazy_build => 1,
144 );
145  
146 sub _build__async_loop {
147 2 ▶ require IO::Async::Loop;
Subroutine _build__async_loop: called CC=1 SCAR=0.0
148 2 return IO::Async::Loop->new;
149 }
150  
151 33 has _async_http => (
152 is => 'ro',
153 lazy_build => 1,
154 );
155  
156 sub _build__async_http {
157 2 ▶ my ($self) = @_;
Subroutine _build__async_http: called CC=1 SCAR=0.0
158 2 require Net::Async::HTTP;
159 2 my $http = Net::Async::HTTP->new;
160 2 $self->_async_loop->add($http);
161 2 return $http;
162 }
163  
164 1 ▶async sub simple_chat_f {
Subroutine simple_chat_f: called CC=1 SCAR=0.0
Pod documented
165 1 my ( $self, @messages ) = @_;
166 1 $log->debugf("[%s] simple_chat_f with %d message(s)", ref $self, scalar @messages);
167 1 return await $self->chat_f( messages => \@messages );
168 33 }
169  
170 1 ▶async sub chat_f {
Subroutine chat_f: called CC=22 SCAR=57.2
Pod documented
171 1 my ( $self, %opts ) = @_;
172  
173 1 ▶ my $messages = delete $opts{messages} // [];
Condition50%1/2
delete $opts{"messages"} // []
l!l
10
MC/DC0%0/1
delete $opts{"messages"} // []
delete $opts{"messages"}
Truth table50%1/2
A
A= delete $opts{"messages"}
Aresult
11
00
174 1 ▶ my @messages = ref $messages eq 'ARRAY' ? @$messages : ($messages);
Branch: 1 branch
BranchTrueFalseTotal
ref $messages eq 'ARRAY' ? : 1 0 1
175  
176 # Auto-fallback: forced named tool on an engine that cannot do
177 # native named-tool-forcing but supports json_schema response_format.
178 # Rewrite tools+tool_choice into a response_format and remember the
179 # tool name so we can synthesize a tool_calls entry afterwards.
180 1 my $synth_tool_name;
181 1 ▶ if ( exists $opts{tool_choice}
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named") and $self->supports("response_format_json_schema")) 0 1 1
Condition33%3/9
exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named") and $self->supports("response_format_json_schema")
!ll&&!rl&&r
100
exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named")
!ll&&!rl&&r
100
exists $opts{"tool_choice"} and exists $opts{"tools"}
!ll&&!rl&&r
100
MC/DC0%0/4
exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named") and $self->supports("response_format_json_schema")
exists $opts{"tool_choice"} exists $opts{"tools"} not $self->supports("tool_choice_named") $self->supports("response_format_json_schema")
Truth table20%1/5
A and B and not(C) and D
A= exists $opts{"tool_choice"}B= exists $opts{"tools"}C= not $self->supports("tool_choice_named")D= $self->supports("response_format_json_schema")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
182 && exists $opts{tools}
183 && !$self->supports('tool_choice_named')
184 && $self->supports('response_format_json_schema')
185 ) {
186 0 my $tc = Langertha::ToolChoice->from_hash( $opts{tool_choice} );
187 0 ▶ if ( $tc && $tc->type eq 'tool' && defined $tc->name && length $tc->name ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc and $tc->type eq "tool" and defined $tc->name and length $tc->name) 0 0 0
Condition0%0/9
$tc and $tc->type eq "tool" and defined $tc->name and length $tc->name
!ll&&!rl&&r
000
$tc and $tc->type eq "tool" and defined $tc->name
!ll&&!rl&&r
000
$tc and $tc->type eq "tool"
!ll&&!rl&&r
000
MC/DC0%0/4
$tc and $tc->type eq "tool" and defined $tc->name and length $tc->name
$tc $tc->type eq "tool" defined $tc->name length $tc->name
Truth table0%0/5
A and B and C and D
A= $tcB= $tc->type eq "tool"C= defined $tc->nameD= length $tc->name
ABCDresult
0XXX0
10XX0
110X0
11100
11111
188 0 my $name = $tc->name;
189 my ($tool) =
190 0 ▶ grep { defined $_ && $_->name eq $name }
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and $_->name eq $name 0 0 0
191 0 map { Langertha::Tool->from_hash($_) }
192 0 @{ $opts{tools} };
193 0 ▶ if ($tool) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tool) 0 0 0
194 0 delete $opts{tools};
195 0 delete $opts{tool_choice};
196 $opts{response_format} = {
197 type => 'json_schema',
198 json_schema => {
199 0 %{ $tool->to_json_schema },
200 strict => JSON->true,
201 },
202 };
203 0 $synth_tool_name = $name;
204 0 $log->debugf("[%s] forced-tool fallback: tool '%s' rerouted via response_format",
205 ref $self, $name);
206 }
207 }
208 }
209  
210 1 my $request = $self->chat_request( $self->chat_messages(@messages), %opts );
211  
212 1 my $response = await $self->_async_http->do_request( request => $request );
213  
214 0 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
215 0 die "".(ref $self)." request failed: ".$response->status_line;
216 }
217  
218 0 my $result = $request->response_call->($response);
219  
220 0 ▶ if ( $synth_tool_name && blessed($result) && $result->isa('Langertha::Response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($synth_tool_name and builtin::blessed($result) and $result->isa("Langertha::Response")) 0 0 0
Condition0%0/6
$synth_tool_name and builtin::blessed($result) and $result->isa("Langertha::Response")
!ll&&!rl&&r
000
$synth_tool_name and builtin::blessed($result)
!ll&&!rl&&r
000
MC/DC0%0/3
$synth_tool_name and builtin::blessed($result) and $result->isa("Langertha::Response")
$synth_tool_name builtin::blessed($result) $result->isa("Langertha::Response")
Truth table0%0/4
A and B and C
A= $synth_tool_nameB= builtin::blessed($result)C= $result->isa("Langertha::Response")
ABCresult
0XX0
10X0
1100
1111
221 0 my $args = $self->decode_loose_json( $result->content );
222 0 ▶ if ( defined $args ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args) 0 0 0
223 0 $result = $result->clone_with(
224 tool_calls => [{
225 name => $synth_tool_name,
226 arguments => $args,
227 synthetic => 1,
228 }],
229 );
230 }
231 }
232  
233 0 ▶ if ( $self->can('has_rate_limit') && $self->has_rate_limit
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")) 0 0 0
Condition0%0/9
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")
!ll&&!rl&&r
000
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result
!ll&&!rl&&r
000
$self->can("has_rate_limit") and $self->has_rate_limit
!ll&&!rl&&r
000
MC/DC0%0/4
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")
$self->can("has_rate_limit") $self->has_rate_limit ref $result $result->isa("Langertha::Response")
Truth table0%0/5
A and B and C and D
A= $self->can("has_rate_limit")B= $self->has_rate_limitC= ref $resultD= $result->isa("Langertha::Response")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
234 && ref $result && $result->isa('Langertha::Response') ) {
235 0 $result = $result->clone_with( rate_limit => $self->rate_limit );
236 }
237 0 return $result;
238 33 }
239  
240  
241  
242 sub simple_chat_stream_f {
243 0 ▶ my ($self, @messages) = @_;
Subroutine simple_chat_stream_f: not called CC=1 SCAR=6.9
Pod documented
244 0 return $self->simple_chat_stream_realtime_f(undef, @messages);
245 }
246  
247  
248 0 ▶async sub simple_chat_stream_realtime_f {
Subroutine simple_chat_stream_realtime_f: not called CC=6 SCAR=37.4
Pod documented
249 0 my ($self, $chunk_callback, @messages) = @_;
250  
251 0 ▶ croak "".(ref $self)." does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_stream_request") 0 0 0
252 unless $self->can('chat_stream_request');
253  
254 0 my $request = $self->chat_stream_request($self->chat_messages(@messages));
255 0 my @all_chunks;
256 0 my $buffer = '';
257 0 my $format = $self->stream_format;
258 0 my $response_status;
259  
260 await $self->_async_http->do_request(
261 request => $request,
262 on_header => sub {
263 0 ▶ my ($response) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
264 0 $response_status = $response;
265  
266 # Return a callback that handles each body chunk
267 return sub {
268 0 ▶ my ($data) = @_;
Subroutine __ANON__: not called CC=4 SCAR=30.0
269 0 ▶ return unless defined $data; # undef signals end of body
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 0 0
270  
271 0 $buffer .= $data;
272 0 my $chunks = $self->_process_stream_buffer(\$buffer, $format);
273 0 for my $chunk (@$chunks) {
274 0 push @all_chunks, $chunk;
275 0 ▶ $chunk_callback->($chunk) if $chunk_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_callback 0 0 0
276 }
277 0 };
278 },
279 0 );
280  
281 0 ▶ unless ($response_status->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response_status->is_success) 0 0 0
282 0 die "".(ref $self)." streaming request failed: ".$response_status->status_line;
283 }
284  
285 # Process remaining buffer
286 0 ▶ if ($buffer ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffer ne "") 0 0 0
287 0 my $chunks = $self->_process_stream_buffer(\$buffer, $format, 1);
288 0 for my $chunk (@$chunks) {
289 0 push @all_chunks, $chunk;
290 0 ▶ $chunk_callback->($chunk) if $chunk_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_callback 0 0 0
291 }
292 }
293  
294 0 my $content = join('', map { $_->content } @all_chunks);
295 0 return ($content, \@all_chunks);
296 33 }
297  
298 sub aggregate_tool_calls {
299 0 ▶ my ( $self, $chunks ) = @_;
Subroutine aggregate_tool_calls: not called CC=4 SCAR=30.0
Pod documented
300 0 ▶ return [] unless ref($chunks) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $chunks eq "ARRAY" 0 0 0
301 0 my @tcs;
302 0 for my $c (@$chunks) {
303 0 ▶ next unless eval { $c->has_tool_calls };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $c->has_tool_calls } } 0 0 0
304 0 push @tcs, @{ $c->tool_calls };
305 }
306 0 return \@tcs;
307 }
308  
309  
310  
311 sub _process_stream_buffer {
312 0 ▶ my ($self, $buffer_ref, $format, $final) = @_;
Subroutine _process_stream_buffer: not called CC=14 SCAR=53.5
313  
314 0 my @chunks;
315  
316 0 ▶ if ($format eq 'sse') {
Branch: 2 branches
BranchTrueFalseTotal
if ($format eq 'sse') { } 0 0 0
elsif ($format eq 'ndjson') { } 0 0 0
317 0 ▶ while ($$buffer_ref =~ s/^(.*?)\n\n//s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^(.*?)\n\n//s) 0 0 0
318 0 my $block = $1;
319 0 for my $line (split /\n/, $block) {
320 0 ▶ next if $line eq '' || $line =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" or $line =~ /^:/ 0 0 0
Condition0%0/3
$line eq "" or $line =~ /^:/
l!l&&r!l&&!r
000
MC/DC0%0/2
$line eq "" or $line =~ /^:/
$line eq "" $line =~ /^:/
Truth table0%0/3
A or B
A= $line eq ""B= $line =~ /^:/
ABresult
1X1
011
000
321 0 ▶ if ($line =~ /^data:\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^data:\s*(.*)$/) 0 0 0
322 0 my $json_data = $1;
323 0 ▶ next if $json_data eq '[DONE]' || $json_data eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $json_data eq "[DONE]" or $json_data eq "" 0 0 0
Condition0%0/3
$json_data eq "[DONE]" or $json_data eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
$json_data eq "[DONE]" or $json_data eq ""
$json_data eq "[DONE]" $json_data eq ""
Truth table0%0/3
A or B
A= $json_data eq "[DONE]"B= $json_data eq ""
ABresult
1X1
011
000
324 0 my $parsed = $self->json->decode($json_data);
325 0 my $chunk = $self->parse_stream_chunk($parsed);
326 0 ▶ push @chunks, $chunk if $chunk;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk 0 0 0
327 }
328 }
329 }
330 } elsif ($format eq 'ndjson') {
331 0 ▶ while ($$buffer_ref =~ s/^(.*?)\n//s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^(.*?)\n//s) 0 0 0
332 0 my $line = $1;
333 0 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 0 0
334 0 my $parsed = $self->json->decode($line);
335 0 my $chunk = $self->parse_stream_chunk($parsed);
336 0 ▶ push @chunks, $chunk if $chunk;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk 0 0 0
337 }
338 }
339  
340 0 return \@chunks;
341 }
342  
343 33 with 'Langertha::Role::ThinkTag', 'Langertha::Role::Langfuse';
344  
345  
346 33 1;
347  
348 __END__
349  
350 =pod
351  
352 =encoding UTF-8
353  
354 =head1 NAME
355  
356 Langertha::Role::Chat - Role for APIs with normal chat functionality
357  
358 =head1 VERSION
359  
360 version 0.502
361  
362 =head1 SYNOPSIS
363  
364 # Synchronous chat
365 my $response = $engine->simple_chat('Hello, how are you?');
366  
367 # Streaming with callback
368 $engine->simple_chat_stream(sub {
369 my ($chunk) = @_;
370 print $chunk->content;
371 }, 'Tell me a story');
372  
373 # Streaming with iterator
374 my $stream = $engine->simple_chat_stream_iterator('Tell me a story');
375 while (my $chunk = $stream->next) {
376 print $chunk->content;
377 }
378  
379 # Async with Future (traditional style)
380 my $future = $engine->simple_chat_f('Hello');
381 my $response = $future->get;
382  
383 # Async with Future::AsyncAwait (recommended)
384 use Future::AsyncAwait;
385  
386 async sub chat_example {
387 my ($engine) = @_;
388 my $response = await $engine->simple_chat_f('Hello');
389 say $response;
390 }
391  
392 # Async streaming with real-time callback
393 async sub stream_example {
394 my ($engine) = @_;
395 my ($content, $chunks) = await $engine->simple_chat_stream_realtime_f(
396 sub { print shift->content },
397 'Tell me a story'
398 );
399 say "\nTotal chunks: ", scalar @$chunks;
400 }
401  
402 =head1 DESCRIPTION
403  
404 This role provides chat functionality for LLM engines. It includes both
405 synchronous and asynchronous (L<Future>-based) methods for chat and streaming.
406  
407 The Future-based C<_f> methods are implemented using L<Future::AsyncAwait> and
408 L<Net::Async::HTTP>. These modules are loaded lazily only when you call a C<_f>
409 method, so synchronous-only usage does not require them.
410  
411 =head2 chat_model
412  
413 The model name used for chat requests. Lazily defaults to C<default_chat_model>
414 if the engine provides it, otherwise falls back to the general C<model>
415 attribute from L<Langertha::Role::Models>.
416  
417 =head2 chat
418  
419 my $request = $engine->chat(@messages);
420  
421 Builds and returns a chat HTTP request object. Messages may be plain strings
422 (treated as C<user> role) or HashRefs with C<role> and C<content> keys. A
423 system prompt from L<Langertha::Role::SystemPrompt> is prepended automatically.
424  
425 =head2 chat_messages
426  
427 my $messages = $engine->chat_messages(@messages);
428  
429 Normalises C<@messages> into the canonical ArrayRef-of-HashRef format expected
430 by C<chat_request>. Plain strings become C<{ role =E<gt> 'user', content =E<gt>
431 $string }>. If the engine has a C<system_prompt> set it is prepended as a
432 C<system> message.
433  
434 =head2 simple_chat
435  
436 my $response = $engine->simple_chat(@messages);
437 my $response = $engine->simple_chat('Hello, how are you?');
438  
439 Sends a synchronous chat request and returns the response text. Blocks until
440 the request completes.
441  
442 =head2 chat_stream
443  
444 my $request = $engine->chat_stream(@messages);
445  
446 Builds and returns a streaming chat HTTP request object. Croaks if the engine
447 does not implement C<chat_stream_request>. Use L</simple_chat_stream> or
448 L</simple_chat_stream_iterator> to execute the request.
449  
450 =head2 simple_chat_stream
451  
452 my $content = $engine->simple_chat_stream($callback, @messages);
453  
454 $engine->simple_chat_stream(sub {
455 my ($chunk) = @_;
456 print $chunk->content;
457 }, 'Tell me a story');
458  
459 Sends a synchronous streaming chat request. Calls C<$callback> with each
460 L<Langertha::Stream::Chunk> as it arrives. Returns the complete concatenated
461 content string when done. Blocks until the stream completes.
462  
463 =head2 simple_chat_stream_iterator
464  
465 my $stream = $engine->simple_chat_stream_iterator(@messages);
466 while (my $chunk = $stream->next) {
467 print $chunk->content;
468 }
469  
470 Returns a L<Langertha::Stream> iterator. The full response is fetched
471 synchronously and buffered; iteration yields each L<Langertha::Stream::Chunk>
472 in order.
473  
474 =head2 simple_chat_f
475  
476 # Traditional Future style
477 my $response = $engine->simple_chat_f(@messages)->get;
478  
479 # With async/await (recommended)
480 use Future::AsyncAwait;
481 async sub my_chat {
482 my $response = await $engine->simple_chat_f(@messages);
483 return $response;
484 }
485  
486 Async version of L</simple_chat>. Returns a L<Future> that resolves to the
487 response text. Uses L<Net::Async::HTTP> internally; loaded lazily on first call.
488  
489 For requests that need named arguments (tools, tool_choice,
490 response_format, etc.) use L</chat_f>; C<simple_chat_f> delegates to it.
491  
492 =head2 chat_f
493  
494 my $response = await $engine->chat_f(
495 messages => [ ... ],
496 tools => [ $tool, ... ],
497 tool_choice => { type => 'tool', name => 'extract' },
498 response_format => { ... },
499 # any other engine-specific extras pass straight through
500 );
501  
502 Async I<single-turn> chat with named arguments. Returns a L<Future>
503 resolving to a L<Langertha::Response>. The caller is responsible for
504 acting on any C<tool_calls> the engine emits — C<chat_f> does not
505 loop. For the multi-turn MCP tool-calling loop use
506 L<Langertha::Role::Tools/chat_with_tools_f> instead.
507  
508 C<tools> in C<chat_f> can be a mix of provider-shape HashRefs
509 (OpenAI, Anthropic, MCP, Gemini); the engine's C<chat_request> handles
510 the per-provider serialization. The L<Langertha::Tool> value object is
511 the canonical normalizer (C<from_hash> accepts every shape, the
512 C<to_PROVIDER> methods produce the wire payload).
513  
514 When the caller asks for a forced named tool on an engine that cannot
515 do native named-tool-forcing but supports C<json_schema>
516 response_format (currently L<Langertha::Engine::Perplexity>), the
517 request is automatically rewritten to use the JSON Schema path and the
518 response is loose-parsed; the resulting L<Langertha::Response> exposes
519 the parsed arguments via L<Langertha::Response/tool_call_args> with
520 C<synthetic =E<gt> 1> on the synthesized tool_call entry.
521  
522 =head2 simple_chat_stream_f
523  
524 my ($content, $chunks) = $engine->simple_chat_stream_f(@messages)->get;
525  
526 Async streaming without a real-time callback. Convenience wrapper around
527 L</simple_chat_stream_realtime_f> with C<undef> as the callback. Returns a
528 L<Future> that resolves to C<($content, \@chunks)>.
529  
530 =head2 aggregate_tool_calls
531  
532 my $tool_calls = $engine->aggregate_tool_calls( $chunks );
533  
534 Walks an ArrayRef of L<Langertha::Stream::Chunk> objects and returns
535 the flat list of L<Langertha::ToolCall> objects collected from any
536 chunks that carry C<tool_calls>. Returns an empty ArrayRef if none of
537 the chunks emitted tool calls.
538  
539 This is the streaming counterpart to L<Langertha::Response/tool_calls>.
540 Engines that need to assemble fragmented tool-call deltas (OpenAI's
541 C<delta.tool_calls> stream, Anthropic's C<input_json_delta>) are
542 expected to do that assembly inside C<parse_stream_chunk> and attach
543 the finished L<Langertha::ToolCall> to the relevant chunk; this
544 helper just collects them.
545  
546 =head2 simple_chat_stream_realtime_f
547  
548 # With async/await (recommended)
549 use Future::AsyncAwait;
550 async sub my_stream {
551 my ($content, $chunks) = await $engine->simple_chat_stream_realtime_f(
552 sub { print shift->content },
553 @messages
554 );
555 return $content;
556 }
557  
558 # Traditional Future style
559 my $future = $engine->simple_chat_stream_realtime_f($callback, @messages);
560 my ($content, $chunks) = $future->get;
561  
562 Async streaming with real-time callback. C<$callback> is called with each
563 L<Langertha::Stream::Chunk> as it arrives from the server. Returns a L<Future>
564 that resolves to C<($content, \@chunks)> where C<$content> is the full
565 concatenated text.
566  
567 This is the recommended method for real-time streaming in async applications.
568 Pass C<undef> as the callback (or use L</simple_chat_stream_f>) if you only
569 need the final result.
570  
571 =head2 content_format
572  
573 my $fmt = $engine->content_format; # 'openai' | 'anthropic' | 'gemini'
574  
575 Wire format for multimodal content blocks. Controls how
576 L<Langertha::Content> objects embedded in a message's C<content> arrayref
577 are serialized during L</chat_messages>. Defaults to C<'openai'>; overridden
578 by L<Langertha::Engine::AnthropicBase> and L<Langertha::Engine::Gemini>.
579  
580 =head2 engine_capabilities
581  
582 my $caps = $engine->engine_capabilities;
583 if ( $caps->{tool_choice_named} ) { ... }
584  
585 Returns a HashRef of capability flags so callers can avoid passing
586 parameters the engine cannot honour.
587  
588 The base implementation reports only what L<Langertha::Role::Chat>
589 itself provides (C<chat>). Every other capability-bearing role
590 (L<Langertha::Role::Tools>, L<Langertha::Role::ResponseFormat>,
591 L<Langertha::Role::Streaming>, L<Langertha::Role::Embedding>,
592 L<Langertha::Role::Transcription>, L<Langertha::Role::ImageGeneration>,
593 L<Langertha::Role::HermesTools>, L<Langertha::Role::Temperature>,
594 L<Langertha::Role::Seed>, L<Langertha::Role::ContextSize>,
595 L<Langertha::Role::ResponseSize>, L<Langertha::Role::SystemPrompt>,
596 L<Langertha::Role::ParallelToolUse>) hangs its own contribution into
597 this method via C<around engine_capabilities>. Engines override (also
598 via C<around>) when the wire reality differs from the role inventory
599 — for example to clear C<tool_choice_named> on providers that only
600 accept string forms.
601  
602 Common keys produced by the bundled roles:
603  
604 =over
605  
606 =item * C<chat> — C<simple_chat>/C<simple_chat_f> work
607  
608 =item * C<streaming> — C<chat_stream_request> is wired up
609  
610 =item * C<tools_native> — engine accepts a C<tools> array on the wire
611  
612 =item * C<tools_hermes> — tools are injected via Hermes-style XML
613 prompt rather than (or in addition to) the native API
614  
615 =item * C<tool_choice_auto> / C<tool_choice_any> / C<tool_choice_none> —
616 which string-form C<tool_choice> values are accepted
617  
618 =item * C<tool_choice_named> — C<{type =E<gt> 'tool', name =E<gt> '...'}>
619 forcing works (possibly translated internally — Gemini routes named
620 tools through C<allowed_function_names>, for example)
621  
622 =item * C<response_format_json_object> — C<{type =E<gt> 'json_object'}>
623  
624 =item * C<response_format_json_schema> — JSON Schema structured output
625  
626 =item * C<embedding>, C<transcription>, C<image_generation> — auxiliary
627 capabilities matching the corresponding roles
628  
629 =item * C<temperature>, C<seed>, C<context_size>, C<response_size>,
630 C<system_prompt>, C<parallel_tool_use> — generation-parameter knobs
631 the engine will honour
632  
633 =back
634  
635 Callers should treat the hash as advisory — a missing key means
636 "unknown / unsupported", a true value means "the engine claims it
637 will honour this".
638  
639 =head1 SEE ALSO
640  
641 =over
642  
643 =item * L<Langertha::Role::Langfuse> - Observability integration (composed by this role)
644  
645 =item * L<Langertha::Role::SystemPrompt> - System prompt injection
646  
647 =item * L<Langertha::Role::Streaming> - Stream parsing (SSE / NDJSON)
648  
649 =item * L<Langertha::Role::Tools> - Tool calling on top of chat
650  
651 =item * L<Langertha::Role::Models> - Model selection
652  
653 =item * L<Langertha::Stream> - Stream iterator
654  
655 =item * L<Langertha::Stream::Chunk> - Individual stream chunk
656  
657 =back
658  
659 =head1 SUPPORT
660  
661 =head2 Issues
662  
663 Please report bugs and feature requests on GitHub at
664 L<https://github.com/Getty/langertha/issues>.
665  
666 =head2 IRC
667  
668 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
669  
670 =head1 CONTRIBUTING
671  
672 Contributions are welcome! Please fork the repository and submit a pull request.
673  
674 =head1 AUTHOR
675  
676 Torsten Raudssus <getty@cpan.org>
677  
678 =head1 COPYRIGHT AND LICENSE
679  
680 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
681  
682 This is free software; you can redistribute it and/or modify it under
683 the same terms as the Perl 5 programming language system itself.
684  
685 =cut
« Langertha/Raider.pm ↑ Summary Langertha/Engine/LMStudio.pm »