Langertha/Chat.pm

filter: Statementstmt 67.9% 121 / 178 Branchbran 50.0% 22 / 44 Conditioncond 33.3% 2 / 6 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 80.9% 17 / 21 Podpod 100% 5 / 5 totaltotal 64.9% 167 / 257 CC 34 SCAR 26.6
CC
34
Cov
64%
simple_chat_with_tools_f
63.3
simple_chat_stream
12.0
simple_chat_with_tools
8.3
CRAP 14.3
« Langertha/ToolCall.pm ↑ Summary Langertha/Role/OpenAICompatible.pm »
1 package Langertha::Chat;
2 # ABSTRACT: Chat abstraction wrapping an engine with optional overrides
3 2 our $VERSION = '0.502';
4 2 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 2 with 'Langertha::Role::PluginHost';
11  
12  
13 2 has engine => (
14 is => 'ro',
15 required => 1,
16 );
17  
18 2 has system_prompt => (
19 is => 'ro',
20 isa => 'Str',
21 predicate => 'has_system_prompt',
22 );
23  
24 2 has model => (
25 is => 'ro',
26 isa => 'Str',
27 predicate => 'has_model',
28 );
29  
30 2 has temperature => (
31 is => 'ro',
32 isa => 'Num',
33 predicate => 'has_temperature',
34 );
35  
36 has mcp_servers => (
37 is => 'ro',
38 isa => 'ArrayRef',
39 36 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
40 2 );
41  
42 2 has tool_max_iterations => (
43 is => 'ro',
44 isa => 'Int',
45 default => 10,
46 );
47  
48  
49 sub _extra {
50 27 ▶ my ( $self ) = @_;
Subroutine _extra: called CC=3 SCAR=11.0
51 return (
52 27 ▶ ($self->has_model ? (model => $self->model) : ()),
Branch: 2 branches
BranchTrueFalseTotal
$self->has_model ? : 2 25 27
$self->has_temperature ? : 4 23 27
53 ($self->has_temperature ? (temperature => $self->temperature) : ()),
54 );
55 }
56  
57 sub _build_messages {
58 23 ▶ my ( $self, @messages ) = @_;
Subroutine _build_messages: called CC=3 SCAR=11.0
59 return [
60 ($self->has_system_prompt
61 ? ({ role => 'system', content => $self->system_prompt })
62 : ()),
63 23 ▶ map { ref $_ ? $_ : { role => 'user', content => $_ } } @messages
Branch: 2 branches
BranchTrueFalseTotal
$self->has_system_prompt ? : 5 18 23
ref $_ ? : 3 22 25
64 ];
65 }
66  
67 sub _assert_chat_engine {
68 25 ▶ my ( $self ) = @_;
Subroutine _assert_chat_engine: called CC=2 SCAR=6.9
69 25 my $engine = $self->engine;
70 25 ▶ croak ref($engine) . " does not support chat"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->does("Langertha::Role::Chat") 1 24 25
71 unless $engine->does('Langertha::Role::Chat');
72 24 return $engine;
73 }
74  
75 # --- Plugin hook runners (async) ---
76  
77 27 ▶async sub _run_plugin_before_llm_call {
Subroutine _run_plugin_before_llm_call: called CC=2 SCAR=6.9
78 27 my ( $self, $conversation, $iteration ) = @_;
79 27 for my $plugin (@{$self->_plugin_instances}) {
80 17 $conversation = await $plugin->plugin_before_llm_call($conversation, $iteration);
81 }
82 27 return $conversation;
83 2 }
84  
85 27 ▶async sub _run_plugin_after_llm_response {
Subroutine _run_plugin_after_llm_response: called CC=2 SCAR=6.9
86 27 my ( $self, $data, $iteration ) = @_;
87 27 for my $plugin (@{$self->_plugin_instances}) {
88 17 $data = await $plugin->plugin_after_llm_response($data, $iteration);
89 }
90 27 return $data;
91 2 }
92  
93 4 ▶async sub _run_plugin_after_tool_call {
Subroutine _run_plugin_after_tool_call: called CC=2 SCAR=6.9
94 4 my ( $self, $name, $input, $result ) = @_;
95 4 for my $plugin (@{$self->_plugin_instances}) {
96 3 $result = await $plugin->plugin_after_tool_call($name, $input, $result);
97 }
98 4 return $result;
99 2 }
100  
101 # --- Simple chat (no tools) ---
102  
103 sub simple_chat {
104 20 ▶ my ( $self, @messages ) = @_;
Subroutine simple_chat: called CC=1 SCAR=0.0
Pod documented
105 20 $log->debugf("[Chat] simple_chat via %s", ref $self->engine);
106 20 my $engine = $self->_assert_chat_engine;
107 19 my $conversation = $self->_build_messages(@messages);
108  
109 19 $conversation = $self->_run_plugin_before_llm_call($conversation, 1)->get;
110  
111 19 my $request = $engine->chat_request($conversation, $self->_extra);
112 19 my $response = $engine->user_agent->request($request);
113 19 my $data = $request->response_call->($response);
114  
115 19 $data = $self->_run_plugin_after_llm_response($data, 1)->get;
116  
117 19 return $data;
118 }
119  
120  
121 0 ▶async sub simple_chat_f {
Subroutine simple_chat_f: not called CC=2 SCAR=17.9
Pod documented
122 0 my ( $self, @messages ) = @_;
123 0 my $engine = $self->_assert_chat_engine;
124 0 my $conversation = $self->_build_messages(@messages);
125  
126 0 $conversation = await $self->_run_plugin_before_llm_call($conversation, 1);
127  
128 0 my $request = $engine->chat_request($conversation, $self->_extra);
129 0 my $response = await $engine->_async_http->do_request(
130 request => $request,
131 );
132 0 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
133 0 die "" . (ref $engine) . " request failed: " . $response->status_line;
134 }
135 0 my $data = $request->response_call->($response);
136  
137 0 $data = await $self->_run_plugin_after_llm_response($data, 1);
138  
139 0 return $data;
140 2 }
141  
142  
143 sub simple_chat_stream {
144 0 ▶ my ( $self, $callback, @messages ) = @_;
Subroutine simple_chat_stream: not called CC=3 SCAR=24.8
Pod documented
145 0 my $engine = $self->_assert_chat_engine;
146 0 ▶ croak ref($engine) . " does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->can("chat_stream_request") 0 0 0
147 unless $engine->can('chat_stream_request');
148 0 ▶ croak "simple_chat_stream requires a callback as first argument"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 0 0
149 unless ref $callback eq 'CODE';
150 0 my $conversation = $self->_build_messages(@messages);
151  
152 0 $conversation = $self->_run_plugin_before_llm_call($conversation, 1)->get;
153  
154 0 my $request = $engine->chat_stream_request($conversation, $self->_extra);
155 0 my $chunks = $engine->execute_streaming_request($request, $callback);
156 0 return join('', map { $_->content } @$chunks);
157 }
158  
159  
160 # --- Chat with tools ---
161  
162 sub _gather_tools {
163 5 ▶ my ( $self ) = @_;
Subroutine _gather_tools: called CC=4 SCAR=13.9
164 5 my @mcp_servers = @{$self->mcp_servers};
165 5 ▶ croak "No MCP servers configured" unless @mcp_servers;
Branch: 1 branch
BranchTrueFalseTotal
unless @mcp_servers 1 4 5
166  
167 4 my ( @all_tools, %tool_server_map );
168 4 for my $mcp (@mcp_servers) {
169 4 my $tools = $mcp->list_tools->get;
170 4 for my $tool (@$tools) {
171 5 $tool_server_map{$tool->{name}} = $mcp;
172 5 push @all_tools, $tool;
173 }
174 }
175 4 return (\@all_tools, \%tool_server_map);
176 }
177  
178 sub _tool_loop_iteration {
179 8 ▶ my ( $self, $engine, $conversation, $formatted_tools, $iteration ) = @_;
Subroutine _tool_loop_iteration: called CC=5 SCAR=17.6
180  
181 # Plugin hook: before LLM call
182 8 $conversation = $self->_run_plugin_before_llm_call($conversation, $iteration)->get;
183  
184 # Build and send the request
185 8 my $request = $engine->build_tool_chat_request($conversation, $formatted_tools, $self->_extra);
186  
187 8 my $response = $engine->user_agent->request($request);
188 8 ▶ my $data = ref $response eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
ref $response eq 'HASH' ? : 0 8 8
189 ? $response # mock: chat_request returns data directly via response_call
190 : $engine->parse_response($response);
191  
192 # If response_call exists (Langertha::Request::HTTP), use it
193 8 ▶ if (ref $request && $request->can('response_call') && $request->response_call) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $request and $request->can("response_call") and $request->response_call) 8 0 8
Condition33%2/6
ref $request and $request->can("response_call") and $request->response_call
!ll&&!rl&&r
008
ref $request and $request->can("response_call")
!ll&&!rl&&r
008
MC/DC0%0/3
ref $request and $request->can("response_call") and $request->response_call
ref $request $request->can("response_call") $request->response_call
Truth table25%1/4
A and B and C
A= ref $requestB= $request->can("response_call")C= $request->response_call
ABCresult
0XX0
10X0
1100
1111
194 8 $data = $request->response_call->($response);
195 }
196  
197 # Plugin hook: after LLM response
198 8 $data = $self->_run_plugin_after_llm_response($data, $iteration)->get;
199  
200 8 return ($conversation, $data);
201 }
202  
203 sub simple_chat_with_tools {
204 4 ▶ my ( $self, @messages ) = @_;
Subroutine simple_chat_with_tools: called CC=8 SCAR=21.2
Pod documented
205 4 my $engine = $self->_assert_chat_engine;
206 4 ▶ croak ref($engine) . " does not support tools"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->does("Langertha::Role::Tools") 0 4 4
207 unless $engine->does('Langertha::Role::Tools');
208  
209 4 my ($all_tools, $tool_server_map) = $self->_gather_tools;
210 4 $log->debugf("[Chat] simple_chat_with_tools via %s, %d tools, max_iterations=%d",
211 ref $engine, scalar @$all_tools, $self->tool_max_iterations);
212 4 my $formatted_tools = $engine->format_tools($all_tools);
213 4 my $conversation = $self->_build_messages(@messages);
214  
215 4 for my $iteration (1..$self->tool_max_iterations) {
216 8 ($conversation, my $data) = $self->_tool_loop_iteration(
217 $engine, $conversation, $formatted_tools, $iteration,
218 );
219  
220 8 my $tool_calls = $engine->response_tool_calls($data);
221  
222 8 ▶ unless (@$tool_calls) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$tool_calls) 4 4 8
223 4 my $text = $engine->response_text_content($data);
224 4 ▶ if ($engine->think_tag_filter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->think_tag_filter) 0 4 4
225 0 ($text) = $engine->filter_think_content($text);
226 }
227 4 return $text;
228 }
229  
230 # Execute each tool call
231 4 my @results;
232 4 for my $tc (@$tool_calls) {
233 5 my ( $name, $input ) = $engine->extract_tool_call($tc);
234  
235 5 $log->debugf("[Chat] Calling tool: %s", $name);
236  
237 # Plugin hook: before tool call (can skip)
238 5 my @plugin_tc = $self->_plugin_pipeline_tool_call($name, $input)->get;
239 5 ▶ unless (@plugin_tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@plugin_tc) 1 4 5
240 1 push @results, { tool_call => $tc, result => {
241 content => [{ type => 'text', text => "Tool call '$name' was skipped by plugin." }],
242 }};
243 1 next;
244 }
245 4 ( $name, $input ) = @plugin_tc;
246  
247 4 ▶ my $mcp = $tool_server_map->{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $mcp = $tool_server_map->{$name} or die "Tool '${name}' not found on any MCP server" 0 4 4
248 or die "Tool '$name' not found on any MCP server";
249  
250 my $result = $mcp->call_tool($name, $input)->else(sub {
251 0 ▶ my ( $error ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
252 0 Future->done({
253 content => [{ type => 'text', text => "Error calling tool '$name': $error" }],
254 isError => JSON::MaybeXS->true,
255 });
256 4 })->get;
257  
258 # Plugin hook: after tool call
259 4 $result = $self->_run_plugin_after_tool_call($name, $input, $result)->get;
260  
261 4 push @results, { tool_call => $tc, result => $result };
262 }
263  
264 4 push @$conversation, $engine->format_tool_results($data, \@results);
265 }
266  
267 0 die "Tool calling loop exceeded " . $self->tool_max_iterations . " iterations";
268 }
269  
270  
271 1 ▶async sub simple_chat_with_tools_f {
Subroutine simple_chat_with_tools_f: called CC=9 SCAR=41.5
Pod documented
272 1 my ( $self, @messages ) = @_;
273 1 my $engine = $self->_assert_chat_engine;
274 1 ▶ croak ref($engine) . " does not support tools"
Branch: 1 branch
BranchTrueFalseTotal
unless $engine->does("Langertha::Role::Tools") 0 1 1
275 unless $engine->does('Langertha::Role::Tools');
276  
277 1 my ($all_tools, $tool_server_map) = $self->_gather_tools;
278 0 my $formatted_tools = $engine->format_tools($all_tools);
279 0 my $conversation = $self->_build_messages(@messages);
280  
281 0 for my $iteration (1..$self->tool_max_iterations) {
282 0 $conversation = await $self->_run_plugin_before_llm_call($conversation, $iteration);
283  
284 0 my $request = $engine->build_tool_chat_request($conversation, $formatted_tools, $self->_extra);
285  
286 0 my $response = await $engine->_async_http->do_request(request => $request);
287 0 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
288 0 die "" . (ref $engine) . " tool chat request failed: " . $response->status_line;
289 }
290  
291 0 my $data = $engine->parse_response($response);
292 0 $data = await $self->_run_plugin_after_llm_response($data, $iteration);
293  
294 0 my $tool_calls = $engine->response_tool_calls($data);
295  
296 0 ▶ unless (@$tool_calls) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$tool_calls) 0 0 0
297 0 my $text = $engine->response_text_content($data);
298 0 ▶ if ($engine->think_tag_filter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->think_tag_filter) 0 0 0
299 0 ($text) = $engine->filter_think_content($text);
300 }
301 0 return $text;
302 }
303  
304 0 my @results;
305 0 for my $tc (@$tool_calls) {
306 0 my ( $name, $input ) = $engine->extract_tool_call($tc);
307  
308 0 my @plugin_tc = await $self->_plugin_pipeline_tool_call($name, $input);
309 0 ▶ unless (@plugin_tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@plugin_tc) 0 0 0
310 0 push @results, { tool_call => $tc, result => {
311 content => [{ type => 'text', text => "Tool call '$name' was skipped by plugin." }],
312 }};
313 0 next;
314 }
315 0 ( $name, $input ) = @plugin_tc;
316  
317 0 ▶ my $mcp = $tool_server_map->{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $mcp = $tool_server_map->{$name} or die "Tool '${name}' not found on any MCP server" 0 0 0
318 or die "Tool '$name' not found on any MCP server";
319  
320 my $result = await $mcp->call_tool($name, $input)->else(sub {
321 0 ▶ Future->done({
Subroutine __ANON__: not called CC=1 SCAR=6.9
322 content => [{ type => 'text', text => "Error calling tool '$name': $_[0]" }],
323 isError => JSON::MaybeXS->true,
324 });
325 0 });
326  
327 0 $result = await $self->_run_plugin_after_tool_call($name, $input, $result);
328 0 push @results, { tool_call => $tc, result => $result };
329 }
330  
331 0 push @$conversation, $engine->format_tool_results($data, \@results);
332 }
333  
334 0 die "Tool calling loop exceeded " . $self->tool_max_iterations . " iterations";
335 2 }
336  
337  
338  
339 2 __PACKAGE__->meta->make_immutable;
340  
341 2 1;
342  
343 __END__
344  
345 =pod
346  
347 =encoding UTF-8
348  
349 =head1 NAME
350  
351 Langertha::Chat - Chat abstraction wrapping an engine with optional overrides
352  
353 =head1 VERSION
354  
355 version 0.502
356  
357 =head1 SYNOPSIS
358  
359 use Langertha::Engine::OpenAI;
360 use Langertha::Chat;
361  
362 my $engine = Langertha::Engine::OpenAI->new(
363 api_key => $ENV{OPENAI_API_KEY},
364 model => 'gpt-4o',
365 );
366  
367 my $chat = Langertha::Chat->new(
368 engine => $engine,
369 system_prompt => 'You are a helpful assistant.',
370 plugins => ['Langfuse'],
371 );
372  
373 my $reply = $chat->simple_chat('Hello!');
374  
375 # With MCP tool calling
376 my $chat_tools = Langertha::Chat->new(
377 engine => $engine,
378 mcp_servers => [$mcp],
379 plugins => ['Langfuse'],
380 );
381 my $result = $chat_tools->simple_chat_with_tools('List files in /tmp');
382  
383 =head1 DESCRIPTION
384  
385 C<Langertha::Chat> wraps any engine that consumes L<Langertha::Role::Chat>
386 and adds optional overrides for model, system prompt, and temperature, plus
387 plugin lifecycle hooks via L<Langertha::Role::PluginHost>.
388  
389 Use this class when you want to share a single engine instance across
390 multiple chat contexts with different configurations, or when you need
391 plugin observability (e.g. L<Langertha::Plugin::Langfuse>) without
392 modifying the engine itself.
393  
394 =head2 engine
395  
396 The LLM engine to delegate chat requests to. Must consume
397 L<Langertha::Role::Chat>.
398  
399 =head2 system_prompt
400  
401 Optional system prompt. When set, prepended to messages for each
402 request, overriding any system prompt on the engine itself.
403  
404 =head2 model
405  
406 Optional model name override. When set, overrides the engine's
407 C<chat_model> via C<%extra> pass-through.
408  
409 =head2 temperature
410  
411 Optional temperature override. When set, overrides the engine's
412 temperature.
413  
414 =head2 mcp_servers
415  
416 ArrayRef of L<Net::Async::MCP> instances for tool calling.
417  
418 =head2 tool_max_iterations
419  
420 Maximum tool-calling round trips. Defaults to C<10>.
421  
422 =head2 simple_chat
423  
424 my $response = $chat->simple_chat('Hello!');
425  
426 Sends a synchronous chat request. Fires C<plugin_before_llm_call> and
427 C<plugin_after_llm_response> hooks.
428  
429 =head2 simple_chat_f
430  
431 my $response = await $chat->simple_chat_f('Hello!');
432  
433 Async version of L</simple_chat>.
434  
435 =head2 simple_chat_stream
436  
437 my $content = $chat->simple_chat_stream(sub { print shift->content }, 'Hi');
438  
439 Synchronous streaming chat. Calls C<$callback> with each chunk.
440  
441 =head2 simple_chat_with_tools
442  
443 my $text = $chat->simple_chat_with_tools(@messages);
444  
445 Synchronous tool-calling chat loop. Gathers tools from L</mcp_servers>,
446 sends chat requests, executes tool calls, and iterates until the LLM
447 returns a final text response. Fires plugin hooks at each step:
448 C<plugin_before_llm_call>, C<plugin_after_llm_response>,
449 C<plugin_before_tool_call>, and C<plugin_after_tool_call>.
450  
451 =head2 simple_chat_with_tools_f
452  
453 my $text = await $chat->simple_chat_with_tools_f(@messages);
454  
455 Async version of L</simple_chat_with_tools>.
456  
457 =head1 SEE ALSO
458  
459 =over
460  
461 =item * L<Langertha::Role::PluginHost> - Plugin system consumed by this class
462  
463 =item * L<Langertha::Role::Chat> - Chat role required by the engine
464  
465 =item * L<Langertha::Role::Tools> - Tool-calling role required for MCP methods
466  
467 =item * L<Langertha::Plugin::Langfuse> - Observability plugin for chat sessions
468  
469 =item * L<Langertha::Embedder> - Embedding counterpart to this class
470  
471 =item * L<Langertha::ImageGen> - Image generation counterpart to this class
472  
473 =item * L<Langertha::Raider> - Autonomous agent with full conversation history
474  
475 =back
476  
477 =head1 SUPPORT
478  
479 =head2 Issues
480  
481 Please report bugs and feature requests on GitHub at
482 L<https://github.com/Getty/langertha/issues>.
483  
484 =head2 IRC
485  
486 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
487  
488 =head1 CONTRIBUTING
489  
490 Contributions are welcome! Please fork the repository and submit a pull request.
491  
492 =head1 AUTHOR
493  
494 Torsten Raudssus <getty@cpan.org>
495  
496 =head1 COPYRIGHT AND LICENSE
497  
498 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
499  
500 This is free software; you can redistribute it and/or modify it under
501 the same terms as the Perl 5 programming language system itself.
502  
503 =cut
« Langertha/ToolCall.pm ↑ Summary Langertha/Role/OpenAICompatible.pm »