blib/lib/Langertha/Role/Tools.pm

filter: Statementstmt 93.7% 392 / 418 Branchbran 85.5% 183 / 214 Conditioncond 62.6% 89 / 142 MC/DCmcdc 41.3% 31 / 75 Subroutinesub 96.0% 49 / 51 Podpod 100% 9 / 9 totaltotal 82.8% 753 / 909 CC 180 SCAR 36.6
CC
180
Cov
86%
_raw_text_content
245.7
_hermes_stream_split
32.3
format_tool_results
22.2
CRAP 38.7
« blib/lib/Langertha/Usage.pm ↑ Summary blib/lib/Langertha/Engine/LMStudio.pm »
1 package Langertha::Role::Tools;
2 # ABSTRACT: Role for MCP tool calling support
3 182 our $VERSION = '0.503';
4 182 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 182 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 182 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 182 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 182 ▶use Scalar::Util qw( blessed refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 182 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 182 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 182 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 182 ▶use Langertha::ToolResult;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 182 with 'Langertha::Role::ParallelToolUse';
15  
16  
17 has mcp_servers => (
18 is => 'ro',
19 isa => 'ArrayRef',
20 3816 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
21 182 );
22  
23  
24 182 has tool_max_iterations => (
25 is => 'ro',
26 isa => 'Int',
27 default => 10,
28 );
29  
30  
31 has tool_wire_format => (
32 is => 'ro',
33 isa => 'Str',
34 lazy => 1,
35 builder => '_build_tool_wire_format',
36 clearer => '_clear_tool_wire_format',
37 10 ▶ trigger => sub { $_[0]->_set_tool_wire_format_given(1) },
Subroutine __ANON__: called CC=1 SCAR=0.0
38 182 );
39  
40 # A lazy slot looks the same whether the constructor filled it or the builder
41 # did, but only the builder's value may be dropped when a clone_object copy
42 # changes chat_model (Manifest::Builder's per-model probe, karr k251). The
43 # trigger fires for a constructor value and never for the builder, so this
44 # flag tells the two apart; clone_object copies it along with the tag.
45 182 has _tool_wire_format_given => (
46 is => 'ro',
47 isa => 'Bool',
48 init_arg => undef,
49 default => 0,
50 writer => '_set_tool_wire_format_given',
51 );
52  
53 # Drops a builder-made tag so the next read resolves it again (for the
54 # clone's chat_model); a constructor tag stays.
55 117 ▶sub _reset_derived_tool_wire_format {
Subroutine _reset_derived_tool_wire_format: called CC=2 SCAR=6.9
56 117 my ($self) = @_;
57 117 ▶ $self->_clear_tool_wire_format unless $self->_tool_wire_format_given;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_tool_wire_format_given 113 4 117
58 117 return $self;
59 }
60  
61 # Defaults to the OpenAI dialect; AnthropicCompatible, HermesTools, and
62 # OpenAIResponses override the builder via -excludes, while Engines (Ollama,
63 # Gemini, AKI, NousResearch) ship their own override. See
64 # Langertha::Engine::AnthropicBase:9-23 for the canonical -excludes exemplar.
65 234 ▶sub _build_tool_wire_format { 'openai' }
Subroutine _build_tool_wire_format: called CC=1 SCAR=0.0
66  
67  
68 # The five tool-format methods below are tag-driven defaults: they delegate to
69 # the Langertha::Tool / ToolCall / ToolResult value objects keyed by
70 # L</tool_wire_format>. Engines no longer carry per-format copies.
71  
72 194 ▶sub build_tool_chat_request {
Subroutine build_tool_chat_request: called CC=2 SCAR=6.9
Pod documented
73 194 my ( $self, $conversation, $formatted_tools, %extra ) = @_;
74 194 ▶ if ( $self->tool_wire_format eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->tool_wire_format eq "hermes") 27 167 194
75 27 return $self->chat_request( $self->_hermes_tool_messages( $conversation, $formatted_tools ), %extra );
76 }
77 167 return $self->chat_request( $conversation, tools => $formatted_tools, %extra );
78 }
79  
80 # The hermes wire has no tools body key: the tools ride a leading system
81 # message built from hermes_tool_prompt. Shared by the tool loop and by a
82 # single chat_f / chat_stream_realtime_f turn (karr k231).
83 181 ▶sub _hermes_tool_messages {
Subroutine _hermes_tool_messages: called CC=1 SCAR=0.0
84 181 my ( $self, $conversation, $formatted_tools ) = @_;
85 181 my $tool_prompt = sprintf( $self->hermes_tool_prompt, $self->encode_json_text($formatted_tools) );
86 181 return [ { role => 'system', content => $tool_prompt }, @$conversation ];
87 }
88  
89 # Splits hermes model text into the text without the call tags and the
90 # well-formed calls ({name, arguments} HASHes) the tags carried, honoring
91 # hermes_call_tag. Shared by response_tool_calls, response_text_content,
92 # chat_f's reply lift (karr k231) and the streamed lift (k253). Delegates to
93 # Langertha::ToolCall->extract_hermes_from_text, the one hermes lift (k255):
94 # only a well-formed call reaches the tool loop (k163), a block that carries
95 # no call stays in the text where it was (k253 review).
96 236 ▶sub _hermes_split_text {
Subroutine _hermes_split_text: called CC=3 SCAR=11.0
97 236 my ( $self, $text ) = @_;
98 236 my ( $content, $calls ) = Langertha::ToolCall->extract_hermes_from_text(
99 $text, tag => $self->hermes_call_tag );
100 # Carry the k345 undecodable flag through the reduced hash so it survives the
101 # Response tool_calls upgrade and the tool loop answers a bad hermes call an
102 # error result rather than running the tool on {} -- karr k350.
103 return ( $content, [ map {
104 236 ▶ { name => $_->name, arguments => $_->arguments,
Branch: 2 branches
BranchTrueFalseTotal
$_->arguments_undecodable ? : 14 161 175
$_->has_arguments_error ? : 14 0 14
105 ( $_->arguments_undecodable
106 ? ( arguments_undecodable => 1,
107 ( $_->has_arguments_error ? ( arguments_error => $_->arguments_error ) : () ) )
108 : () ) }
109 } @$calls ] );
110 }
111  
112 # The streamed counterpart of chat_f's reply lift (karr k253, ADR 0001): text
113 # inside <tool_call>...</tool_call> (hermes_call_tag) is not emitted, and the
114 # calls land on the final chunk. Called by chat_stream_realtime_f for each
115 # chunk of a turn whose tools went into the prompt; returns the chunk to
116 # deliver, or undef for a chunk that carried only call markup. Each closed
117 # block goes through _hermes_split_text, so the stream finds the calls chat_f
118 # finds and streams a block that is no call as text, where chat_f keeps it.
119 # $flush (the stream ended without a final chunk) returns the chunk for
120 # whatever is still held, or undef when nothing is. finish_reason becomes
121 # tool_calls only over stop or none, as chat_f's lift (k253 review).
122 1649 ▶sub _hermes_stream_chunk {
Subroutine _hermes_stream_chunk: called CC=20 SCAR=30.4
123 1649 my ( $self, $state, $chunk, $flush ) = @_;
124 1649 ▶ if ($flush) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flush) 119 1530 1649
125 119 ▶ return if $state->{done};
Branch: 1 branch
BranchTrueFalseTotal
if $state->{"done"} 117 2 119
126 2 my $text = $self->_hermes_stream_split( $state, '', 1 );
127 2 my $calls = $self->_hermes_stream_calls($state);
128 2 ▶ return unless length $text || @$calls;
Branch: 1 branch
BranchTrueFalseTotal
unless length $text or @$calls 0 2 2
Condition66%2/3
length $text or @$calls
l!l&&r!l&&!r
110
MC/DC0%0/2
length $text or @$calls
length $text @$calls
Truth table66%2/3
A or B
A= length $textB= @$calls
ABresult
1X1
011
000
129 2 require Langertha::Stream::Chunk;
130 2 ▶ return Langertha::Stream::Chunk->new( content => $text, is_final => 1,
Branch: 1 branch
BranchTrueFalseTotal
@$calls ? : 1 1 2
131 @$calls ? ( tool_calls => $calls, finish_reason => 'tool_calls' ) : () );
132 }
133 1530 ▶ return $chunk if $state->{done};
Branch: 1 branch
BranchTrueFalseTotal
if $state->{"done"} 0 1530 1530
134 1530 ▶ my $final = $chunk->is_final || length( $chunk->finish_reason // '' );
Condition60%3/5
$chunk->is_final || length($chunk->finish_reason // '')
l!l&&r!l&&!r
11701413
$chunk->finish_reason // ""
l!l
01413
MC/DC50%1/2
$chunk->is_final || length($chunk->finish_reason // '')
$chunk->is_final $chunk->finish_reason
Truth table66%2/3
A || B
A= $chunk->is_finalB= $chunk->finish_reason
ABresult
1X1
011
000
135 1530 my $text = $self->_hermes_stream_split( $state, $chunk->content, $final );
136 1530 my %set;
137 1530 ▶ $set{content} = $text if $text ne $chunk->content;
Branch: 1 branch
BranchTrueFalseTotal
if $text ne $chunk->content 1253 277 1530
138 1530 ▶ if ($final) {
Branch: 1 branch
BranchTrueFalseTotal
if ($final) 117 1413 1530
139 117 $state->{done} = 1;
140 117 my $calls = $self->_hermes_stream_calls($state);
141 117 ▶ if (@$calls) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$calls) 114 3 117
142 114 ▶ $set{tool_calls} = [ @{ $chunk->tool_calls // [] }, @$calls ];
Condition50%1/2
$chunk->tool_calls // []
l!l
0114
MC/DC0%0/1
$chunk->tool_calls // []
$chunk->tool_calls
Truth table50%1/2
A
A= $chunk->tool_calls
Aresult
11
00
143 114 my $reason = $chunk->finish_reason;
144 114 ▶ $set{finish_reason} = 'tool_calls' if !length( $reason // '' ) || $reason eq 'stop';
Branch: 1 branch
BranchTrueFalseTotal
if not length($reason // "") or $reason eq "stop" 113 1 114
Condition60%3/5
not length($reason // "") or $reason eq "stop"
l!l&&r!l&&!r
01131
$reason // ""
l!l
1140
MC/DC50%1/2
not length($reason // "") or $reason eq "stop"
$reason $reason eq "stop"
Truth table66%2/3
not(A) or B
A= $reasonB= $reason eq "stop"
ABresult
0X1
111
100
145 }
146 }
147 1530 ▶ return $chunk unless %set;
Branch: 1 branch
BranchTrueFalseTotal
unless %set 163 1367 1530
148 return if !$final && $text eq ''
149 1367 ▶ && !grep { my $has = "has_$_"; $chunk->$has } qw( thinking tool_calls usage cached_tokens citations );
Branch: 1 branch
BranchTrueFalseTotal
if not $final and $text eq "" and not grep({my $has = "has_$_"; $chunk->$has;} "thinking", "tool_calls", "usage", "cached_tokens", "citations") 1037 330 1367
Condition83%5/6
not $final and $text eq "" and not grep({my $has = "has_$_";
!ll&&!rl&&r
33001037
not $final and $text eq ""
!ll&&!rl&&r
1162141037
MC/DC66%2/3
not $final and $text eq "" and not grep({my $has = "has_$_"; $chunk->$has;} "thinking", "tool_calls", "usage", "cached_tokens", "citations")
not $final $text eq "" not grep({my $has = "has_$_"; $chunk->$has;} "thinking", "tool_calls", "usage", "cached_tokens", "citations")
Truth table75%3/4
not(A) and B and not(C)
A= not $finalB= $text eq ""C= not grep({my $has = "has_$_"; $chunk->$has;} "thinking", "tool_calls", "usage", "cached_tokens", "citations")
ABCresult
0XX0
10X0
1100
1111
150 330 return $chunk->meta->clone_object( $chunk, %set );
151 }
152  
153 # The calls of the closed blocks the stream withheld, as the Response
154 # BUILDARGS upgrade makes them of chat_f's.
155 119 ▶sub _hermes_stream_calls {
Subroutine _hermes_stream_calls: called CC=5 SCAR=16.3
156 119 my ( $self, $state ) = @_;
157 return [ map {
158 Langertha::ToolCall->new(
159 name => $_->{name},
160 arguments => ( ref $_->{arguments} eq 'HASH' ? $_->{arguments} : {} ),
161 # Carry the k345 undecodable flag through the streamed lift the same way
162 # the Response BUILDARGS upgrade does (k350): a closed block whose
163 # arguments are no object is a call with arguments {} and the flag, so the
164 # streamed tool_calls match the non-streaming reply's -- karr k351.
165 ( $_->{arguments_undecodable}
166 ? ( arguments_undecodable => 1,
167 116 ▶ ( defined $_->{arguments_error} ? ( arguments_error => $_->{arguments_error} ) : () ) )
Branch: 3 branches
BranchTrueFalseTotal
ref $_->{'arguments'} eq 'HASH' ? : 116 0 116
$_->{'arguments_undecodable'} ? : 6 110 116
defined $_->{'arguments_error'} ? : 6 0 6
168 : () ),
169 )
170 119 ▶ } @{ $state->{calls} // [] } ];
Condition100%2/2
$state->{"calls"} // []
l!l
1163
MC/DC100%1/1
$state->{"calls"} // []
$state->{"calls"}
Truth table100%2/2
A
A= $state->{"calls"}
Aresult
11
00
171 }
172  
173 # Tag-aware incremental splitter behind _hermes_stream_chunk. Appends $text to
174 # the held text and returns what may be emitted now: text outside a call block
175 # streams, a closed <tool_call>...</tool_call> is decided when it closes (its
176 # call goes to $state->{calls}; a block that is no call is emitted in place as
177 # text), and a tail that may still turn into a tag is held until the next chunk. With the
178 # think tag filter on (Role::ThinkTag), a <think> block passes through as text
179 # and a call tag inside it is no call, as chat_f strips thinking before its
180 # lift. Until a think tag is seen, a closing one is an orphan (the chat
181 # template opened the thought in the prompt): the text before it is thinking,
182 # so the calls closed before it are handed back as text, as chat_f finds none
183 # in thinking (k302). $flush releases everything held, an unclosed call block
184 # as text.
185 1532 ▶sub _hermes_stream_split {
Subroutine _hermes_stream_split: called CC=32 SCAR=34.8
186 1532 my ( $self, $state, $text, $flush ) = @_;
187 1532 my $buf = \$state->{pending};
188 1532 ▶ $$buf //= '';
Condition100%2/2
$$buf //= ""
l!l
1413119
MC/DC100%1/1
$$buf //= ""
$$buf
Truth table100%2/2
A
A= $$buf
Aresult
11
00
189 1532 ▶ $$buf .= $text // '';
Condition50%1/2
$text // ""
l!l
15320
MC/DC0%0/1
$text // ""
$text
Truth table50%1/2
A
A= $text
Aresult
11
00
190 1532 my $tag = $self->hermes_call_tag;
191 1532 ▶ my $think = $self->can('think_tag_filter') && $self->think_tag_filter ? $self->think_tag : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->can('think_tag_filter') && $self->think_tag_filter ? : 1532 0 1532
Condition33%1/3
$self->can("think_tag_filter") and $self->think_tag_filter
!ll&&!rl&&r
001532
MC/DC0%0/2
$self->can("think_tag_filter") and $self->think_tag_filter
$self->can("think_tag_filter") $self->think_tag_filter
Truth table33%1/3
A and B
A= $self->can("think_tag_filter")B= $self->think_tag_filter
ABresult
0X0
100
111
192 1532 my $out = '';
193 1532 while (1) {
194 1804 ▶ my $mode = $state->{mode} // 'text';
Condition100%2/2
$state->{"mode"} // "text"
l!l
1536268
MC/DC100%1/1
$state->{"mode"} // "text"
$state->{"mode"}
Truth table100%2/2
A
A= $state->{"mode"}
Aresult
11
00
195 1804 ▶ if ( $mode eq 'call' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "call") 1023 781 1804
196 1023 my $close = "</$tag>";
197 1023 my $at = index( $$buf, $close );
198 1023 ▶ last if $at < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $at < 0 893 130 1023
199 130 my $block = substr( $$buf, 0, $at + length $close, '' );
200 130 my ( undef, $calls ) = $self->_hermes_split_text($block);
201 130 ▶ if (@$calls) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$calls) { } 121 9 130
202 121 push @{ $state->{calls} }, @$calls;
203 114 push @{ $state->{tentative} }, [ $block, scalar @$calls ]
204 121 ▶ if defined $think && !$state->{think_seen};
Branch: 1 branch
BranchTrueFalseTotal
if defined $think and not $state->{"think_seen"} 114 7 121
Condition66%2/3
defined $think and not $state->{"think_seen"}
!ll&&!rl&&r
07114
MC/DC50%1/2
defined $think and not $state->{"think_seen"}
defined $think not $state->{"think_seen"}
Truth table66%2/3
A and not(B)
A= defined $thinkB= not $state->{"think_seen"}
ABresult
0X0
100
111
205 }
206 9 else { $out .= $block }
207 130 $state->{mode} = 'text';
208 130 next;
209 }
210 my @marks = $mode eq 'think' ? ( [ "</$think>", 'text' ] )
211 : ( [ "<$tag>", 'call' ], defined $think ? [ "<$think>", 'think' ] : (),
212 781 ▶ defined $think && !$state->{think_seen} ? [ "</$think>", 'orphan' ] : () );
Branch: 3 branches
BranchTrueFalseTotal
$mode eq 'think' ? : 102 679 781
defined $think ? : 679 0 679
defined $think && !$state->{'think_seen'} ? : 610 69 679
Condition66%2/3
defined $think and not $state->{"think_seen"}
!ll&&!rl&&r
069610
MC/DC50%1/2
defined $think and not $state->{"think_seen"}
defined $think not $state->{"think_seen"}
Truth table66%2/3
A and not(B)
A= defined $thinkB= not $state->{"think_seen"}
ABresult
0X0
100
111
213 781 my ( $at, $hit );
214 781 for my $mark (@marks) {
215 2070 my $pos = index( $$buf, $mark->[0] );
216 2070 ▶ ( $at, $hit ) = ( $pos, $mark ) if $pos >= 0 && ( !defined $at || $pos < $at );
Branch: 1 branch
BranchTrueFalseTotal
if $pos >= 0 and !defined($at) || $pos < $at 143 1927 2070
Condition100%6/6
$pos >= 0 and !defined($at) || $pos < $at
!ll&&!rl&&r
19261143
not defined $at or $pos < $at
l!l&&r!l&&!r
14211
MC/DC100%3/3
$pos >= 0 and !defined($at) || $pos < $at
$pos >= 0 not defined $at $pos < $at
Truth table100%4/4
A and not(B) or C
A= $pos >= 0B= not defined $atC= $pos < $at
ABCresult
0XX0
1000
11X1
1011
217 }
218 781 ▶ if ( $hit && $hit->[1] eq 'orphan' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hit and $hit->[1] eq "orphan") 5 776 781
Condition100%3/3
$hit and $hit->[1] eq "orphan"
!ll&&!rl&&r
6391375
MC/DC100%2/2
$hit and $hit->[1] eq "orphan"
$hit $hit->[1] eq "orphan"
Truth table100%3/3
A and B
A= $hitB= $hit->[1] eq "orphan"
ABresult
0X0
100
111
219 # Everything up to here was thinking, so its calls were none.
220 5 ▶ my @blocks = @{ delete $state->{tentative} // [] };
Condition50%1/2
delete $state->{"tentative"} // []
l!l
50
MC/DC0%0/1
delete $state->{"tentative"} // []
delete $state->{"tentative"}
Truth table50%1/2
A
A= delete $state->{"tentative"}
Aresult
11
00
221 5 my $count = 0;
222 5 $count += $_->[1] for @blocks;
223 5 splice @{ $state->{calls} }, 0, $count;
224 5 $out .= substr( $$buf, 0, $at, '' ) . join( '', map { $_->[0] } @blocks )
225 . substr( $$buf, 0, length $hit->[0], '' );
226 5 $state->{think_seen} = 1;
227 5 next;
228 }
229 776 ▶ if ($hit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hit) 137 639 776
230 137 ▶ $state->{think_seen} = 1 if $hit->[1] eq 'think';
Branch: 1 branch
BranchTrueFalseTotal
if $hit->[1] eq "think" 3 134 137
231 # A call block stays held from its opening tag on; think tags stream.
232 137 ▶ $out .= substr( $$buf, 0, $hit->[1] eq 'call' ? $at : $at + length $hit->[0], '' );
Branch: 1 branch
BranchTrueFalseTotal
$hit->[1] eq 'call' ? : 131 6 137
233 137 $state->{mode} = $hit->[1];
234 137 next;
235 }
236 639 my $keep = 0;
237 639 for my $mark ( map { $_->[0] } @marks ) {
238 1657 for my $len ( reverse 1 .. length($mark) - 1 ) {
239 11796 ▶ next if $len > length $$buf;
Branch: 1 branch
BranchTrueFalseTotal
if $len > length $$buf 7447 4349 11796
240 4349 ▶ next unless substr( $$buf, -$len ) eq substr( $mark, 0, $len );
Branch: 1 branch
BranchTrueFalseTotal
unless substr($$buf, -$len) eq substr($mark, 0, $len) 4067 282 4349
241 282 ▶ $keep = $len if $len > $keep;
Branch: 1 branch
BranchTrueFalseTotal
if $len > $keep 222 60 282
242 282 last;
243 }
244 }
245 639 $out .= substr( $$buf, 0, length($$buf) - $keep, '' );
246 639 last;
247 }
248 1532 ▶ if ($flush) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flush) 119 1413 1532
249 119 $out .= $$buf;
250 119 $$buf = '';
251 119 $state->{mode} = 'text';
252 }
253 1532 return $out;
254 }
255  
256  
257 515 ▶sub format_tools {
Subroutine format_tools: called CC=1 SCAR=0.0
Pod documented
258 515 my ( $self, $mcp_tools ) = @_;
259 515 return Langertha::Tool->format_list( $self->tool_wire_format, $mcp_tools );
260 }
261  
262  
263 41 ▶sub response_tool_calls {
Subroutine response_tool_calls: called CC=4 SCAR=13.9
Pod documented
264 41 my ( $self, $data ) = @_;
265 41 my $fmt = $self->tool_wire_format;
266 # The calls tool_loop_response would run, as raw structures -- karr k341.
267 # Hermes: the calls of chat_response's reply (native ones, else the lift),
268 # as { name, arguments }; a body it rejects falls back to the text split.
269 41 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 21 20 41
270 21 ▶ my $reply = $self->_reply_from_data($data) or return $self->_raw_tool_calls($data);
Branch: 1 branch
BranchTrueFalseTotal
my $reply = $self->_reply_from_data($data) or return $self->_raw_tool_calls($data) 17 4 21
271 17 $reply = $self->_hermes_lift($reply);
272 10 return [ map { { name => $_->name, arguments => $_->arguments } }
273 17 ▶ @{ $reply->has_tool_calls ? $reply->tool_calls : [] } ];
Branch: 1 branch
BranchTrueFalseTotal
$reply->has_tool_calls ? : 9 8 17
274 }
275 # Others: a located structure that parses to no ToolCall is no call.
276 21 return [ grep { defined Langertha::ToolCall->from_fmt( $fmt, $_ ) }
277 20 @{ Langertha::ToolCall->locate( $fmt, $data ) } ];
278 }
279  
280 # The raw calls read straight off a decoded body, without chat_response:
281 # response_tool_calls' hermes fallback, and what an engine's own
282 # chat_response uses (AKI native), which must not recurse into it.
283 16 ▶sub _raw_tool_calls {
Subroutine _raw_tool_calls: called CC=4 SCAR=14.2
284 16 my ( $self, $data ) = @_;
285 16 my $fmt = $self->tool_wire_format;
286 16 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 16 0 16
287 16 my $content = $self->hermes_extract_content($data);
288 # A call inside the thinking is not a call: split the think-filtered text,
289 # as chat_f and the stream lift do (k302) -- karr k323.
290 16 ▶ ($content) = $self->filter_think_content($content)
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("filter_think_content") 16 0 16
291 if $self->can('filter_think_content');
292 16 ▶ return [] unless $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 4 12 16
293 12 return ( $self->_hermes_split_text($content) )[1];
294 }
295 0 return Langertha::ToolCall->locate( $fmt, $data );
296 }
297  
298  
299 13 ▶sub extract_tool_call {
Subroutine extract_tool_call: called CC=3 SCAR=11.0
Pod documented
300 13 my ( $self, $tc ) = @_;
301 13 my $fmt = $self->tool_wire_format;
302 13 ▶ return ( $tc->{name}, $tc->{arguments} ) if $fmt eq 'hermes';
Branch: 1 branch
BranchTrueFalseTotal
if $fmt eq "hermes" 3 10 13
303 10 my $call = Langertha::ToolCall->from_fmt( $fmt, $tc );
304 10 ▶ return $call ? ( $call->name, $call->arguments ) : ( undef, undef );
Branch: 1 branch
BranchTrueFalseTotal
$call ? : 10 0 10
305 }
306  
307  
308 26 ▶sub response_text_content {
Subroutine response_text_content: called CC=4 SCAR=13.9
Pod documented
309 26 my ( $self, $data ) = @_;
310 # The text chat_f and the tool loops answer (Gemini thought parts out,
311 # content-chunk lists joined, think tags filtered), read by the engine's
312 # chat_response. A body chat_response rejects falls back to the plain
313 # per-format read below: plugins call this reader, it never croaks -- karr k338.
314 26 ▶ if ( my $reply = $self->_reply_from_data($data) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $reply = $self->_reply_from_data($data)) 22 4 26
315 22 ▶ my $text = $reply->content // '';
Condition50%1/2
$reply->content // ""
l!l
220
MC/DC0%0/1
$reply->content // ""
$reply->content
Truth table50%1/2
A
A= $reply->content
Aresult
11
00
316 22 ▶ $text = ( $self->_hermes_split_text($text) )[0]
Branch: 1 branch
BranchTrueFalseTotal
if $self->tool_wire_format eq "hermes" 5 17 22
317 if $self->tool_wire_format eq 'hermes';
318 22 return $text;
319 }
320 4 return $self->_raw_text_content($data);
321 }
322  
323 # The per-format text read straight off a decoded body, without
324 # chat_response: response_text_content's fallback, and what an engine's own
325 # chat_response uses (AKI native), which must not recurse into it.
326 8 ▶sub _raw_text_content {
Subroutine _raw_text_content: called CC=26 SCAR=55.0
327 8 my ( $self, $data ) = @_;
328 8 ▶ return '' unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 1 7 8
329 7 my $fmt = $self->tool_wire_format;
330 7 ▶ if ( $fmt eq 'openai' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "openai") 2 5 7
331 2 ▶ my $choice = $data->{choices}[0] or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $choice = $data->{"choices"}[0] or return "" 0 2 2
332 0 ▶ return $choice->{message}{content} // '';
Condition0%0/2
$choice->{"message"}{"content"} // ""
l!l
00
MC/DC0%0/1
$choice->{"message"}{"content"} // ""
$choice->{"message"}{"content"}
Truth table0%0/2
A
A= $choice->{"message"}{"content"}
Aresult
11
00
333 }
334 5 ▶ if ( $fmt eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "ollama") 0 5 5
335 0 ▶ my $msg = $data->{message} or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $msg = $data->{"message"} or return "" 0 0 0
336 0 ▶ return $msg->{content} // '';
Condition0%0/2
$msg->{"content"} // ""
l!l
00
MC/DC0%0/1
$msg->{"content"} // ""
$msg->{"content"}
Truth table0%0/2
A
A= $msg->{"content"}
Aresult
11
00
337 }
338 5 ▶ if ( $fmt eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "anthropic") 1 4 5
339 return join( '',
340 1 ▶ map { $_->{text} } grep { $_->{type} eq 'text' } @{ $data->{content} // [] } );
Condition50%1/2
$data->{"content"} // []
l!l
01
MC/DC0%0/1
$data->{"content"} // []
$data->{"content"}
Truth table50%1/2
A
A= $data->{"content"}
Aresult
11
00
341 }
342 4 ▶ if ( $fmt eq 'gemini' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "gemini") 0 4 4
343 0 ▶ my $candidates = $data->{candidates} || [];
Condition0%0/2
$data->{'candidates'} || []
l!l
00
MC/DC0%0/1
$data->{'candidates'} || []
$data->{'candidates'}
Truth table0%0/2
A
A= $data->{'candidates'}
Aresult
11
00
344 0 ▶ return '' unless @$candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @$candidates 0 0 0
345 0 ▶ my $parts = $candidates->[0]{content}{parts} || [];
Condition0%0/2
$candidates->[0]{'content'}{'parts'} || []
l!l
00
MC/DC0%0/1
$candidates->[0]{'content'}{'parts'} || []
$candidates->[0]{'content'}{'parts'}
Truth table0%0/2
A
A= $candidates->[0]{'content'}{'parts'}
Aresult
11
00
346 0 return join( '', map { $_->{text} } grep { exists $_->{text} } @$parts );
347 }
348 4 ▶ if ( $fmt eq 'responses' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "responses") 0 4 4
349 0 my $text = '';
350 0 ▶ for my $item ( @{ $data->{output} // [] } ) {
Condition0%0/2
$data->{"output"} // []
l!l
00
MC/DC0%0/1
$data->{"output"} // []
$data->{"output"}
Truth table0%0/2
A
A= $data->{"output"}
Aresult
11
00
351 0 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 0 0
352 0 ▶ next unless ( $item->{type} // '' ) eq 'message';
Branch: 1 branch
BranchTrueFalseTotal
unless ($item->{"type"} // "") eq "message" 0 0 0
Condition0%0/2
$item->{"type"} // ""
l!l
00
MC/DC0%0/1
$item->{"type"} // ""
$item->{"type"}
Truth table0%0/2
A
A= $item->{"type"}
Aresult
11
00
353 0 ▶ for my $block ( @{ $item->{content} // [] } ) {
Condition0%0/2
$item->{"content"} // []
l!l
00
MC/DC0%0/1
$item->{"content"} // []
$item->{"content"}
Truth table0%0/2
A
A= $item->{"content"}
Aresult
11
00
354 0 ▶ $text .= ( $block->{text} // '' ) if ( $block->{type} // '' ) eq 'output_text';
Branch: 1 branch
BranchTrueFalseTotal
if ($block->{"type"} // "") eq "output_text" 0 0 0
Condition0%0/4
$block->{"type"} // ""
l!l
00
$block->{"text"} // ""
l!l
00
MC/DC0%0/1
$block->{"type"} // ""
$block->{"type"}
MC/DC0%0/1
$block->{"text"} // ""
$block->{"text"}
Truth table0%0/2
A
A= $block->{"type"}
Aresult
11
00
Truth table0%0/2
A
A= $block->{"text"}
Aresult
11
00
355 }
356 }
357 0 return $text;
358 }
359 4 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 4 0 4
360 4 return ( $self->_hermes_split_text( $self->hermes_extract_content($data) ) )[0];
361 }
362 0 return '';
363 }
364  
365  
366 # The Response the engine's chat_response builds from a decoded body, as if
367 # the body had arrived in a 200. The engine's rate limit describes the last
368 # real response, so it is kept as it was -- karr k338.
369 197 ▶sub _chat_response_from_data {
Subroutine _chat_response_from_data: called CC=4 SCAR=13.9
370 197 my ( $self, $data ) = @_;
371 197 require HTTP::Response;
372 197 my $http = HTTP::Response->new( 200, 'OK',
373 [ 'Content-Type' => 'application/json' ], $self->json->encode($data) );
374 197 ▶ return $self->chat_response($http) unless $self->can('_last_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("_last_rate_limit") 8 189 197
375 189 my ( $had, $rate_limit ) = ( $self->_has_last_rate_limit, $self->_last_rate_limit );
376 189 my $reply;
377 189 my $ok = eval { $reply = $self->chat_response($http); 1 };
378 189 my $err = $@;
379 189 ▶ if ($had) { $self->_last_rate_limit($rate_limit) } else { $self->_clear_last_rate_limit }
Branch: 1 branch
BranchTrueFalseTotal
if ($had) { } 133 56 189
380 189 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 23 166 189
381 166 return $reply;
382 }
383  
384 # _chat_response_from_data for the readers: undef instead of a croak, when
385 # the body is no HASH or the engine cannot parse it.
386 47 ▶sub _reply_from_data {
Subroutine _reply_from_data: called CC=4 SCAR=13.9
387 47 my ( $self, $data ) = @_;
388 47 ▶ return undef unless ref $data eq 'HASH' && $self->can('chat_response');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" and $self->can("chat_response") 1 46 47
Condition66%2/3
ref $data eq "HASH" and $self->can("chat_response")
!ll&&!rl&&r
1046
MC/DC50%1/2
ref $data eq "HASH" and $self->can("chat_response")
ref $data eq "HASH" $self->can("chat_response")
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= $self->can("chat_response")
ABresult
0X0
100
111
389 46 local $@;
390 46 my $reply = eval { $self->_chat_response_from_data($data) };
391 46 ▶ return blessed $reply ? $reply : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($reply) ? : 39 7 46
392 }
393  
394 # A result's tool_call is a Langertha::ToolCall (the tool loops read
395 # Response.tool_calls, ADR 0003) or the raw wire structure response_tool_calls
396 # locates (langertha-raider). The id / name the result block pairs with, from
397 # either -- karr k321.
398 173 ▶sub _result_call_id {
Subroutine _result_call_id: called CC=6 SCAR=17.9
399 173 my ( $tc ) = @_;
400 173 ▶ return $tc->id if blessed $tc;
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($tc) 78 95 173
401 95 ▶ return $tc->{functionCall}{id} // '' if ref $tc->{functionCall} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $tc->{"functionCall"} eq "HASH" 20 75 95
Condition100%2/2
$tc->{"functionCall"}{"id"} // ""
l!l
173
MC/DC100%1/1
$tc->{"functionCall"}{"id"} // ""
$tc->{"functionCall"}{"id"}
Truth table100%2/2
A
A= $tc->{"functionCall"}{"id"}
Aresult
11
00
402 75 ▶ return $tc->{call_id} // $tc->{id} // '';
Condition100%5/5
($tc->{"call_id"} // $tc->{"id"}) // ""
l!l
678
$tc->{"call_id"} // $tc->{"id"}
l!l&&r!l&&!r
17508
MC/DC100%2/2
($tc->{"call_id"} // $tc->{"id"}) // ""
$tc->{"call_id"} $tc->{"id"}
Truth table100%3/3
A // B
A= $tc->{"call_id"}B= $tc->{"id"}
ABresult
1X1
011
000
403 }
404  
405 58 ▶sub _result_call_name {
Subroutine _result_call_name: called CC=7 SCAR=19.6
406 58 my ( $tc ) = @_;
407 58 ▶ return $tc->name if blessed $tc;
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($tc) 24 34 58
408 34 ▶ return $tc->{functionCall}{name} // '' if ref $tc->{functionCall} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $tc->{"functionCall"} eq "HASH" 20 14 34
Condition50%1/2
$tc->{"functionCall"}{"name"} // ""
l!l
200
MC/DC0%0/1
$tc->{"functionCall"}{"name"} // ""
$tc->{"functionCall"}{"name"}
Truth table50%1/2
A
A= $tc->{"functionCall"}{"name"}
Aresult
11
00
409 14 ▶ return $tc->{function}{name} // '' if ref $tc->{function} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $tc->{"function"} eq "HASH" 10 4 14
Condition50%1/2
$tc->{"function"}{"name"} // ""
l!l
100
MC/DC0%0/1
$tc->{"function"}{"name"} // ""
$tc->{"function"}{"name"}
Truth table50%1/2
A
A= $tc->{"function"}{"name"}
Aresult
11
00
410 4 ▶ return $tc->{name} // '';
Condition100%2/2
$tc->{"name"} // ""
l!l
31
MC/DC100%1/1
$tc->{"name"} // ""
$tc->{"name"}
Truth table100%2/2
A
A= $tc->{"name"}
Aresult
11
00
411 }
412  
413 # The MCP call_tool result's payload as ToolResult constructor args: content
414 # plus structuredContent, which every format falls back to when content is
415 # empty (karr k326, k336).
416 187 ▶sub _result_payload {
Subroutine _result_payload: called CC=3 SCAR=11.1
417 187 my ( $result ) = @_;
418 return (
419 content => ( $result->{content} // [] ),
420 ( defined $result->{structuredContent}
421 187 ▶ ? ( structured_content => $result->{structuredContent} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
defined $result->{'structuredContent'} ? : 3 184 187
Condition50%1/2
$result->{"content"} // []
l!l
1870
MC/DC0%0/1
$result->{"content"} // []
$result->{"content"}
Truth table50%1/2
A
A= $result->{"content"}
Aresult
11
00
422 );
423 }
424  
425 # Tool-result images ride natively (ToolResult's image_input option; the
426 # responses, gemini and anthropic wires have a form for it, karr k344, k359)
427 # only when the selected model sees images (image_input, ADR 0019) and the
428 # wire takes them for that model (_tool_result_images_on_wire). The tool loop
429 # sends what an MCP server returned, not what the caller chose, so a model that
430 # makes no claim keeps the k336 placeholder.
431 59 ▶sub _tool_result_images_on_wire { 1 }
Subroutine _tool_result_images_on_wire: called CC=1 SCAR=0.0
432  
433 94 ▶sub _tool_result_image_opts {
Subroutine _tool_result_image_opts: called CC=4 SCAR=13.9
434 94 my ( $self ) = @_;
435 94 ▶ return () unless $self->_tool_result_images_on_wire
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_tool_result_images_on_wire and $self->can("supports") and $self->supports("image_input") 43 51 94
Condition83%5/6
$self->_tool_result_images_on_wire and $self->can("supports") and $self->supports("image_input")
!ll&&!rl&&r
232051
$self->_tool_result_images_on_wire and $self->can("supports")
!ll&&!rl&&r
23071
MC/DC66%2/3
$self->_tool_result_images_on_wire and $self->can("supports") and $self->supports("image_input")
$self->_tool_result_images_on_wire $self->can("supports") $self->supports("image_input")
Truth table75%3/4
A and B and C
A= $self->_tool_result_images_on_wireB= $self->can("supports")C= $self->supports("image_input")
ABCresult
0XX0
10X0
1100
1111
436 && $self->can('supports') && $self->supports('image_input');
437 51 return ( image_input => 1 );
438 }
439  
440 # Tool-result PDFs ride natively (ToolResult's native_pdf option, karr k361)
441 # only where the wire documents a PDF inside a tool result for the selected
442 # model (_tool_result_pdf_on_wire: OpenAIResponses' input_file, Gemini 3's
443 # functionResponse.parts) and the model claims image_input: both providers
444 # document PDF understanding as a vision feature (OpenAI parses page text and
445 # page images and names vision models; Gemini reads documents through its
446 # vision), so a text-only model keeps the k336 placeholder rather than risk a
447 # 400 mid-loop. Off by default: every other wire (openai, ollama, hermes,
448 # Perplexity's Agent API, older Gemini) has no documented form. The anthropic
449 # wire's PDF document block is decided by _tool_result_source_blocks_on_wire
450 # (k326, k364) and does not read this, nor image_input (k371): the Anthropic
451 # dialect extracts PDF text without vision (MiniMax-M2.7, text-only, read one
452 # live 2026-09-30), so the block is a wire fact, not a model question.
453 0 ▶sub _tool_result_pdf_on_wire { 0 }
Subroutine _tool_result_pdf_on_wire: not called CC=1 SCAR=6.9
454  
455 49 ▶sub _tool_result_pdf_opts {
Subroutine _tool_result_pdf_opts: called CC=4 SCAR=13.9
456 49 my ( $self ) = @_;
457 49 ▶ return () unless $self->_tool_result_pdf_on_wire
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_tool_result_pdf_on_wire and $self->can("supports") and $self->supports("image_input") 29 20 49
Condition83%5/6
$self->_tool_result_pdf_on_wire and $self->can("supports") and $self->supports("image_input")
!ll&&!rl&&r
25420
$self->_tool_result_pdf_on_wire and $self->can("supports")
!ll&&!rl&&r
25024
MC/DC66%2/3
$self->_tool_result_pdf_on_wire and $self->can("supports") and $self->supports("image_input")
$self->_tool_result_pdf_on_wire $self->can("supports") $self->supports("image_input")
Truth table75%3/4
A and B and C
A= $self->_tool_result_pdf_on_wireB= $self->can("supports")C= $self->supports("image_input")
ABCresult
0XX0
10X0
1100
1111
458 && $self->can('supports') && $self->supports('image_input');
459 20 return ( native_pdf => 1 );
460 }
461  
462 # Whether the anthropic wire takes Anthropic's source blocks (document,
463 # search_result) inside a tool_result (karr k364, k366). First-party Anthropic
464 # documents them; a /anthropic shim that rejects them sets this to 0, and
465 # ToolResult then sends a text document as a text block, a PDF as the k336
466 # placeholder and a native document / search_result as its text. Wire truth,
467 # not a model question, so it is a private predicate and not a capability flag.
468 19 ▶sub _tool_result_source_blocks_on_wire { 1 }
Subroutine _tool_result_source_blocks_on_wire: called CC=1 SCAR=0.0
469  
470 # A native document / search_result is the caller's choice for the Anthropic
471 # wire, so turning it into text is worth one warning per engine instance (the
472 # ADR 0035 once-key pattern). An MCP resource becoming text is the normal path
473 # on these shims and stays quiet.
474 20 ▶sub _carp_degraded_source_blocks {
Subroutine _carp_degraded_source_blocks: called CC=3 SCAR=11.0
475 20 my ( $self, $result ) = @_;
476 20 ▶ my @types = $result->_native_source_block_types or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@types) = $result->_native_source_block_types or return 7 13 20
477 7 ▶ return unless $self->can('_langertha_carp');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("_langertha_carp") 0 7 7
478 7 $self->_langertha_carp( "".( ref $self ).": sending " . join( ' / ', @types )
479 . " blocks in a tool result as text -- this endpoint takes no document or"
480 . " search_result block inside a tool_result", 'tool_result_source_blocks' );
481 7 return;
482 }
483  
484 152 ▶sub format_tool_results {
Subroutine format_tool_results: called CC=22 SCAR=31.0
Pod documented
485 152 my ( $self, $data, $results ) = @_;
486 152 my $fmt = $self->tool_wire_format;
487  
488 152 ▶ if ( $fmt eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "anthropic") 45 107 152
489 45 my $source_blocks = $self->_tool_result_source_blocks_on_wire;
490 45 ▶ my @opts = ( $self->_tool_result_image_opts,
Branch: 1 branch
BranchTrueFalseTotal
$source_blocks ? : 25 20 45
491 ( $source_blocks ? () : ( source_blocks => 0 ) ) );
492 my @blocks = map {
493 45 my $result = Langertha::ToolResult->new(
494 id => _result_call_id( $_->{tool_call} ),
495 _result_payload( $_->{result} ),
496 52 ▶ is_error => ( $_->{result}{isError} ? 1 : 0 ),
Branch: 1 branch
BranchTrueFalseTotal
$_->{'result'}{'isError'} ? : 7 45 52
497 );
498 52 ▶ $self->_carp_degraded_source_blocks($result) unless $source_blocks;
Branch: 1 branch
BranchTrueFalseTotal
unless $source_blocks 20 32 52
499 52 $result->to( 'anthropic', @opts );
500 } @$results;
501 return (
502 { role => 'assistant', content => $data->{content} },
503 45 { role => 'user', content => \@blocks },
504 );
505 }
506  
507 107 ▶ if ( $fmt eq 'gemini' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "gemini") 26 81 107
508 26 my @opts = ( $self->_tool_result_image_opts, $self->_tool_result_pdf_opts );
509 my @parts = map {
510 26 Langertha::ToolResult->new(
511 name => _result_call_name( $_->{tool_call} ),
512 id => _result_call_id( $_->{tool_call} ),
513 29 _result_payload( $_->{result} ),
514 )->to( 'gemini', @opts )
515 } @$results;
516 26 my $candidate = $data->{candidates}[0];
517 return (
518 { role => 'model', parts => $candidate->{content}{parts} },
519 26 { role => 'user', parts => \@parts },
520 );
521 }
522  
523 81 ▶ if ( $fmt eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "ollama") 11 70 81
524 11 my $msg = $data->{message};
525 my %echo = (
526 role => 'assistant',
527 content => $msg->{content},
528 tool_calls => $msg->{tool_calls},
529 11 );
530 # Ollama returns the chain-of-thought in message.thinking; echo it back for
531 # the same reason the openai branch below echoes reasoning_content
532 # (karr k136).
533 11 ▶ $echo{thinking} = $msg->{thinking} if defined $msg->{thinking};
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg->{"thinking"} 1 10 11
534 return (
535 \%echo,
536 map {
537 11 Langertha::ToolResult->new(
538 name => _result_call_name( $_->{tool_call} ),
539 id => _result_call_id( $_->{tool_call} ),
540 15 _result_payload( $_->{result} ),
541 )->to('ollama')
542 } @$results,
543 );
544 }
545  
546 70 ▶ if ( $fmt eq 'responses' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "responses") 23 47 70
547 # The Responses API takes one flat item list: the model's own output items
548 # echoed back, then one function_call_output per result. It only accepts a
549 # function_call_output whose call_id was announced by a *top-level*
550 # function_call item, so hoist any call out of the legacy
551 # nested-inside-a-message shape that ToolCall->locate('responses') also
552 # walks. Returns a LIST like every other branch — every caller does
553 # `push @$conversation, $engine->format_tool_results(...)` (karr #85).
554 23 my @echo;
555 23 ▶ for my $item ( @{ $data->{output} // [] } ) {
Condition50%1/2
$data->{"output"} // []
l!l
230
MC/DC0%0/1
$data->{"output"} // []
$data->{"output"}
Truth table50%1/2
A
A= $data->{"output"}
Aresult
11
00
556 40 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 40 40
557 40 ▶ if ( ( $item->{type} // '' ) eq 'message' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($item->{"type"} // "") eq "message") 6 34 40
Condition50%1/2
$item->{"type"} // ""
l!l
400
MC/DC0%0/1
$item->{"type"} // ""
$item->{"type"}
Truth table50%1/2
A
A= $item->{"type"}
Aresult
11
00
558 6 ▶ my @content = grep { ref($_) eq 'HASH' } @{ $item->{content} // [] };
Condition50%1/2
$item->{"content"} // []
l!l
60
MC/DC0%0/1
$item->{"content"} // []
$item->{"content"}
Truth table50%1/2
A
A= $item->{"content"}
Aresult
11
00
559 6 ▶ my @calls = grep { ( $_->{type} // '' ) eq 'function_call' } @content;
Condition50%1/2
$_->{"type"} // ""
l!l
60
MC/DC0%0/1
$_->{"type"} // ""
$_->{"type"}
Truth table50%1/2
A
A= $_->{"type"}
Aresult
11
00
560 6 ▶ my @rest = grep { ( $_->{type} // '' ) ne 'function_call' } @content;
Condition50%1/2
$_->{"type"} // ""
l!l
60
MC/DC0%0/1
$_->{"type"} // ""
$_->{"type"}
Truth table50%1/2
A
A= $_->{"type"}
Aresult
11
00
561 6 ▶ push @echo, { %$item, content => \@rest } if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 4 2 6
562 6 push @echo, @calls;
563 6 next;
564 }
565 34 push @echo, $item;
566 }
567 # Which echoed items the wire takes back as input is the envelope's call:
568 # the ResponsesCompatible hook passes all through on OpenAI and filters to
569 # the Agent input schema on Perplexity (karr k213, ADR 0020).
570 23 ▶ @echo = map { $self->_responses_echo_item($_) } @echo
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_responses_echo_item") 23 0 23
571 if $self->can('_responses_echo_item');
572 23 my @opts = ( $self->_tool_result_image_opts, $self->_tool_result_pdf_opts );
573 return (
574 @echo,
575 map {
576 23 Langertha::ToolResult->new(
577 id => _result_call_id( $_->{tool_call} ),
578 23 _result_payload( $_->{result} ),
579 )->to( 'responses', @opts )
580 } @$results,
581 );
582 }
583  
584 47 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 11 36 47
585 11 my $content = $self->hermes_extract_content($data);
586 11 my $res_tag = $self->hermes_response_tag;
587 return (
588 { role => 'assistant', content => $content },
589 map {
590 11 { role => 'tool',
591 content => Langertha::ToolResult->new(
592 name => _result_call_name( $_->{tool_call} ),
593 14 _result_payload( $_->{result} ),
594 )->to( 'hermes', response_tag => $res_tag ) }
595 } @$results,
596 );
597 }
598  
599 # openai (default)
600 36 my $msg = $data->{choices}[0]{message};
601 my %echo = (
602 role => 'assistant',
603 content => $msg->{content},
604 tool_calls => $msg->{tool_calls},
605 36 );
606 # Carry the provider's reasoning fields back into the assistant echo.
607 # DeepSeek returns HTTP 400 on the next iteration of a tool loop when
608 # reasoning_content is not sent back while tools are present; Moonshot
609 # (kimi) requires the same within one tool-call loop, OpenRouter requires
610 # reasoning_details to round-trip unmodified, Mistral loses output quality
611 # and xAI misses the prompt cache without it. Deliberately an allowlist and
612 # not the whole message: some OpenAI-compatible servers reject unknown keys
613 # on an inbound assistant message (karr k136).
614 36 for my $key (qw( reasoning_content reasoning reasoning_details )) {
615 108 ▶ $echo{$key} = $msg->{$key} if defined $msg->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg->{$key} 5 103 108
616 }
617 return (
618 \%echo,
619 map {
620 36 Langertha::ToolResult->new(
621 id => _result_call_id( $_->{tool_call} ),
622 54 _result_payload( $_->{result} ),
623 )->to('openai')
624 } @$results,
625 );
626 }
627  
628  
629 # One tool-loop turn's reply, read by the parser chat_f uses: chat_response
630 # croaks on an error-in-body 200 exactly as chat_f does (k301/k311/k317) and
631 # yields the same final text (Gemini thought parts out, content-chunk arrays
632 # joined, think tags filtered) -- karr k321, k322. The calls to run are
633 # Response.tool_calls (ADR 0003); hermes calls ride in the text and are lifted
634 # as chat_f lifts them, unless the engine's chat_response already did (AKI
635 # native). ->raw stays the wire body the assistant echo is built from.
636 # Shared by chat_with_tools_f and both Langertha::Chat tool loops.
637 # Public since k341 (ADR 0028): langertha-raider's loop reads its replies here
638 # instead of the raw body. Takes the HTTP::Response or the decoded body.
639 209 ▶sub tool_loop_response {
Subroutine tool_loop_response: called CC=4 SCAR=13.9
Pod documented
640 209 my ( $self, $reply ) = @_;
641 209 ▶ my $response = blessed $reply && $reply->isa('HTTP::Response')
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($reply) && $reply->isa('HTTP::Response') ? : 58 151 209
Condition66%2/3
builtin::blessed($reply) and $reply->isa("HTTP::Response")
!ll&&!rl&&r
151058
MC/DC50%1/2
builtin::blessed($reply) and $reply->isa("HTTP::Response")
builtin::blessed($reply) $reply->isa("HTTP::Response")
Truth table66%2/3
A and B
A= builtin::blessed($reply)B= $reply->isa("HTTP::Response")
ABresult
0X0
100
111
642 ? $self->chat_response($reply)
643 : $self->_chat_response_from_data($reply);
644 # A blocked prompt is an answer to chat_f (k301) but ends a tool loop, whose
645 # result is only text: '' would hide why -- karr k339.
646 186 my $blocked = $self->_tool_loop_block_reason($response);
647 186 ▶ croak "" . ( ref $self ) . " prompt blocked: $blocked" if defined $blocked;
Branch: 1 branch
BranchTrueFalseTotal
if defined $blocked 7 179 186
648 179 return $self->_hermes_lift($response);
649 }
650  
651 57 ▶sub _tool_loop_response { shift->tool_loop_response(@_) }
Subroutine _tool_loop_response: called CC=1 SCAR=0.0
652  
653  
654 # The hermes calls ride in the text: lifted as chat_f lifts them, unless the
655 # engine's chat_response already did (AKI native).
656 196 ▶sub _hermes_lift {
Subroutine _hermes_lift: called CC=5 SCAR=16.1
657 196 my ( $self, $response ) = @_;
658 return $response unless $self->tool_wire_format eq 'hermes'
659 196 ▶ && !( $response->has_tool_calls && @{ $response->tool_calls } );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->tool_wire_format eq "hermes" and not $response->has_tool_calls && @{$response->tool_calls;} 153 43 196
Condition83%5/6
$self->tool_wire_format eq "hermes" and not $response->has_tool_calls && @{$response->tool_calls;}
!ll&&!rl&&r
151243
$response->has_tool_calls && @{$response->tool_calls;}
!ll&&!rl&&r
4302
MC/DC66%2/3
$self->tool_wire_format eq "hermes" and not $response->has_tool_calls && @{$response->tool_calls;}
$self->tool_wire_format eq "hermes" $response->has_tool_calls @{$response->tool_calls;}
Truth table75%3/4
A and not(B && C)
A= $self->tool_wire_format eq "hermes"B= $response->has_tool_callsC= @{$response->tool_calls;}
ABCresult
0XX0
1110
10X1
1101
660 43 my ( $clean, $calls ) = $self->_hermes_split_text( $response->content );
661 43 ▶ return @$calls ? $response->clone_with( content => $clean, tool_calls => $calls ) : $response;
Branch: 1 branch
BranchTrueFalseTotal
@$calls ? : 18 25 43
662 }
663  
664 # Why the provider refused the prompt itself, when a reply says so (Gemini's
665 # promptFeedback.blockReason); undef otherwise. Engines whose wire reports a
666 # blocked prompt override it -- karr k339.
667 156 ▶sub _tool_loop_block_reason { return }
Subroutine _tool_loop_block_reason: called CC=1 SCAR=0.0
668  
669 # The finish reasons that mean "the reply hit its token limit", as each wire
670 # spells it: OpenAI-compatible and Ollama 'length', Anthropic 'max_tokens',
671 # Gemini 'MAX_TOKENS', an incomplete Responses message 'incomplete'.
672 182 my %TOKEN_LIMIT_FINISH = map { $_ => 1 } qw( length max_tokens MAX_TOKENS incomplete );
673  
674 # The calls one tool-loop turn runs, and the wire body its assistant echo is
675 # built from. A reply cut off by its token limit can carry a call whose
676 # arguments string was cut too; it decodes to nothing, and running the tool on
677 # {} is wrong, so that call is dropped, as the stream parser drops an
678 # unfinished call. With no call left the loop croaks; otherwise the complete
679 # calls run, a carp names the dropped ones, and the echo leaves them out, so
680 # the next turn has no call without a result -- karr k324.
681 166 ▶sub tool_loop_calls {
Subroutine tool_loop_calls: called CC=8 SCAR=20.8
Pod documented
682 166 my ( $self, $reply, $data ) = @_;
683 166 ▶ $data //= $reply->raw;
Condition66%2/3
$data //= $reply->raw
l!l&&r!l&&!r
16420
MC/DC0%0/2
$data //= $reply->raw
$data $reply->raw
Truth table66%2/3
A //= B
A= $dataB= $reply->raw
ABresult
1X1
011
000
684 166 ▶ my @calls = $reply->has_tool_calls ? @{ $reply->tool_calls } : ();
Branch: 1 branch
BranchTrueFalseTotal
$reply->has_tool_calls ? : 82 84 166
685 166 my $reason = $reply->finish_reason;
686 return ( \@calls, $data )
687 166 ▶ unless @calls && defined $reason && $TOKEN_LIMIT_FINISH{$reason};
Branch: 1 branch
BranchTrueFalseTotal
unless @calls and defined $reason and $TOKEN_LIMIT_FINISH{$reason} 143 23 166
Condition100%6/6
@calls and defined $reason and $TOKEN_LIMIT_FINISH{$reason}
!ll&&!rl&&r
944923
@calls and defined $reason
!ll&&!rl&&r
88672
MC/DC100%3/3
@calls and defined $reason and $TOKEN_LIMIT_FINISH{$reason}
@calls defined $reason $TOKEN_LIMIT_FINISH{$reason}
Truth table100%4/4
A and B and C
A= @callsB= defined $reasonC= $TOKEN_LIMIT_FINISH{$reason}
ABCresult
0XX0
10X0
1100
1111
688 23 my @dropped = grep { $_->arguments_undecodable } @calls;
689 23 ▶ return ( \@calls, $data ) unless @dropped;
Branch: 1 branch
BranchTrueFalseTotal
unless @dropped 3 20 23
690 20 my $class = ref $self;
691 20 ▶ croak "$class tool call arguments truncated (finish_reason $reason); raise response_size"
Branch: 1 branch
BranchTrueFalseTotal
if @dropped == @calls 16 4 20
692 if @dropped == @calls;
693 $self->_langertha_carp( "$class: dropped " . scalar(@dropped)
694 . " tool call(s) with truncated arguments (finish_reason $reason): "
695 4 . join( ', ', map { $_->name } @dropped ) . "; raise response_size" );
696 4 return ( [ grep { !$_->arguments_undecodable } @calls ],
697 $self->_echo_without_undecodable_calls($data) );
698 }
699  
700 47 ▶sub _tool_loop_calls { shift->tool_loop_calls(@_) }
Subroutine _tool_loop_calls: called CC=1 SCAR=0.0
701  
702  
703 # A copy of the wire body without the raw calls whose arguments do not
704 # decode; everything else is shared. Hermes calls ride in the text, and an
705 # unfinished <tool_call> block never became a call.
706 4 ▶sub _echo_without_undecodable_calls {
Subroutine _echo_without_undecodable_calls: called CC=5 SCAR=16.2
707 4 my ( $self, $data ) = @_;
708 4 my $fmt = $self->tool_wire_format;
709 4 ▶ return $data if $fmt eq 'hermes';
Branch: 1 branch
BranchTrueFalseTotal
if $fmt eq "hermes" 0 4 4
710 4 my %drop;
711 4 for my $raw ( @{ Langertha::ToolCall->locate( $fmt, $data ) } ) {
712 8 my $call = Langertha::ToolCall->from_fmt( $fmt, $raw );
713 8 ▶ $drop{ refaddr $raw } = 1 if $call && $call->arguments_undecodable;
Branch: 1 branch
BranchTrueFalseTotal
if $call and $call->arguments_undecodable 4 4 8
Condition66%2/3
$call and $call->arguments_undecodable
!ll&&!rl&&r
044
MC/DC50%1/2
$call and $call->arguments_undecodable
$call $call->arguments_undecodable
Truth table66%2/3
A and B
A= $callB= $call->arguments_undecodable
ABresult
0X0
100
111
714 }
715 4 return _without_refs( $data, \%drop );
716 }
717  
718 64 ▶sub _without_refs {
Subroutine _without_refs: called CC=4 SCAR=13.9
719 64 my ( $node, $drop ) = @_;
720 64 ▶ return { map { $_ => _without_refs( $node->{$_}, $drop ) } keys %$node }
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "HASH" 20 44 64
721 if ref $node eq 'HASH';
722 8 return [ map { _without_refs( $_, $drop ) }
723 44 ▶ grep { !( ref $_ && $drop->{ refaddr $_ } ) } @$node ]
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "ARRAY" 8 36 44
Condition66%2/3
ref $_ && $$drop{builtin::refaddr($_)}
!ll&&!rl&&r
084
MC/DC50%1/2
ref $_ && $$drop{builtin::refaddr($_)}
ref $_ $$drop{builtin::refaddr($_)}
Truth table66%2/3
A && B
A= ref $_B= $$drop{builtin::refaddr($_)}
ABresult
0X0
100
111
724 if ref $node eq 'ARRAY';
725 36 return $node;
726 }
727  
728 # The tool list a tool loop sends and the server each name runs on, from
729 # ( [ $mcp, \@tools ], ... ) in mcp_servers order. A name two servers offer is
730 # sent once -- providers reject a request that declares one function twice --
731 # and runs on the first server; a carp names both -- karr k332.
732 134 ▶sub _tool_loop_tools {
Subroutine _tool_loop_tools: called CC=5 SCAR=16.1
733 134 my ( $self, @server_tools ) = @_;
734 134 my ( @all_tools, %tool_server_map, %server_no );
735 134 ▶ my $label = sub { "MCP server $server_no{ refaddr $_[0] } (" . ref( $_[0] ) . ")" };
Subroutine __ANON__: called CC=1 SCAR=0.0
736 134 my $no = 0;
737 134 for my $pair (@server_tools) {
738 137 my ( $mcp, $tools ) = @$pair;
739 137 ▶ $server_no{ refaddr $mcp } //= ++$no;
Condition33%1/3
$server_no{builtin::refaddr($mcp)} //= ++$no
l!l&&r!l&&!r
01370
MC/DC0%0/2
$server_no{builtin::refaddr($mcp)} //= ++$no
$server_no{builtin::refaddr($mcp)} ++$no
Truth table33%1/3
A //= B
A= $server_no{builtin::refaddr($mcp)}B= ++$no
ABresult
1X1
011
000
740 137 for my $tool (@$tools) {
741 141 my $name = $tool->{name};
742 141 ▶ if ( my $first = $tool_server_map{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $first = $tool_server_map{$name}) 3 138 141
743 3 $self->_langertha_carp( "" . ( ref $self ) . ": tool '$name' is offered by "
744 . $label->($first) . " and " . $label->($mcp) . "; using the first" );
745 3 next;
746 }
747 138 $tool_server_map{$name} = $mcp;
748 138 push @all_tools, $tool;
749 }
750 }
751 134 return ( \@all_tools, \%tool_server_map );
752 }
753  
754 # The result a tool loop answers a call to a tool no server offers: an error
755 # the model can recover from, not a die that loses the batch -- karr k332.
756 8 ▶sub _unknown_tool_result {
Subroutine _unknown_tool_result: called CC=2 SCAR=7.2
757 8 my ( $name ) = @_;
758 return {
759 8 ▶ content => [ { type => 'text', text => "unknown tool " . ( $name // '' ) } ],
Condition50%1/2
$name // ""
l!l
80
MC/DC0%0/1
$name // ""
$name
Truth table50%1/2
A
A= $name
Aresult
11
00
760 isError => JSON->true,
761 };
762 }
763  
764 # The result a tool loop answers a call whose arguments do not decode, or
765 # undef for a call whose arguments did. A call cut off by the token limit was
766 # already dropped by _tool_loop_calls; any other one would run the tool on {},
767 # so the model gets an error it can retry instead -- karr k345.
768 86 ▶sub _undecodable_arguments_result {
Subroutine _undecodable_arguments_result: called CC=3 SCAR=11.1
769 86 my ( $tc ) = @_;
770 86 ▶ return undef unless $tc->arguments_undecodable;
Branch: 1 branch
BranchTrueFalseTotal
unless $tc->arguments_undecodable 77 9 86
771 return {
772 9 ▶ content => [ { type => 'text',
Condition50%1/2
$tc->arguments_error // "not a JSON object"
l!l
90
MC/DC0%0/1
$tc->arguments_error // "not a JSON object"
$tc->arguments_error
Truth table50%1/2
A
A= $tc->arguments_error
Aresult
11
00
773 text => "arguments are not valid JSON: " . ( $tc->arguments_error // 'not a JSON object' ) } ],
774 isError => JSON->true,
775 };
776 }
777  
778 41 ▶async sub chat_with_tools_f {
Subroutine chat_with_tools_f: called CC=10 SCAR=23.1
Pod documented
779 41 my ( $self, @messages ) = @_;
780  
781 41 ▶ croak "No MCP servers configured" unless @{$self->mcp_servers};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->mcp_servers;} 0 41 41
782  
783 # Gather tools from all MCP servers
784 41 my @server_tools;
785 41 for my $mcp (@{$self->mcp_servers}) {
786 42 push @server_tools, [ $mcp, await $mcp->list_tools ];
787 }
788 41 my ( $all_tools, $tool_server_map ) = $self->_tool_loop_tools(@server_tools);
789 41 my @all_tools = @$all_tools;
790  
791 41 my $formatted_tools = $self->format_tools(\@all_tools);
792 # URL images this engine inlines: fetched async, not by LWP in the loop (k274).
793 41 @messages = await $self->_prefetch_inline_images_f(@messages);
794 41 my $conversation = $self->chat_messages(@messages);
795  
796 $log->debugf("[%s] chat_with_tools_f: %d tools from %d MCP servers, max_iterations=%d",
797 41 ref $self, scalar @all_tools, scalar @{$self->mcp_servers}, $self->tool_max_iterations);
798  
799 41 for my $iteration (1..$self->tool_max_iterations) {
800 58 $log->debugf("[%s] Tool loop iteration %d/%d",
801 ref $self, $iteration, $self->tool_max_iterations);
802  
803 58 my $request = $self->build_tool_chat_request($conversation, $formatted_tools);
804 58 my $response = await $self->_async_do_request_f(request => $request);
805  
806 # A failed response records its rate limit before the die, as in chat_f
807 # (karr k300); a success does it in parse_response.
808 58 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 2 56 58
809 2 ▶ $self->_update_rate_limit($response) if $self->can('_update_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_update_rate_limit") 2 0 2
810 2 die $self->_request_failed_message( $response, 'tool chat request' );
811 }
812  
813 56 my $reply = $self->_tool_loop_response($response);
814 47 my ( $calls, $data ) = $self->_tool_loop_calls( $reply, $reply->raw );
815 42 my @tool_calls = @$calls;
816  
817 # No tool calls means the LLM is done — return final text
818 42 ▶ return $reply->content unless @tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless @tool_calls 25 17 42
819  
820 # Execute each tool call via the appropriate MCP server
821 17 my @results;
822 17 for my $tc (@tool_calls) {
823 23 my ( $name, $input ) = ( $tc->name, $tc->arguments );
824  
825 # A name no server offers is answered with an error result, so the
826 # batch runs to the end and the model can correct itself (k332).
827 23 my $mcp = $tool_server_map->{$name};
828 23 ▶ unless ($mcp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($mcp) 2 21 23
829 2 push @results, { tool_call => $tc, result => _unknown_tool_result($name) };
830 2 next;
831 }
832 21 ▶ if ( my $bad = _undecodable_arguments_result($tc) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bad = _undecodable_arguments_result($tc)) 3 18 21
833 3 push @results, { tool_call => $tc, result => $bad };
834 3 next;
835 }
836  
837 18 $log->debugf("[%s] Calling tool: %s", ref $self, $name);
838  
839 0 ▶ my $result = await $mcp->call_tool($name, $input)->else(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
840 0 my ( $error ) = @_;
841 0 Future->done({
842 content => [{ type => 'text', text => "Error calling tool '$name': $error" }],
843 isError => JSON->true,
844 });
845 18 });
846  
847 18 push @results, { tool_call => $tc, result => $result };
848 }
849  
850 # Append assistant message and tool results to conversation
851 17 push @$conversation, $self->format_tool_results($data, \@results);
852 }
853  
854 0 die "Tool calling loop exceeded ".$self->tool_max_iterations." iterations";
855 182 }
856  
857  
858  
859 182 1;
860  
861 __END__
862  
863 =pod
864  
865 =encoding UTF-8
866  
867 =head1 NAME
868  
869 Langertha::Role::Tools - Role for MCP tool calling support
870  
871 =head1 VERSION
872  
873 version 0.503
874  
875 =head1 SYNOPSIS
876  
877 use IO::Async::Loop;
878 use Future::AsyncAwait;
879  
880 my $loop = IO::Async::Loop->new;
881  
882 # Set up any Net::Async::MCP-compatible client (langertha-raider uses
883 # Net::Async::MCP directly)
884 my $mcp = SomeMCPClient->new(server => $my_mcp_server);
885 $loop->add($mcp);
886 await $mcp->initialize;
887  
888 # Create engine with MCP servers (native tool calling)
889 my $engine = Langertha::Engine::Anthropic->new(
890 api_key => $ENV{ANTHROPIC_API_KEY},
891 model => 'claude-sonnet-4-6',
892 mcp_servers => [$mcp],
893 );
894  
895 my $response = await $engine->chat_with_tools_f(
896 'Use the available tools to answer my question'
897 );
898  
899 # Hermes tool calling (for APIs without native tool support)
900 my $engine = Langertha::Engine::AKI->new(
901 api_key => $ENV{AKI_API_KEY},
902 mcp_servers => [$mcp],
903 );
904  
905 =head1 DESCRIPTION
906  
907 This role adds MCP (Model Context Protocol) tool calling support to Langertha
908 engines. It provides the L</chat_with_tools_f> method which implements the full
909 async tool-calling loop:
910  
911 =over 4
912  
913 =item 1. Gather available tools from all configured MCP servers
914  
915 =item 2. Send a chat request with tool definitions to the LLM
916  
917 =item 3. If the LLM returns tool calls, execute them via MCP
918  
919 =item 4. Feed tool results back to the LLM and repeat
920  
921 =item 5. When the LLM returns final text, return it
922  
923 =back
924  
925 All tool wire-translation is tag-driven: an engine declares its dialect via
926 L</tool_wire_format> (C<openai> | C<anthropic> | C<gemini> | C<ollama> |
927 C<responses> | C<hermes>) and the default implementations of C<format_tools>,
928 C<response_tool_calls>, C<extract_tool_call>, C<format_tool_results>, and
929 C<response_text_content> delegate to the L<Langertha::Tool>,
930 L<Langertha::ToolCall>, and L<Langertha::ToolResult> value objects keyed by that
931 tag. Engines carry no per-format tool code. The C<hermes> dialect injects tools
932 into the system prompt and parses C<E<lt>tool_callE<gt>> XML; its tag names and
933 prompt template come from L<Langertha::Role::HermesTools>.
934  
935 =head2 mcp_servers
936  
937 mcp_servers => [$mcp1, $mcp2]
938  
939 ArrayRef of MCP client objects to use as tool providers — any
940 L<Net::Async::MCP>-compatible client (for example a L<Net::Async::MCP> client
941 as used by the langertha-raider distribution). Each entry must respond to
942 C<list_tools> and C<call_tool>. Defaults to an empty ArrayRef. At least one
943 server must be configured before calling L</chat_with_tools_f>.
944  
945 =head2 tool_max_iterations
946  
947 tool_max_iterations => 20
948  
949 Maximum number of tool-calling round trips before aborting with an error.
950 Defaults to C<10>. Increase for complex multi-step tool workflows.
951  
952 =head2 tool_wire_format
953  
954 tool_wire_format => 'anthropic'
955  
956 The single per-engine enum naming which tool dialect this engine speaks —
957 C<openai> | C<anthropic> | C<gemini> | C<ollama> | C<responses> | C<hermes>.
958 This one tag drives all tool wire-translation: the outbound tool definitions
959 (L<Langertha::Tool>), the inbound tool calls (L<Langertha::ToolCall>), the
960 result blocks (L<Langertha::ToolResult>), the final-text extraction, and the
961 outbound transport (native API parameter vs. Hermes prompt injection).
962  
963 The default follows the engine base-class hierarchy: C<OpenAIBase> leaves it at
964 C<openai>, C<AnthropicBase> overrides to C<anthropic>, and so on — so the ~25
965 concrete engines inherit it and carry no tool-format code of their own. Override
966 C<_build_tool_wire_format> to change it.
967  
968 =head2 build_tool_chat_request
969  
970 my $request = $self->build_tool_chat_request($conversation, $formatted_tools);
971  
972 Builds an HTTP request for a tool-calling chat turn. For native wire formats the
973 tools are passed as an API parameter via C<chat_request>; for the C<hermes>
974 format they are injected into the system prompt as XML.
975  
976 =head2 format_tools
977  
978 my $tools = $engine->format_tools($mcp_tools);
979  
980 Converts an ArrayRef of MCP tool definitions to the wire C<tools> payload for
981 this engine's L</tool_wire_format> via L<Langertha::Tool/format_list>.
982  
983 =head2 response_tool_calls
984  
985 my $tool_calls = $engine->response_tool_calls($raw_data);
986  
987 Returns the ArrayRef of raw tool-call structures in C<$raw_data>: the calls
988 L</tool_loop_response> puts on L<Langertha::Response/tool_calls> for the same
989 body, in the same order, as this engine's format spells them. Located via
990 L<Langertha::ToolCall/locate>; a structure that parses to no call (no name) is
991 left out. For C<hermes>, each call is C<< { name, arguments } >>: the
992 C<E<lt>tool_callE<gt>> XML tags parsed out of the model's text (with
993 C<think_tag_filter> on, a call inside the thinking is not returned), or the
994 native calls the engine's parser found. May be empty. Calls cut off by the
995 token limit are still returned; L</tool_loop_calls> drops them.
996  
997 =head2 extract_tool_call
998  
999 my ($name, $args) = $engine->extract_tool_call($tool_call);
1000  
1001 Extracts the tool name and decoded argument HashRef from a single raw tool-call
1002 structure, via L<Langertha::ToolCall/from_fmt>.
1003  
1004 =head2 response_text_content
1005  
1006 my $text = $engine->response_text_content($raw_data);
1007  
1008 Returns the assistant's final text from a decoded response body (what
1009 C<parse_response> returns): the C<content> of the L<Langertha::Response> the
1010 engine's C<chat_response> builds from it, the text L<Langertha::Role::Chat/chat_f>
1011 and the tool loops answer. Gemini thought parts and Anthropic thinking blocks
1012 stay out, a content-chunk list (Mistral) becomes its text, C<E<lt>thinkE<gt>>
1013 tags are filtered when C<think_tag_filter> is on, and for C<hermes> the
1014 C<E<lt>tool_callE<gt>> tags are stripped.
1015  
1016 A body C<chat_response> rejects (an error in the body, a shape it cannot read)
1017 does not croak here: the text is read per L</tool_wire_format> straight off the
1018 body, or C<''>. The engine's L<Langertha::Engine::Remote/rate_limit> is left
1019 as it was.
1020  
1021 =head2 format_tool_results
1022  
1023 my @messages = $engine->format_tool_results($raw_data, $results);
1024  
1025 Assembles tool execution results into the provider-shaped message envelope for
1026 the next turn: the assistant echo of the prior turn plus one
1027 L<Langertha::ToolResult> block per result (arity varies by format).
1028  
1029 For the C<openai> and C<ollama> dialects the echo also carries the provider's
1030 reasoning back when the turn had it — C<reasoning_content>, C<reasoning>,
1031 C<reasoning_details> and C<thinking> respectively — because DeepSeek rejects a
1032 tool loop whose earlier assistant turn lost it.
1033  
1034 Always returns a LIST, for every C<tool_wire_format> — the callers append it
1035 straight onto the conversation with
1036 C<< push @$conversation, $engine->format_tool_results(...) >>, so a single
1037 arrayref would land as one bogus conversation element.
1038  
1039 Each result's C<tool_call> may be a L<Langertha::ToolCall> (what the tool
1040 loops pass) or the raw structure L</response_tool_calls> located.
1041  
1042 An image in a tool's output reaches the model as an image, not as a text
1043 placeholder, on the C<responses> wire (C<input_image> parts in
1044 C<function_call_output.output>), on Gemini 3 (C<functionResponse.parts>) and on
1045 the C<anthropic> wire (an C<image> block in the C<tool_result>), when
1046 C<< supports('image_input') >> is true for the configured model; see
1047 L<Langertha::ToolResult/DESCRIPTION>. The C<responses> and Gemini forms are
1048 documentation-derived, not live-verified, and so is the C<anthropic> form on
1049 the C</anthropic> shims (Kimi documents it, MiniMax does not say).
1050 L<Langertha::Engine::AKIAnthropic> keeps the placeholder for every model: its
1051 shim answers a C<tool_result> image without error, but the model does not see
1052 it.
1053  
1054 A PDF in a tool's output (an embedded resource blob, C<application/pdf>)
1055 reaches the model as a file, not as a text placeholder, on
1056 L<Langertha::Engine::OpenAIResponses> (an C<input_file> part in
1057 C<function_call_output.output>) and on Gemini 3 (C<functionResponse.parts>),
1058 when C<< supports('image_input') >> is true for the configured model: both
1059 providers document PDF understanding as a vision feature. Both forms are
1060 documentation-derived, not live-verified. L<Langertha::Engine::Perplexity>
1061 keeps the placeholder (its Agent API documents only text and image parts
1062 there), as do the OpenAI chat, Ollama and Hermes wires and Gemini before 3.
1063  
1064 On the C<anthropic> wire an embedded text resource or PDF goes out as a
1065 C<document> block, except on L<Langertha::Engine::AKIAnthropic>,
1066 L<Langertha::Engine::MoonshotAnthropic> and (conservatively, not live-verified)
1067 L<Langertha::Engine::LMStudioAnthropic>, whose C</anthropic> endpoints take no
1068 C<document> or C<search_result> in a C<tool_result>: there the text goes out as
1069 a C<text> block and a PDF as a placeholder. The PDF C<document> block elsewhere
1070 does not depend on C<image_input> (k371). An Anthropic-native C<document> or
1071 C<search_result> block in a tool's output becomes a C<text> block with its text
1072 there too, and the engine warns once.
1073  
1074 =head2 tool_loop_response
1075  
1076 my $reply = $engine->tool_loop_response($http_response);
1077 my $reply = $engine->tool_loop_response($data); # decoded body
1078  
1079 Reads one tool-loop turn's reply the way L</chat_with_tools_f> and the
1080 L<Langertha::Chat> tool loops do, and returns the L<Langertha::Response>. Takes
1081 the L<HTTP::Response> of the turn or the body C<parse_response> decoded from
1082 it (the engine's L<Langertha::Engine::Remote/rate_limit> is only updated from
1083 an C<HTTP::Response>). Meant for sibling distributions that run their own tool
1084 loop, such as langertha-raider, so they read replies as core does.
1085  
1086 The reply is parsed by the engine's C<chat_response>, the parser
1087 L<Langertha::Role::Chat/chat_f> uses: an error in a 200 body croaks with
1088 C<chat_f>'s text, and the C<content> is C<chat_f>'s final text. The calls to
1089 run are L<Langertha::Response/tool_calls>; on C<hermes> engines the
1090 C<E<lt>tool_callE<gt>> blocks of the text are lifted there and stripped from
1091 C<content>, unless the engine's parser already did. A prompt the provider
1092 refused outright (Gemini's C<promptFeedback.blockReason>) croaks with
1093 C<< <engine class> prompt blocked: REASON >>. C<raw> is the wire body the
1094 assistant echo (L</format_tool_results>) is built from. To leave out calls cut
1095 off by the token limit, pass the reply to L</tool_loop_calls>.
1096  
1097 =head2 tool_loop_calls
1098  
1099 my ( $calls, $data ) = $engine->tool_loop_calls( $reply, $data );
1100  
1101 The calls one tool-loop turn runs, and the wire body to build its assistant
1102 echo (L</format_tool_results>) from, for a C<$reply> from
1103 L</tool_loop_response>. C<$data> defaults to C<< $reply->raw >>. Public since
1104 k341 for sibling distributions that run their own tool loop, such as
1105 langertha-raider.
1106  
1107 C<$calls> is an ArrayRef of L<Langertha::ToolCall>. When the reply hit its
1108 token limit (C<finish_reason> C<length>, C<max_tokens>, C<MAX_TOKENS> or
1109 C<incomplete>), a call whose arguments do not decode
1110 (L<Langertha::ToolCall/arguments_undecodable>) is dropped: with no call left
1111 this croaks C<tool call arguments truncated (finish_reason REASON); raise
1112 response_size>, otherwise one warning names the dropped calls and the returned
1113 C<$data> is a copy without them, so the next turn has no call without a
1114 result. Otherwise the reply's calls and C<$data> come back unchanged.
1115  
1116 =head2 chat_with_tools_f
1117  
1118 my $response = await $engine->chat_with_tools_f(@messages);
1119  
1120 Async tool-calling chat loop. Accepts the same message arguments as
1121 L<Langertha::Role::Chat/simple_chat>. Gathers tools from all L</mcp_servers>,
1122 sends the request, executes any tool calls returned by the LLM, and repeats
1123 until the LLM returns a final text response or L</tool_max_iterations> is
1124 exceeded. Returns a L<Future> that resolves to the final text response.
1125  
1126 Each reply is read by the engine's C<chat_response>, the parser
1127 L<Langertha::Role::Chat/chat_f> uses: a response whose body reports an error
1128 fails with the text C<chat_f> croaks, the calls run are the reply's
1129 L<Langertha::Response/tool_calls>, and the final text is its C<content>. A
1130 prompt the provider refuses outright (Gemini's C<promptFeedback.blockReason>)
1131 dies with C<prompt blocked: REASON>, where C<chat_f> returns the Response.
1132  
1133 A reply that hit its token limit (C<finish_reason> C<length>, C<max_tokens>,
1134 C<MAX_TOKENS> or C<incomplete>) never runs a call whose arguments do not
1135 decode (L<Langertha::ToolCall/arguments_undecodable>): if no other call is
1136 left the loop dies with C<tool call arguments truncated>, otherwise the
1137 complete calls run, one warning names the dropped ones, and the dropped calls
1138 are left out of the conversation.
1139  
1140 A call to a tool no server offers does not stop the loop: it is answered with
1141 an error result C<unknown tool NAME>, and the other calls of the turn still
1142 run. A tool name offered by two servers is sent once and runs on the first
1143 server in L</mcp_servers>, with a warning naming both.
1144  
1145 A call whose arguments do not decode on a reply that did not hit its token
1146 limit is not run either: it is answered with an error result C<arguments are
1147 not valid JSON: REASON> (L<Langertha::ToolCall/arguments_error>), and the
1148 loop continues so the model can retry.
1149  
1150 =head1 SEE ALSO
1151  
1152 =over
1153  
1154 =item * L<Langertha::Role::HermesTools> - Hermes-style tool calling via XML tags
1155  
1156 =item * L<Langertha::Role::Chat> - Chat role this is built on top of
1157  
1158 =item * L<Langertha::Raider> - Autonomous agent with persistent history using
1159 tools (in the langertha-raider distribution)
1160  
1161 =item * L<Net::Async::MCP> - Base for the MCP clients used as tool providers
1162  
1163 =item * L<Langertha::Engine::Anthropic> - Engine with native tool support
1164  
1165 =back
1166  
1167 =head1 SUPPORT
1168  
1169 =head2 Issues
1170  
1171 Please report bugs and feature requests on GitHub at
1172 L<https://github.com/Getty/langertha/issues>.
1173  
1174 =head2 IRC
1175  
1176 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
1177  
1178 =head1 CONTRIBUTING
1179  
1180 Contributions are welcome! Please fork the repository and submit a pull request.
1181  
1182 =head1 AUTHOR
1183  
1184 Torsten Raudssus <getty@cpan.org>
1185  
1186 =head1 COPYRIGHT AND LICENSE
1187  
1188 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
1189  
1190 This is free software; you can redistribute it and/or modify it under
1191 the same terms as the Perl 5 programming language system itself.
1192  
1193 =cut
« blib/lib/Langertha/Usage.pm ↑ Summary blib/lib/Langertha/Engine/LMStudio.pm »