blib/lib/Langertha/Chat.pm

filter: Statementstmt 96.1% 202 / 210 Branchbran 87.5% 49 / 56 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 92.3% 24 / 26 Podpod 100% 5 / 5 totaltotal 94.2% 280 / 297 CC 36 SCAR 14.2
CC
36
Cov
94%
simple_chat_with_tools_f
9.0
simple_chat_with_tools
8.0
_build_messages
5.0
CRAP 4.1
« blib/lib/Langertha/Role/ContextSize.pm ↑ Summary blib/lib/Langertha/Role/HermesTools.pm »
1 package Langertha::Chat;
2 # ABSTRACT: Chat abstraction wrapping an engine with optional overrides
3 23 our $VERSION = '0.505';
4 23 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 23 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 23 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 23 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 23 ▶use Langertha::Role::Tools ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 23 with 'Langertha::Role::PluginHost';
12  
13  
14 23 has engine => (
15 is => 'ro',
16 required => 1,
17 );
18  
19 23 has system_prompt => (
20 is => 'ro',
21 isa => 'Str',
22 predicate => 'has_system_prompt',
23 );
24  
25 23 has model => (
26 is => 'ro',
27 isa => 'Str',
28 predicate => 'has_model',
29 );
30  
31 23 has temperature => (
32 is => 'ro',
33 isa => 'Num',
34 predicate => 'has_temperature',
35 );
36  
37 has mcp_servers => (
38 is => 'ro',
39 isa => 'ArrayRef',
40 106 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
41 23 );
42  
43 23 has tool_max_iterations => (
44 is => 'ro',
45 isa => 'Int',
46 default => 10,
47 );
48  
49  
50 209 ▶sub _extra {
Subroutine _extra: called CC=3 SCAR=11.0
51 209 my ( $self ) = @_;
52 return (
53 209 ▶ ($self->has_model ? (model => $self->model) : ()),
Branch: 2 branches
BranchTrueFalseTotal
$self->has_model ? : 22 187 209
$self->has_temperature ? : 6 203 209
54 ($self->has_temperature ? (temperature => $self->temperature) : ()),
55 );
56 }
57  
58 # The wrapper's model rides %extra into the engine's request builder past
59 # chat_f, so the engine's per-request model warning (Role::Chat, karr k352) is
60 # raised here, once per call, with the request features the call uses: the
61 # wrapper's temperature, the gathered tools, streaming (karr k360).
62 153 ▶sub _warn_model_override {
Subroutine _warn_model_override: called CC=3 SCAR=11.0
63 153 my ( $self, $method, $streaming, %request ) = @_;
64 153 ▶ return unless $self->has_model;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_model 141 12 153
65 12 my $engine = $self->engine;
66 12 ▶ return unless $engine->can('_warn_model_override');
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->can("_warn_model_override") 2 10 12
67 10 $engine->_warn_model_override( "Langertha::Chat->$method", { $self->_extra, %request }, $streaming );
68 10 return;
69 }
70  
71 # Each message goes through the engine's own per-message step of chat_messages,
72 # so Langertha::Content objects become the engine's content_format blocks
73 # (karr k275). The leading system messages are the engine's own
74 # _system_messages: the engine's system_prompt unless the wrapper has one, plus
75 # engine prefixes such as NousResearch's reasoning prompt either way (k277).
76 153 ▶sub _build_messages {
Subroutine _build_messages: called CC=5 SCAR=16.1
77 153 my ( $self, @messages ) = @_;
78 153 my $engine = $self->engine;
79 153 my $normalize = $engine->can('_normalize_content_blocks');
80 153 ▶ my @override = $self->has_system_prompt ? ( $self->system_prompt ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->has_system_prompt ? : 22 131 153
81 return [
82 ( $engine->can('_system_messages')
83 ? $engine->_system_messages(@override)
84 5 : map { +{ role => 'system', content => $_ } } @override ),
85 map {
86 153 ▶ my $msg = ref $_ ? $_ : { role => 'user', content => $_ };
Branch: 2 branches
BranchTrueFalseTotal
$engine->can('_system_messages') ? : 130 23 153
ref $_ ? : 17 138 155
87 155 ▶ $normalize ? $engine->$normalize($msg) : $msg;
Branch: 1 branch
BranchTrueFalseTotal
$normalize ? : 130 25 155
88 } @messages
89 ];
90 }
91  
92 # The _f paths fetch the URL images the engine inlines through its async
93 # backend before the build, like the engine's own _f paths (karr k274, k275).
94 73 ▶async sub _build_messages_f {
Subroutine _build_messages_f: called CC=2 SCAR=7.0
95 73 my ( $self, @messages ) = @_;
96 73 my $engine = $self->engine;
97 73 ▶ @messages = await $engine->_prefetch_inline_images_f(@messages)
Branch: 1 branch
BranchTrueFalseTotal
if $engine->can("_prefetch_inline_images_f") 73 0 73
98 if $engine->can('_prefetch_inline_images_f');
99 73 return $self->_build_messages(@messages);
100 23 }
101  
102 155 ▶sub _assert_chat_engine {
Subroutine _assert_chat_engine: called CC=2 SCAR=6.9
103 155 my ( $self ) = @_;
104 155 my $engine = $self->engine;
105 155 ▶ croak ref($engine) . " does not support chat"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->does("Langertha::Role::Chat") 1 154 155
106 unless $engine->does('Langertha::Role::Chat');
107 154 return $engine;
108 }
109  
110 # --- Plugin hook runners (async) ---
111  
112 199 ▶async sub _run_plugin_before_llm_call {
Subroutine _run_plugin_before_llm_call: called CC=2 SCAR=6.9
113 199 my ( $self, $conversation, $iteration ) = @_;
114 199 for my $plugin (@{$self->_plugin_instances}) {
115 74 $conversation = await $plugin->plugin_before_llm_call($conversation, $iteration);
116 }
117 199 return $conversation;
118 23 }
119  
120 193 ▶async sub _run_plugin_after_llm_response {
Subroutine _run_plugin_after_llm_response: called CC=2 SCAR=6.9
121 193 my ( $self, $data, $iteration ) = @_;
122 193 for my $plugin (@{$self->_plugin_instances}) {
123 74 $data = await $plugin->plugin_after_llm_response($data, $iteration);
124 }
125 193 return $data;
126 23 }
127  
128 52 ▶async sub _run_plugin_after_tool_call {
Subroutine _run_plugin_after_tool_call: called CC=2 SCAR=6.9
129 52 my ( $self, $name, $input, $result ) = @_;
130 52 for my $plugin (@{$self->_plugin_instances}) {
131 23 $result = await $plugin->plugin_after_tool_call($name, $input, $result);
132 }
133 52 return $result;
134 23 }
135  
136 # --- Simple chat (no tools) ---
137  
138 27 ▶sub simple_chat {
Subroutine simple_chat: called CC=1 SCAR=0.0
Pod documented
139 27 my ( $self, @messages ) = @_;
140 27 $log->debugf("[Chat] simple_chat via %s", ref $self->engine);
141 27 my $engine = $self->_assert_chat_engine;
142 26 $self->_warn_model_override( 'simple_chat', 0 );
143 26 my $conversation = $self->_build_messages(@messages);
144  
145 26 $conversation = $self->_run_plugin_before_llm_call($conversation, 1)->get;
146  
147 26 my $request = $engine->chat_request($conversation, $self->_extra);
148 26 my $response = $engine->user_agent->request($request);
149 26 my $data = $request->response_call->($response);
150  
151 26 $data = $self->_run_plugin_after_llm_response($data, 1)->get;
152  
153 26 return $data;
154 }
155  
156  
157 # A failed response still updates the engine's rate limit before the die, so
158 # a caller can back off from a 429 (karr k300); returns the engine's error
159 # text, the same as its sync croak (karr k312).
160 4 ▶sub _failed_message {
Subroutine _failed_message: called CC=3 SCAR=11.7
161 4 my ( $self, $engine, $response, $what ) = @_;
162 4 ▶ $engine->_update_rate_limit($response) if $engine->can('_update_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
if $engine->can("_update_rate_limit") 4 0 4
163 4 ▶ return $engine->can('_request_failed_message')
Branch: 1 branch
BranchTrueFalseTotal
$engine->can('_request_failed_message') ? : 4 0 4
164 ? $engine->_request_failed_message( $response, $what )
165 : "" . (ref $engine) . " $what failed: " . $response->status_line;
166 }
167  
168 31 ▶async sub simple_chat_f {
Subroutine simple_chat_f: called CC=2 SCAR=6.9
Pod documented
169 31 my ( $self, @messages ) = @_;
170 31 my $engine = $self->_assert_chat_engine;
171 31 $self->_warn_model_override( 'simple_chat_f', 0 );
172 31 my $conversation = await $self->_build_messages_f(@messages);
173  
174 31 $conversation = await $self->_run_plugin_before_llm_call($conversation, 1);
175  
176 31 my $request = $engine->chat_request($conversation, $self->_extra);
177 31 my $response = await $engine->_async_do_request_f(
178 request => $request,
179 );
180 30 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 2 28 30
181 2 die $self->_failed_message( $engine, $response, 'request' );
182 }
183 28 my $data = $request->response_call->($response);
184  
185 28 $data = await $self->_run_plugin_after_llm_response($data, 1);
186  
187 28 return $data;
188 23 }
189  
190  
191 1 ▶sub simple_chat_stream {
Subroutine simple_chat_stream: called CC=3 SCAR=12.0
Pod documented
192 1 my ( $self, $callback, @messages ) = @_;
193 1 my $engine = $self->_assert_chat_engine;
194 1 ▶ croak ref($engine) . " does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->can("chat_stream_request") 0 1 1
195 unless $engine->can('chat_stream_request');
196 1 ▶ croak "simple_chat_stream requires a callback as first argument"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 1 1
197 unless ref $callback eq 'CODE';
198 1 $self->_warn_model_override( 'simple_chat_stream', 1 );
199 1 my $conversation = $self->_build_messages(@messages);
200  
201 1 $conversation = $self->_run_plugin_before_llm_call($conversation, 1)->get;
202  
203 1 my $request = $engine->chat_stream_request($conversation, $self->_extra);
204 0 my $chunks = $engine->execute_streaming_request($request, $callback);
205 0 return join('', map { $_->content } @$chunks);
206 }
207  
208  
209 # --- Chat with tools ---
210  
211 96 ▶sub _gather_tools {
Subroutine _gather_tools: called CC=2 SCAR=6.9
212 96 my ( $self ) = @_;
213 96 my @mcp_servers = @{$self->mcp_servers};
214 96 ▶ croak "No MCP servers configured" unless @mcp_servers;
Branch: 1 branch
BranchTrueFalseTotal
unless @mcp_servers 1 95 96
215  
216 # A name two servers offer goes on the wire once, from the first (k332).
217 return $self->engine->_tool_loop_tools(
218 95 map { [ $_, $_->list_tools->get ] } @mcp_servers );
219 }
220  
221 82 ▶sub _tool_loop_iteration {
Subroutine _tool_loop_iteration: called CC=2 SCAR=6.9
222 82 my ( $self, $engine, $conversation, $formatted_tools, $iteration ) = @_;
223  
224 # Plugin hook: before LLM call
225 82 $conversation = $self->_run_plugin_before_llm_call($conversation, $iteration)->get;
226  
227 # Build and send the request
228 82 my $request = $engine->build_tool_chat_request($conversation, $formatted_tools, $self->_extra);
229  
230 82 my $response = $engine->user_agent->request($request);
231 # The same failure text and rate-limit update as the async loop (karr k312).
232 82 ▶ die $self->_failed_message( $engine, $response, 'tool chat request' )
Branch: 1 branch
BranchTrueFalseTotal
unless $response->is_success 1 81 82
233 unless $response->is_success;
234  
235 81 my $reply = $self->_tool_loop_reply_f( $engine, $response, $iteration )->get;
236  
237 72 return ($conversation, $reply->raw, $reply);
238 }
239  
240 # One tool-loop turn's reply. plugin_after_llm_response gets the RAW decoded
241 # wire body -- the provider's own block list, never the flattened Response
242 # (karr #81) -- and the body the hooks return is read by the parser chat_f
243 # uses (karr k321, k322): an error-in-body 200 croaks as it does there, the
244 # final text is chat_f's, the calls to run are Response.tool_calls (ADR 0003).
245 # The assistant echo is built from ->raw of that same reply, so a hook that
246 # drops a call, changes its arguments or rewrites the text is honoured by all
247 # three, and every echoed call gets exactly one result -- karr k347.
248 139 ▶async sub _tool_loop_reply_f {
Subroutine _tool_loop_reply_f: called CC=1 SCAR=0.0
249 139 my ( $self, $engine, $response, $iteration ) = @_;
250 139 my $data = $engine->parse_response($response);
251 139 $data = await $self->_run_plugin_after_llm_response($data, $iteration);
252 139 return $engine->tool_loop_response($data);
253 23 }
254  
255 53 ▶sub simple_chat_with_tools {
Subroutine simple_chat_with_tools: called CC=8 SCAR=20.8
Pod documented
256 53 my ( $self, @messages ) = @_;
257 53 my $engine = $self->_assert_chat_engine;
258 53 ▶ croak ref($engine) . " does not support tools"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->does("Langertha::Role::Tools") 0 53 53
259 unless $engine->does('Langertha::Role::Tools');
260  
261 53 my ($all_tools, $tool_server_map) = $self->_gather_tools;
262 53 $log->debugf("[Chat] simple_chat_with_tools via %s, %d tools, max_iterations=%d",
263 ref $engine, scalar @$all_tools, $self->tool_max_iterations);
264 53 my $formatted_tools = $engine->format_tools($all_tools);
265 53 $self->_warn_model_override( 'simple_chat_with_tools', 0, tools => $formatted_tools );
266 53 my $conversation = $self->_build_messages(@messages);
267  
268 53 for my $iteration (1..$self->tool_max_iterations) {
269 82 ($conversation, my $data, my $reply) =$self->_tool_loop_iteration(
270 $engine, $conversation, $formatted_tools, $iteration,
271 );
272  
273 # Calls cut off by the token limit are dropped, as in chat_with_tools_f (k324).
274 72 ( my $calls, $data ) = $engine->tool_loop_calls( $reply, $reply->raw );
275 67 my @tool_calls = @$calls;
276 67 ▶ return $reply->content unless @tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless @tool_calls 38 29 67
277  
278 # Execute each tool call
279 29 my @results;
280 29 for my $tc (@tool_calls) {
281 40 my ( $name, $input ) = ( $tc->name, $tc->arguments );
282  
283 # Arguments that do not decode are answered with an error result
284 # before any plugin sees the call (k345).
285 40 ▶ if ( my $bad = Langertha::Role::Tools::_undecodable_arguments_result($tc) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bad = Langertha::Role::Tools::_undecodable_arguments_result($tc)) 3 37 40
286 3 push @results, { tool_call => $tc, result => $bad };
287 3 next;
288 }
289  
290 37 $log->debugf("[Chat] Calling tool: %s", $name);
291  
292 # Plugin hook: before tool call (can skip)
293 37 my @plugin_tc = $self->_plugin_pipeline_tool_call($name, $input)->get;
294 37 ▶ unless (@plugin_tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@plugin_tc) 2 35 37
295 2 push @results, { tool_call => $tc, result => {
296 content => [{ type => 'text', text => "Tool call '$name' was skipped by plugin." }],
297 }};
298 2 next;
299 }
300 35 ( $name, $input ) = @plugin_tc;
301  
302 # The plugins see every call and may rename one onto a real tool; a
303 # name no server offers after them is answered with an error result,
304 # so the batch runs to the end and the model can correct itself
305 # (k332, k348).
306 35 my $mcp = $tool_server_map->{$name};
307 35 ▶ unless ($mcp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($mcp) 3 32 35
308 3 push @results, { tool_call => $tc,
309 result => Langertha::Role::Tools::_unknown_tool_result($name) };
310 3 next;
311 }
312  
313 0 ▶ my $result = $mcp->call_tool($name, $input)->else(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
314 0 my ( $error ) = @_;
315 0 Future->done({
316 content => [{ type => 'text', text => "Error calling tool '$name': $error" }],
317 isError => JSON->true,
318 });
319 32 })->get;
320  
321 # Plugin hook: after tool call
322 32 $result = $self->_run_plugin_after_tool_call($name, $input, $result)->get;
323  
324 32 push @results, { tool_call => $tc, result => $result };
325 }
326  
327 29 push @$conversation, $engine->format_tool_results($data, \@results);
328 }
329  
330 0 die "Tool calling loop exceeded " . $self->tool_max_iterations . " iterations";
331 }
332  
333  
334 43 ▶async sub simple_chat_with_tools_f {
Subroutine simple_chat_with_tools_f: called CC=9 SCAR=22.0
Pod documented
335 43 my ( $self, @messages ) = @_;
336 43 my $engine = $self->_assert_chat_engine;
337 43 ▶ croak ref($engine) . " does not support tools"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->does("Langertha::Role::Tools") 0 43 43
338 unless $engine->does('Langertha::Role::Tools');
339  
340 43 my ($all_tools, $tool_server_map) = $self->_gather_tools;
341 42 my $formatted_tools = $engine->format_tools($all_tools);
342 42 $self->_warn_model_override( 'simple_chat_with_tools_f', 0, tools => $formatted_tools );
343 42 my $conversation = await $self->_build_messages_f(@messages);
344  
345 42 for my $iteration (1..$self->tool_max_iterations) {
346 59 $conversation = await $self->_run_plugin_before_llm_call($conversation, $iteration);
347  
348 59 my $request = $engine->build_tool_chat_request($conversation, $formatted_tools, $self->_extra);
349  
350 59 my $response = await $engine->_async_do_request_f(request => $request);
351 59 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 1 58 59
352 1 die $self->_failed_message( $engine, $response, 'tool chat request' );
353 }
354  
355 # As the sync loop: the raw body to the hook, chat_f's parser on what it
356 # returns, calls, text and echo from that one reply (k321, k322, k347).
357 58 my $reply = await $self->_tool_loop_reply_f( $engine, $response, $iteration );
358  
359 49 my ( $calls, $data ) = $engine->tool_loop_calls( $reply, $reply->raw );
360 44 my @tool_calls = @$calls;
361 44 ▶ return $reply->content unless @tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless @tool_calls 27 17 44
362  
363 17 my @results;
364 17 for my $tc (@tool_calls) {
365 27 my ( $name, $input ) = ( $tc->name, $tc->arguments );
366  
367 # Arguments that do not decode are answered with an error result
368 # before any plugin sees the call (k345).
369 27 ▶ if ( my $bad = Langertha::Role::Tools::_undecodable_arguments_result($tc) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bad = Langertha::Role::Tools::_undecodable_arguments_result($tc)) 3 24 27
370 3 push @results, { tool_call => $tc, result => $bad };
371 3 next;
372 }
373  
374 24 my @plugin_tc = await $self->_plugin_pipeline_tool_call($name, $input);
375 24 ▶ unless (@plugin_tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@plugin_tc) 1 23 24
376 1 push @results, { tool_call => $tc, result => {
377 content => [{ type => 'text', text => "Tool call '$name' was skipped by plugin." }],
378 }};
379 1 next;
380 }
381 23 ( $name, $input ) = @plugin_tc;
382  
383 # The plugins see every call and may rename one onto a real tool; a
384 # name no server offers after them is answered with an error result,
385 # so the batch runs to the end and the model can correct itself
386 # (k332, k348).
387 23 my $mcp = $tool_server_map->{$name};
388 23 ▶ unless ($mcp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($mcp) 3 20 23
389 3 push @results, { tool_call => $tc,
390 result => Langertha::Role::Tools::_unknown_tool_result($name) };
391 3 next;
392 }
393  
394 0 ▶ my $result = await $mcp->call_tool($name, $input)->else(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
395 0 Future->done({
396 content => [{ type => 'text', text => "Error calling tool '$name': $_[0]" }],
397 isError => JSON->true,
398 });
399 20 });
400  
401 20 $result = await $self->_run_plugin_after_tool_call($name, $input, $result);
402 20 push @results, { tool_call => $tc, result => $result };
403 }
404  
405 17 push @$conversation, $engine->format_tool_results($data, \@results);
406 }
407  
408 0 die "Tool calling loop exceeded " . $self->tool_max_iterations . " iterations";
409 23 }
410  
411  
412  
413 23 __PACKAGE__->meta->make_immutable;
414  
415 23 1;
416  
417 __END__
« blib/lib/Langertha/Role/ContextSize.pm ↑ Summary blib/lib/Langertha/Role/HermesTools.pm »