| 1 | package Langertha::Chat; | ||||||||||||||
| 2 | # ABSTRACT: Chat abstraction wrapping an engine with optional overrides | ||||||||||||||
| 3 | 22 | our $VERSION = '0.503'; | |||||||||||||
| 4 | 22 | ▶ | use Moose; | ||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||
| 5 | 22 | ▶ | use Future::AsyncAwait; | ||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||
| 6 | 22 | ▶ | use Carp qw( croak ); | ||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||
| 7 | 22 | ▶ | use JSON::MaybeXS; | ||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||
| 8 | 22 | ▶ | use Log::Any qw( $log ); | ||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||
| 9 | 22 | ▶ | use Langertha::Role::Tools (); | ||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||
| 10 | |||||||||||||||
| 11 | 22 | with 'Langertha::Role::PluginHost'; | |||||||||||||
| 12 | |||||||||||||||
| 13 | |||||||||||||||
| 14 | 22 | has engine => ( | |||||||||||||
| 15 | is => 'ro', | ||||||||||||||
| 16 | required => 1, | ||||||||||||||
| 17 | ); | ||||||||||||||
| 18 | |||||||||||||||
| 19 | 22 | has system_prompt => ( | |||||||||||||
| 20 | is => 'ro', | ||||||||||||||
| 21 | isa => 'Str', | ||||||||||||||
| 22 | predicate => 'has_system_prompt', | ||||||||||||||
| 23 | ); | ||||||||||||||
| 24 | |||||||||||||||
| 25 | 22 | has model => ( | |||||||||||||
| 26 | is => 'ro', | ||||||||||||||
| 27 | isa => 'Str', | ||||||||||||||
| 28 | predicate => 'has_model', | ||||||||||||||
| 29 | ); | ||||||||||||||
| 30 | |||||||||||||||
| 31 | 22 | 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 | 22 | ); | |||||||||||||
| 42 | |||||||||||||||
| 43 | 22 | has tool_max_iterations => ( | |||||||||||||
| 44 | is => 'ro', | ||||||||||||||
| 45 | isa => 'Int', | ||||||||||||||
| 46 | default => 10, | ||||||||||||||
| 47 | ); | ||||||||||||||
| 48 | |||||||||||||||
| 49 | |||||||||||||||
| 50 | 205 | ▶ | sub _extra { | ||||||||||||
|
Subroutine
_extra: called CC=3 SCAR=11.0
| |||||||||||||||
| 51 | 205 | my ( $self ) = @_; | |||||||||||||
| 52 | return ( | ||||||||||||||
| 53 | 205 | ▶ | ($self->has_model ? (model => $self->model) : ()), | ||||||||||||
|
Branch: 2 branches
| |||||||||||||||
| 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 | 151 | ▶ | sub _warn_model_override { | ||||||||||||
|
Subroutine
_warn_model_override: called CC=3 SCAR=11.0
| |||||||||||||||
| 63 | 151 | my ( $self, $method, $streaming, %request ) = @_; | |||||||||||||
| 64 | 151 | ▶ | return unless $self->has_model; | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 65 | 12 | my $engine = $self->engine; | |||||||||||||
| 66 | 12 | ▶ | return unless $engine->can('_warn_model_override'); | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 151 | ▶ | sub _build_messages { | ||||||||||||
|
Subroutine
_build_messages: called CC=5 SCAR=16.1
| |||||||||||||||
| 77 | 151 | my ( $self, @messages ) = @_; | |||||||||||||
| 78 | 151 | my $engine = $self->engine; | |||||||||||||
| 79 | 151 | my $normalize = $engine->can('_normalize_content_blocks'); | |||||||||||||
| 80 | 151 | ▶ | my @override = $self->has_system_prompt ? ( $self->system_prompt ) : (); | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 81 | return [ | ||||||||||||||
| 82 | ( $engine->can('_system_messages') | ||||||||||||||
| 83 | ? $engine->_system_messages(@override) | ||||||||||||||
| 84 | 5 | : map { +{ role => 'system', content => $_ } } @override ), | |||||||||||||
| 85 | map { | ||||||||||||||
| 86 | 151 | ▶ | my $msg = ref $_ ? $_ : { role => 'user', content => $_ }; | ||||||||||||
|
Branch: 2 branches
| |||||||||||||||
| 87 | 153 | ▶ | $normalize ? $engine->$normalize($msg) : $msg; | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 72 | ▶ | async sub _build_messages_f { | ||||||||||||
|
Subroutine
_build_messages_f: called CC=2 SCAR=7.0
| |||||||||||||||
| 95 | 72 | my ( $self, @messages ) = @_; | |||||||||||||
| 96 | 72 | my $engine = $self->engine; | |||||||||||||
| 97 | 72 | ▶ | @messages = await $engine->_prefetch_inline_images_f(@messages) | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 98 | if $engine->can('_prefetch_inline_images_f'); | ||||||||||||||
| 99 | 72 | return $self->_build_messages(@messages); | |||||||||||||
| 100 | 22 | } | |||||||||||||
| 101 | |||||||||||||||
| 102 | 153 | ▶ | sub _assert_chat_engine { | ||||||||||||
|
Subroutine
_assert_chat_engine: called CC=2 SCAR=6.9
| |||||||||||||||
| 103 | 153 | my ( $self ) = @_; | |||||||||||||
| 104 | 153 | my $engine = $self->engine; | |||||||||||||
| 105 | 153 | ▶ | croak ref($engine) . " does not support chat" | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 106 | unless $engine->does('Langertha::Role::Chat'); | ||||||||||||||
| 107 | 152 | return $engine; | |||||||||||||
| 108 | } | ||||||||||||||
| 109 | |||||||||||||||
| 110 | # --- Plugin hook runners (async) --- | ||||||||||||||
| 111 | |||||||||||||||
| 112 | 195 | ▶ | async sub _run_plugin_before_llm_call { | ||||||||||||
|
Subroutine
_run_plugin_before_llm_call: called CC=2 SCAR=6.9
| |||||||||||||||
| 113 | 195 | my ( $self, $conversation, $iteration ) = @_; | |||||||||||||
| 114 | 195 | for my $plugin (@{$self->_plugin_instances}) { | |||||||||||||
| 115 | 74 | $conversation = await $plugin->plugin_before_llm_call($conversation, $iteration); | |||||||||||||
| 116 | } | ||||||||||||||
| 117 | 195 | return $conversation; | |||||||||||||
| 118 | 22 | } | |||||||||||||
| 119 | |||||||||||||||
| 120 | 189 | ▶ | async sub _run_plugin_after_llm_response { | ||||||||||||
|
Subroutine
_run_plugin_after_llm_response: called CC=2 SCAR=6.9
| |||||||||||||||
| 121 | 189 | my ( $self, $data, $iteration ) = @_; | |||||||||||||
| 122 | 189 | for my $plugin (@{$self->_plugin_instances}) { | |||||||||||||
| 123 | 74 | $data = await $plugin->plugin_after_llm_response($data, $iteration); | |||||||||||||
| 124 | } | ||||||||||||||
| 125 | 189 | return $data; | |||||||||||||
| 126 | 22 | } | |||||||||||||
| 127 | |||||||||||||||
| 128 | 50 | ▶ | async sub _run_plugin_after_tool_call { | ||||||||||||
|
Subroutine
_run_plugin_after_tool_call: called CC=2 SCAR=6.9
| |||||||||||||||
| 129 | 50 | my ( $self, $name, $input, $result ) = @_; | |||||||||||||
| 130 | 50 | for my $plugin (@{$self->_plugin_instances}) { | |||||||||||||
| 131 | 23 | $result = await $plugin->plugin_after_tool_call($name, $input, $result); | |||||||||||||
| 132 | } | ||||||||||||||
| 133 | 50 | return $result; | |||||||||||||
| 134 | 22 | } | |||||||||||||
| 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
| |||||||||||||||
| 163 | 4 | ▶ | return $engine->can('_request_failed_message') | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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
| |||||||||||||||
| 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 | 22 | } | |||||||||||||
| 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
| |||||||||||||||
| 195 | unless $engine->can('chat_stream_request'); | ||||||||||||||
| 196 | 1 | ▶ | croak "simple_chat_stream requires a callback as first argument" | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 94 | ▶ | sub _gather_tools { | ||||||||||||
|
Subroutine
_gather_tools: called CC=2 SCAR=6.9
| |||||||||||||||
| 212 | 94 | my ( $self ) = @_; | |||||||||||||
| 213 | 94 | my @mcp_servers = @{$self->mcp_servers}; | |||||||||||||
| 214 | 94 | ▶ | croak "No MCP servers configured" unless @mcp_servers; | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 215 | |||||||||||||||
| 216 | # A name two servers offer goes on the wire once, from the first (k332). | ||||||||||||||
| 217 | return $self->engine->_tool_loop_tools( | ||||||||||||||
| 218 | 93 | map { [ $_, $_->list_tools->get ] } @mcp_servers ); | |||||||||||||
| 219 | } | ||||||||||||||
| 220 | |||||||||||||||
| 221 | 80 | ▶ | sub _tool_loop_iteration { | ||||||||||||
|
Subroutine
_tool_loop_iteration: called CC=2 SCAR=6.9
| |||||||||||||||
| 222 | 80 | my ( $self, $engine, $conversation, $formatted_tools, $iteration ) = @_; | |||||||||||||
| 223 | |||||||||||||||
| 224 | # Plugin hook: before LLM call | ||||||||||||||
| 225 | 80 | $conversation = $self->_run_plugin_before_llm_call($conversation, $iteration)->get; | |||||||||||||
| 226 | |||||||||||||||
| 227 | # Build and send the request | ||||||||||||||
| 228 | 80 | my $request = $engine->build_tool_chat_request($conversation, $formatted_tools, $self->_extra); | |||||||||||||
| 229 | |||||||||||||||
| 230 | 80 | my $response = $engine->user_agent->request($request); | |||||||||||||
| 231 | # The same failure text and rate-limit update as the async loop (karr k312). | ||||||||||||||
| 232 | 80 | ▶ | die $self->_failed_message( $engine, $response, 'tool chat request' ) | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 233 | unless $response->is_success; | ||||||||||||||
| 234 | |||||||||||||||
| 235 | 79 | my $reply = $self->_tool_loop_reply_f( $engine, $response, $iteration )->get; | |||||||||||||
| 236 | |||||||||||||||
| 237 | 70 | 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 | 135 | ▶ | async sub _tool_loop_reply_f { | ||||||||||||
|
Subroutine
_tool_loop_reply_f: called CC=1 SCAR=0.0
| |||||||||||||||
| 249 | 135 | my ( $self, $engine, $response, $iteration ) = @_; | |||||||||||||
| 250 | 135 | my $data = $engine->parse_response($response); | |||||||||||||
| 251 | 135 | $data = await $self->_run_plugin_after_llm_response($data, $iteration); | |||||||||||||
| 252 | 135 | return $engine->tool_loop_response($data); | |||||||||||||
| 253 | 22 | } | |||||||||||||
| 254 | |||||||||||||||
| 255 | 52 | ▶ | sub simple_chat_with_tools { | ||||||||||||
|
Subroutine
simple_chat_with_tools: called CC=8 SCAR=20.8
Pod
documented
| |||||||||||||||
| 256 | 52 | my ( $self, @messages ) = @_; | |||||||||||||
| 257 | 52 | my $engine = $self->_assert_chat_engine; | |||||||||||||
| 258 | 52 | ▶ | croak ref($engine) . " does not support tools" | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 259 | unless $engine->does('Langertha::Role::Tools'); | ||||||||||||||
| 260 | |||||||||||||||
| 261 | 52 | my ($all_tools, $tool_server_map) = $self->_gather_tools; | |||||||||||||
| 262 | 52 | $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 | 52 | my $formatted_tools = $engine->format_tools($all_tools); | |||||||||||||
| 265 | 52 | $self->_warn_model_override( 'simple_chat_with_tools', 0, tools => $formatted_tools ); | |||||||||||||
| 266 | 52 | my $conversation = $self->_build_messages(@messages); | |||||||||||||
| 267 | |||||||||||||||
| 268 | 52 | for my $iteration (1..$self->tool_max_iterations) { | |||||||||||||
| 269 | 80 | ($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 | 70 | ( my $calls, $data ) = $engine->tool_loop_calls( $reply, $reply->raw ); | |||||||||||||
| 275 | 65 | my @tool_calls = @$calls; | |||||||||||||
| 276 | 65 | ▶ | return $reply->content unless @tool_calls; | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 277 | |||||||||||||||
| 278 | # Execute each tool call | ||||||||||||||
| 279 | 28 | my @results; | |||||||||||||
| 280 | 28 | for my $tc (@tool_calls) { | |||||||||||||
| 281 | 39 | 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 | 39 | ▶ | if ( my $bad = Langertha::Role::Tools::_undecodable_arguments_result($tc) ) { | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 286 | 3 | push @results, { tool_call => $tc, result => $bad }; | |||||||||||||
| 287 | 3 | next; | |||||||||||||
| 288 | } | ||||||||||||||
| 289 | |||||||||||||||
| 290 | 36 | $log->debugf("[Chat] Calling tool: %s", $name); | |||||||||||||
| 291 | |||||||||||||||
| 292 | # Plugin hook: before tool call (can skip) | ||||||||||||||
| 293 | 36 | my @plugin_tc = $self->_plugin_pipeline_tool_call($name, $input)->get; | |||||||||||||
| 294 | 36 | ▶ | unless (@plugin_tc) { | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 34 | ( $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 | 34 | my $mcp = $tool_server_map->{$name}; | |||||||||||||
| 307 | 34 | ▶ | unless ($mcp) { | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 31 | })->get; | |||||||||||||
| 320 | |||||||||||||||
| 321 | # Plugin hook: after tool call | ||||||||||||||
| 322 | 31 | $result = $self->_run_plugin_after_tool_call($name, $input, $result)->get; | |||||||||||||
| 323 | |||||||||||||||
| 324 | 31 | push @results, { tool_call => $tc, result => $result }; | |||||||||||||
| 325 | } | ||||||||||||||
| 326 | |||||||||||||||
| 327 | 28 | 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 | 42 | ▶ | async sub simple_chat_with_tools_f { | ||||||||||||
|
Subroutine
simple_chat_with_tools_f: called CC=9 SCAR=22.0
Pod
documented
| |||||||||||||||
| 335 | 42 | my ( $self, @messages ) = @_; | |||||||||||||
| 336 | 42 | my $engine = $self->_assert_chat_engine; | |||||||||||||
| 337 | 42 | ▶ | croak ref($engine) . " does not support tools" | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 338 | unless $engine->does('Langertha::Role::Tools'); | ||||||||||||||
| 339 | |||||||||||||||
| 340 | 42 | my ($all_tools, $tool_server_map) = $self->_gather_tools; | |||||||||||||
| 341 | 41 | my $formatted_tools = $engine->format_tools($all_tools); | |||||||||||||
| 342 | 41 | $self->_warn_model_override( 'simple_chat_with_tools_f', 0, tools => $formatted_tools ); | |||||||||||||
| 343 | 41 | my $conversation = await $self->_build_messages_f(@messages); | |||||||||||||
| 344 | |||||||||||||||
| 345 | 41 | for my $iteration (1..$self->tool_max_iterations) { | |||||||||||||
| 346 | 57 | $conversation = await $self->_run_plugin_before_llm_call($conversation, $iteration); | |||||||||||||
| 347 | |||||||||||||||
| 348 | 57 | my $request = $engine->build_tool_chat_request($conversation, $formatted_tools, $self->_extra); | |||||||||||||
| 349 | |||||||||||||||
| 350 | 57 | my $response = await $engine->_async_do_request_f(request => $request); | |||||||||||||
| 351 | 57 | ▶ | unless ($response->is_success) { | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 56 | my $reply = await $self->_tool_loop_reply_f( $engine, $response, $iteration ); | |||||||||||||
| 358 | |||||||||||||||
| 359 | 47 | my ( $calls, $data ) = $engine->tool_loop_calls( $reply, $reply->raw ); | |||||||||||||
| 360 | 42 | my @tool_calls = @$calls; | |||||||||||||
| 361 | 42 | ▶ | return $reply->content unless @tool_calls; | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 362 | |||||||||||||||
| 363 | 16 | my @results; | |||||||||||||
| 364 | 16 | for my $tc (@tool_calls) { | |||||||||||||
| 365 | 26 | 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 | 26 | ▶ | if ( my $bad = Langertha::Role::Tools::_undecodable_arguments_result($tc) ) { | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 370 | 3 | push @results, { tool_call => $tc, result => $bad }; | |||||||||||||
| 371 | 3 | next; | |||||||||||||
| 372 | } | ||||||||||||||
| 373 | |||||||||||||||
| 374 | 23 | my @plugin_tc = await $self->_plugin_pipeline_tool_call($name, $input); | |||||||||||||
| 375 | 23 | ▶ | unless (@plugin_tc) { | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 22 | ( $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 | 22 | my $mcp = $tool_server_map->{$name}; | |||||||||||||
| 388 | 22 | ▶ | unless ($mcp) { | ||||||||||||
|
Branch: 1 branch
| |||||||||||||||
| 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 | 19 | }); | |||||||||||||
| 400 | |||||||||||||||
| 401 | 19 | $result = await $self->_run_plugin_after_tool_call($name, $input, $result); | |||||||||||||
| 402 | 19 | push @results, { tool_call => $tc, result => $result }; | |||||||||||||
| 403 | } | ||||||||||||||
| 404 | |||||||||||||||
| 405 | 16 | push @$conversation, $engine->format_tool_results($data, \@results); | |||||||||||||
| 406 | } | ||||||||||||||
| 407 | |||||||||||||||
| 408 | 0 | die "Tool calling loop exceeded " . $self->tool_max_iterations . " iterations"; | |||||||||||||
| 409 | 22 | } | |||||||||||||
| 410 | |||||||||||||||
| 411 | |||||||||||||||
| 412 | |||||||||||||||
| 413 | 22 | __PACKAGE__->meta->make_immutable; | |||||||||||||
| 414 | |||||||||||||||
| 415 | 22 | 1; | |||||||||||||
| 416 | |||||||||||||||
| 417 | __END__ | ||||||||||||||
| 418 | |||||||||||||||
| 419 | =pod | ||||||||||||||
| 420 | |||||||||||||||
| 421 | =encoding UTF-8 | ||||||||||||||
| 422 | |||||||||||||||
| 423 | =head1 NAME | ||||||||||||||
| 424 | |||||||||||||||
| 425 | Langertha::Chat - Chat abstraction wrapping an engine with optional overrides | ||||||||||||||
| 426 | |||||||||||||||
| 427 | =head1 VERSION | ||||||||||||||
| 428 | |||||||||||||||
| 429 | version 0.503 | ||||||||||||||
| 430 | |||||||||||||||
| 431 | =head1 SYNOPSIS | ||||||||||||||
| 432 | |||||||||||||||
| 433 | use Langertha::Engine::OpenAI; | ||||||||||||||
| 434 | use Langertha::Chat; | ||||||||||||||
| 435 | |||||||||||||||
| 436 | my $engine = Langertha::Engine::OpenAI->new( | ||||||||||||||
| 437 | api_key => $ENV{OPENAI_API_KEY}, | ||||||||||||||
| 438 | model => 'gpt-4o', | ||||||||||||||
| 439 | ); | ||||||||||||||
| 440 | |||||||||||||||
| 441 | my $chat = Langertha::Chat->new( | ||||||||||||||
| 442 | engine => $engine, | ||||||||||||||
| 443 | system_prompt => 'You are a helpful assistant.', | ||||||||||||||
| 444 | plugins => ['Langfuse'], | ||||||||||||||
| 445 | ); | ||||||||||||||
| 446 | |||||||||||||||
| 447 | my $reply = $chat->simple_chat('Hello!'); | ||||||||||||||
| 448 | |||||||||||||||
| 449 | # With MCP tool calling | ||||||||||||||
| 450 | my $chat_tools = Langertha::Chat->new( | ||||||||||||||
| 451 | engine => $engine, | ||||||||||||||
| 452 | mcp_servers => [$mcp], | ||||||||||||||
| 453 | plugins => ['Langfuse'], | ||||||||||||||
| 454 | ); | ||||||||||||||
| 455 | my $result = $chat_tools->simple_chat_with_tools('List files in /tmp'); | ||||||||||||||
| 456 | |||||||||||||||
| 457 | =head1 DESCRIPTION | ||||||||||||||
| 458 | |||||||||||||||
| 459 | C<Langertha::Chat> wraps any engine that consumes L<Langertha::Role::Chat> | ||||||||||||||
| 460 | and adds optional overrides for model, system prompt, and temperature, plus | ||||||||||||||
| 461 | plugin lifecycle hooks via L<Langertha::Role::PluginHost>. | ||||||||||||||
| 462 | |||||||||||||||
| 463 | Use this class when you want to share a single engine instance across | ||||||||||||||
| 464 | multiple chat contexts with different configurations, or when you need | ||||||||||||||
| 465 | plugin observability (e.g. L<Langertha::Plugin::Langfuse>) without | ||||||||||||||
| 466 | modifying the engine itself. | ||||||||||||||
| 467 | |||||||||||||||
| 468 | =head2 engine | ||||||||||||||
| 469 | |||||||||||||||
| 470 | The LLM engine to delegate chat requests to. Must consume | ||||||||||||||
| 471 | L<Langertha::Role::Chat>. | ||||||||||||||
| 472 | |||||||||||||||
| 473 | =head2 system_prompt | ||||||||||||||
| 474 | |||||||||||||||
| 475 | Optional system prompt. When set, prepended to messages for each | ||||||||||||||
| 476 | request in place of the engine's own C<system_prompt>. When not set, the | ||||||||||||||
| 477 | engine's C<system_prompt> is sent, exactly as the engine's own | ||||||||||||||
| 478 | C<chat_messages> would send it. System messages the engine itself mandates | ||||||||||||||
| 479 | still apply either way: with L<Langertha::Engine::NousResearch> and | ||||||||||||||
| 480 | C<reasoning> enabled, its C<reasoning_prompt> leads the conversation, | ||||||||||||||
| 481 | followed by this system prompt. Plugins see these system messages in the | ||||||||||||||
| 482 | conversation passed to C<plugin_before_llm_call>. | ||||||||||||||
| 483 | |||||||||||||||
| 484 | =head2 model | ||||||||||||||
| 485 | |||||||||||||||
| 486 | Optional model name override. When set, it is passed to the engine's request | ||||||||||||||
| 487 | builder as a per-request C<model> through C<%extra>: it replaces the model in | ||||||||||||||
| 488 | the request body, or in the URL on engines that name the model there | ||||||||||||||
| 489 | (L<Langertha::Engine::Gemini>, L<Langertha::Engine::AKI>). It does not change | ||||||||||||||
| 490 | the engine's C<chat_model>, and every model-scoped decision (capabilities, tool | ||||||||||||||
| 491 | wire format, reasoning profile, body details) is still taken for | ||||||||||||||
| 492 | C<chat_model>, as for a C<model> passed to L<Langertha::Role::Chat/chat_f>. | ||||||||||||||
| 493 | When one of those decisions that the call uses would differ for this model, | ||||||||||||||
| 494 | each chat call warns once and names the decisions; the request is sent | ||||||||||||||
| 495 | unchanged. For a different model, use an engine whose C<chat_model> is that | ||||||||||||||
| 496 | model. | ||||||||||||||
| 497 | |||||||||||||||
| 498 | =head2 temperature | ||||||||||||||
| 499 | |||||||||||||||
| 500 | Optional temperature override. When set, overrides the engine's | ||||||||||||||
| 501 | temperature. | ||||||||||||||
| 502 | |||||||||||||||
| 503 | =head2 mcp_servers | ||||||||||||||
| 504 | |||||||||||||||
| 505 | ArrayRef of MCP client objects for tool calling — any | ||||||||||||||
| 506 | L<Net::Async::MCP>-compatible client (for example a L<Net::Async::MCP> client | ||||||||||||||
| 507 | as used by the langertha-raider distribution). Each must respond to | ||||||||||||||
| 508 | C<list_tools> and C<call_tool>. | ||||||||||||||
| 509 | |||||||||||||||
| 510 | =head2 tool_max_iterations | ||||||||||||||
| 511 | |||||||||||||||
| 512 | Maximum tool-calling round trips. Defaults to C<10>. | ||||||||||||||
| 513 | |||||||||||||||
| 514 | =head2 simple_chat | ||||||||||||||
| 515 | |||||||||||||||
| 516 | my $response = $chat->simple_chat('Hello!'); | ||||||||||||||
| 517 | |||||||||||||||
| 518 | Sends a synchronous chat request. Fires C<plugin_before_llm_call> and | ||||||||||||||
| 519 | C<plugin_after_llm_response> hooks. | ||||||||||||||
| 520 | |||||||||||||||
| 521 | =head2 simple_chat_f | ||||||||||||||
| 522 | |||||||||||||||
| 523 | my $response = await $chat->simple_chat_f('Hello!'); | ||||||||||||||
| 524 | |||||||||||||||
| 525 | Async version of L</simple_chat>. | ||||||||||||||
| 526 | |||||||||||||||
| 527 | =head2 simple_chat_stream | ||||||||||||||
| 528 | |||||||||||||||
| 529 | my $content = $chat->simple_chat_stream(sub { print shift->content }, 'Hi'); | ||||||||||||||
| 530 | |||||||||||||||
| 531 | Synchronous streaming chat. Calls C<$callback> with each chunk. | ||||||||||||||
| 532 | |||||||||||||||
| 533 | =head2 simple_chat_with_tools | ||||||||||||||
| 534 | |||||||||||||||
| 535 | my $text = $chat->simple_chat_with_tools(@messages); | ||||||||||||||
| 536 | |||||||||||||||
| 537 | Synchronous tool-calling chat loop. Gathers tools from L</mcp_servers>, | ||||||||||||||
| 538 | sends chat requests, executes tool calls, and iterates until the LLM | ||||||||||||||
| 539 | returns a final text response. Fires plugin hooks at each step: | ||||||||||||||
| 540 | C<plugin_before_llm_call>, C<plugin_after_llm_response>, | ||||||||||||||
| 541 | C<plugin_before_tool_call>, and C<plugin_after_tool_call>. | ||||||||||||||
| 542 | |||||||||||||||
| 543 | Each reply is read by the engine's C<chat_response>, as in | ||||||||||||||
| 544 | L<Langertha::Role::Chat/chat_f>: a response whose body reports an error fails | ||||||||||||||
| 545 | with the same text, the final text is the reply's C<content>, and the calls | ||||||||||||||
| 546 | run are its L<Langertha::Response/tool_calls>. C<plugin_after_llm_response> | ||||||||||||||
| 547 | receives the raw decoded wire body before it is read, and the body it returns | ||||||||||||||
| 548 | is what the turn is read from: the calls run, the final text and the | ||||||||||||||
| 549 | assistant turn echoed back to the provider all follow its edits, so a call a | ||||||||||||||
| 550 | plugin removes is neither run nor echoed. A failed request dies with | ||||||||||||||
| 551 | C<tool chat request failed>, in the sync and the async loop alike. A call | ||||||||||||||
| 552 | whose arguments were cut off by the token limit is not run, a call whose | ||||||||||||||
| 553 | arguments otherwise do not decode is answered with an error result, a call to an | ||||||||||||||
| 554 | unknown tool is answered with an error result, and a tool name two servers | ||||||||||||||
| 555 | offer runs on the first, and a blocked prompt dies with C<prompt blocked>, as | ||||||||||||||
| 556 | in L<Langertha::Role::Tools/chat_with_tools_f>. Whether a tool is unknown is | ||||||||||||||
| 557 | decided on the name C<plugin_before_tool_call> returns: every call reaches the | ||||||||||||||
| 558 | plugins, and one may map a hallucinated name onto a real tool. | ||||||||||||||
| 559 | |||||||||||||||
| 560 | =head2 simple_chat_with_tools_f | ||||||||||||||
| 561 | |||||||||||||||
| 562 | my $text = await $chat->simple_chat_with_tools_f(@messages); | ||||||||||||||
| 563 | |||||||||||||||
| 564 | Async version of L</simple_chat_with_tools>. | ||||||||||||||
| 565 | |||||||||||||||
| 566 | =head1 SEE ALSO | ||||||||||||||
| 567 | |||||||||||||||
| 568 | =over | ||||||||||||||
| 569 | |||||||||||||||
| 570 | =item * L<Langertha::Role::PluginHost> - Plugin system consumed by this class | ||||||||||||||
| 571 | |||||||||||||||
| 572 | =item * L<Langertha::Role::Chat> - Chat role required by the engine | ||||||||||||||
| 573 | |||||||||||||||
| 574 | =item * L<Langertha::Role::Tools> - Tool-calling role required for MCP methods | ||||||||||||||
| 575 | |||||||||||||||
| 576 | =item * L<Langertha::Plugin::Langfuse> - Observability plugin for chat sessions | ||||||||||||||
| 577 | |||||||||||||||
| 578 | =item * L<Langertha::Embedder> - Embedding counterpart to this class | ||||||||||||||
| 579 | |||||||||||||||
| 580 | =item * L<Langertha::ImageGen> - Image generation counterpart to this class | ||||||||||||||
| 581 | |||||||||||||||
| 582 | =item * L<Langertha::Raider> - Autonomous agent with full conversation history | ||||||||||||||
| 583 | |||||||||||||||
| 584 | =back | ||||||||||||||
| 585 | |||||||||||||||
| 586 | =head1 SUPPORT | ||||||||||||||
| 587 | |||||||||||||||
| 588 | =head2 Issues | ||||||||||||||
| 589 | |||||||||||||||
| 590 | Please report bugs and feature requests on GitHub at | ||||||||||||||
| 591 | L<https://github.com/Getty/langertha/issues>. | ||||||||||||||
| 592 | |||||||||||||||
| 593 | =head2 IRC | ||||||||||||||
| 594 | |||||||||||||||
| 595 | Join C<#langertha> on C<irc.perl.org> or message Getty directly. | ||||||||||||||
| 596 | |||||||||||||||
| 597 | =head1 CONTRIBUTING | ||||||||||||||
| 598 | |||||||||||||||
| 599 | Contributions are welcome! Please fork the repository and submit a pull request. | ||||||||||||||
| 600 | |||||||||||||||
| 601 | =head1 AUTHOR | ||||||||||||||
| 602 | |||||||||||||||
| 603 | Torsten Raudssus <getty@cpan.org> | ||||||||||||||
| 604 | |||||||||||||||
| 605 | =head1 COPYRIGHT AND LICENSE | ||||||||||||||
| 606 | |||||||||||||||
| 607 | This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>. | ||||||||||||||
| 608 | |||||||||||||||
| 609 | This is free software; you can redistribute it and/or modify it under | ||||||||||||||
| 610 | the same terms as the Perl 5 programming language system itself. | ||||||||||||||
| 611 | |||||||||||||||
| 612 | =cut | ||||||||||||||