blib/lib/Langertha/Role/Tools.pm

filter: Statementstmt 93.4% 398 / 426 Branchbran 86.1% 193 / 224 Conditioncond 62.2% 84 / 135 MC/DCmcdc 41.6% 30 / 72 Subroutinesub 96.0% 49 / 51 Podpod 100% 9 / 9 totaltotal 83.2% 763 / 917 CC 352 SCAR 37.1
CC
352
Cov
86%
_raw_text_content
245.7
_raw_text_content
245.7
_hermes_stream_split
32.3
CRAP 41.0
« blib/lib/Langertha/Role/ResponseFormat.pm ↑ Summary blib/lib/Langertha/Tool.pm »
1 package Langertha::Role::Tools;
2 # ABSTRACT: Role for MCP tool calling support
3 197 our $VERSION = '0.505';
4 197 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 197 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 197 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 197 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 197 ▶use Scalar::Util qw( blessed refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 197 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 197 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 197 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 197 ▶use Langertha::ToolResult;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 197 with 'Langertha::Role::ParallelToolUse';
15  
16  
17 has mcp_servers => (
18 is => 'ro',
19 isa => 'ArrayRef',
20 4341 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
21 197 );
22  
23  
24 197 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 19 ▶ trigger => sub { $_[0]->_set_tool_wire_format_given(1) },
Subroutine __ANON__: called CC=1 SCAR=0.0
38 197 );
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 197 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 121 ▶sub _reset_derived_tool_wire_format {
Subroutine _reset_derived_tool_wire_format: called CC=2 SCAR=9.2
56 0 ▶ my ($self) = @_;
Subroutine _reset_derived_tool_wire_format: not called CC=2 SCAR=9.2
57 0 ▶ $self->_clear_tool_wire_format unless $self->_tool_wire_format_given;
Branch: 2 branches
BranchTrueFalseTotal
unless $self->_tool_wire_format_given 117 4 121
unless $self->_tool_wire_format_given 0 0 0
58 0 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 297 ▶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 216 ▶sub build_tool_chat_request {
Subroutine build_tool_chat_request: called CC=2 SCAR=6.9
Pod documented
73 216 my ( $self, $conversation, $formatted_tools, %extra ) = @_;
74 216 ▶ if ( $self->tool_wire_format eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->tool_wire_format eq "hermes") 27 189 216
75 27 return $self->chat_request( $self->_hermes_tool_messages( $conversation, $formatted_tools ), %extra );
76 }
77 189 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_$_"; $chunk->$has;} "thinking", "tool_calls", "usage", "cached_tokens", "citations")
!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 526 ▶sub format_tools {
Subroutine format_tools: called CC=1 SCAR=0.0
Pod documented
258 526 my ( $self, $mcp_tools ) = @_;
259 526 return Langertha::Tool->format_list( $self->tool_wire_format, $mcp_tools );
260 }
261  
262  
263 # The parsed response body response_tool_calls and response_text_content read.
264 # A Langertha::Response (what response_call returns for most engines) is read
265 # through its raw body; any other blessed value is no body and croaks instead of
266 # answering empty -- since 0.503 (k341) both went through ToolCall->locate,
267 # which silently answered [] / '' for everything but a plain HASH.
268 76 ▶sub _body_data {
Subroutine _body_data: called CC=5 SCAR=16.1
269 76 my ( $self, $data, $method ) = @_;
270 76 ▶ return $data unless blessed $data;
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($data) 71 5 76
271 5 ▶ return $data->raw if $data->isa('Langertha::Response') && $data->has_raw;
Branch: 1 branch
BranchTrueFalseTotal
if $data->isa("Langertha::Response") and $data->has_raw 2 3 5
Condition100%3/3
$data->isa("Langertha::Response") and $data->has_raw
!ll&&!rl&&r
212
MC/DC100%2/2
$data->isa("Langertha::Response") and $data->has_raw
$data->isa("Langertha::Response") $data->has_raw
Truth table100%3/3
A and B
A= $data->isa("Langertha::Response")B= $data->has_raw
ABresult
0X0
100
111
272 3 ▶ croak ref($self)."->$method: expects the parsed response body (a plain HASH)"
Branch: 1 branch
BranchTrueFalseTotal
$data->isa('Langertha::Response') ? : 1 2 3
273 . ( $data->isa('Langertha::Response') ? ', this Langertha::Response carries no raw body' : ', got a '.ref($data) );
274 }
275  
276 47 ▶sub response_tool_calls {
Subroutine response_tool_calls: called CC=4 SCAR=13.9
Pod documented
277 47 my ( $self, $data ) = @_;
278 47 $data = $self->_body_data( $data, 'response_tool_calls' );
279 45 my $fmt = $self->tool_wire_format;
280 # The calls tool_loop_response would run, as raw structures -- karr k341.
281 # Hermes: the calls of chat_response's reply (native ones, else the lift),
282 # as { name, arguments }; a body it rejects falls back to the text split.
283 45 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 21 24 45
284 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
285 17 $reply = $self->_hermes_lift($reply);
286 10 return [ map { { name => $_->name, arguments => $_->arguments } }
287 17 ▶ @{ $reply->has_tool_calls ? $reply->tool_calls : [] } ];
Branch: 1 branch
BranchTrueFalseTotal
$reply->has_tool_calls ? : 9 8 17
288 }
289 # Others: a located structure that parses to no ToolCall is no call.
290 23 return [ grep { defined Langertha::ToolCall->from_fmt( $fmt, $_ ) }
291 24 @{ Langertha::ToolCall->locate( $fmt, $data ) } ];
292 }
293  
294 # The raw calls read straight off a decoded body, without chat_response:
295 # response_tool_calls' hermes fallback, and what an engine's own
296 # chat_response uses (AKI native), which must not recurse into it.
297 16 ▶sub _raw_tool_calls {
Subroutine _raw_tool_calls: called CC=4 SCAR=14.2
298 16 my ( $self, $data ) = @_;
299 16 my $fmt = $self->tool_wire_format;
300 16 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 16 0 16
301 16 my $content = $self->hermes_extract_content($data);
302 # A call inside the thinking is not a call: split the think-filtered text,
303 # as chat_f and the stream lift do (k302) -- karr k323.
304 16 ▶ ($content) = $self->filter_think_content($content)
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("filter_think_content") 16 0 16
305 if $self->can('filter_think_content');
306 16 ▶ return [] unless $content;
Branch: 1 branch
BranchTrueFalseTotal
unless $content 4 12 16
307 12 return ( $self->_hermes_split_text($content) )[1];
308 }
309 0 return Langertha::ToolCall->locate( $fmt, $data );
310 }
311  
312  
313 17 ▶sub extract_tool_call {
Subroutine extract_tool_call: called CC=5 SCAR=16.1
Pod documented
314 17 my ( $self, $tc ) = @_;
315 # A Langertha::ToolCall (what Response->tool_calls holds) is already parsed;
316 # any other object is no wire structure -- it used to answer (undef, undef).
317 17 ▶ if ( blessed $tc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($tc)) 2 15 17
318 2 ▶ return ( $tc->name, $tc->arguments ) if $tc->isa('Langertha::ToolCall');
Branch: 1 branch
BranchTrueFalseTotal
if $tc->isa("Langertha::ToolCall") 1 1 2
319 1 croak ref($self)."->extract_tool_call: expects a raw tool-call structure or a Langertha::ToolCall, got a ".ref($tc);
320 }
321 15 my $fmt = $self->tool_wire_format;
322 15 ▶ return ( $tc->{name}, $tc->{arguments} ) if $fmt eq 'hermes';
Branch: 1 branch
BranchTrueFalseTotal
if $fmt eq "hermes" 3 12 15
323 12 my $call = Langertha::ToolCall->from_fmt( $fmt, $tc );
324 12 ▶ return $call ? ( $call->name, $call->arguments ) : ( undef, undef );
Branch: 1 branch
BranchTrueFalseTotal
$call ? : 11 1 12
325 }
326  
327  
328 29 ▶sub response_text_content {
Subroutine response_text_content: called CC=4 SCAR=13.9
Pod documented
329 29 my ( $self, $data ) = @_;
330 29 $data = $self->_body_data( $data, 'response_text_content' );
331 # The text chat_f and the tool loops answer (Gemini thought parts out,
332 # content-chunk lists joined, think tags filtered), read by the engine's
333 # chat_response. A body chat_response rejects falls back to the plain
334 # per-format read below: plugins call this reader, it never croaks -- karr k338.
335 28 ▶ if ( my $reply = $self->_reply_from_data($data) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $reply = $self->_reply_from_data($data)) 24 4 28
336 24 ▶ my $text = $reply->content // '';
Condition50%1/2
$reply->content // ""
l!l
240
MC/DC0%0/1
$reply->content // ""
$reply->content
Truth table50%1/2
A
A= $reply->content
Aresult
11
00
337 24 ▶ $text = ( $self->_hermes_split_text($text) )[0]
Branch: 1 branch
BranchTrueFalseTotal
if $self->tool_wire_format eq "hermes" 5 19 24
338 if $self->tool_wire_format eq 'hermes';
339 24 return $text;
340 }
341 4 return $self->_raw_text_content($data);
342 }
343  
344 # The per-format text read straight off a decoded body, without
345 # chat_response: response_text_content's fallback, and what an engine's own
346 # chat_response uses (AKI native), which must not recurse into it.
347 8 ▶sub _raw_text_content {
Subroutine _raw_text_content: called CC=26 SCAR=55.0
348 8 my ( $self, $data ) = @_;
349 8 ▶ return '' unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 1 7 8
350 7 my $fmt = $self->tool_wire_format;
351 7 ▶ if ( $fmt eq 'openai' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "openai") 2 5 7
352 2 ▶ my $choice = $data->{choices}[0] or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $choice = $data->{"choices"}[0] or return "" 0 2 2
353 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
354 }
355 5 ▶ if ( $fmt eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "ollama") 0 5 5
356 0 ▶ my $msg = $data->{message} or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $msg = $data->{"message"} or return "" 0 0 0
357 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
358 }
359 5 ▶ if ( $fmt eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "anthropic") 1 4 5
360 return join( '',
361 0 ▶ 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
362 }
363 4 ▶ if ( $fmt eq 'gemini' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "gemini") 0 4 4
364 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
365 0 ▶ return '' unless @$candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @$candidates 0 0 0
366 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
367 0 return join( '', map { $_->{text} } grep { exists $_->{text} } @$parts );
368 }
369 4 ▶ if ( $fmt eq 'responses' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "responses") 0 4 4
370 0 my $text = '';
371 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
372 0 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 0 0
373 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
374 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
375 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
376 }
377 }
378 0 return $text;
379 }
380 4 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 4 0 4
381 4 return ( $self->_hermes_split_text( $self->hermes_extract_content($data) ) )[0];
382 }
383 0 return '';
384 }
385  
386  
387 # The Response the engine's chat_response builds from a decoded body, as if
388 # the body had arrived in a 200. The engine's rate limit describes the last
389 # real response, so it is kept as it was -- karr k338.
390 205 ▶sub _chat_response_from_data {
Subroutine _chat_response_from_data: called CC=4 SCAR=13.9
391 205 my ( $self, $data ) = @_;
392 205 require HTTP::Response;
393 205 my $http = HTTP::Response->new( 200, 'OK',
394 [ 'Content-Type' => 'application/json' ], $self->json->encode($data) );
395 205 ▶ return $self->chat_response($http) unless $self->can('_last_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("_last_rate_limit") 8 197 205
396 197 my ( $had, $rate_limit ) = ( $self->_has_last_rate_limit, $self->_last_rate_limit );
397 197 my $reply;
398 197 my $ok = eval { $reply = $self->chat_response($http); 1 };
399 197 my $err = $@;
400 197 ▶ if ($had) { $self->_last_rate_limit($rate_limit) } else { $self->_clear_last_rate_limit }
Branch: 1 branch
BranchTrueFalseTotal
if ($had) { } 141 56 197
401 197 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 23 174 197
402 174 return $reply;
403 }
404  
405 # _chat_response_from_data for the readers: undef instead of a croak, when
406 # the body is no HASH or the engine cannot parse it.
407 49 ▶sub _reply_from_data {
Subroutine _reply_from_data: called CC=4 SCAR=13.9
408 49 my ( $self, $data ) = @_;
409 49 ▶ 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 48 49
Condition66%2/3
ref $data eq "HASH" and $self->can("chat_response")
!ll&&!rl&&r
1048
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
410 48 local $@;
411 48 my $reply = eval { $self->_chat_response_from_data($data) };
412 48 ▶ return blessed $reply ? $reply : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($reply) ? : 41 7 48
413 }
414  
415 # A result's tool_call is a Langertha::ToolCall (the tool loops read
416 # Response.tool_calls, ADR 0003) or the raw wire structure response_tool_calls
417 # locates (langertha-raider). The id / name the result block pairs with, from
418 # either -- karr k321.
419 200 ▶sub _result_call_id {
Subroutine _result_call_id: called CC=6 SCAR=17.9
420 200 my ( $tc ) = @_;
421 200 ▶ return $tc->id if blessed $tc;
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($tc) 89 111 200
422 111 ▶ return $tc->{functionCall}{id} // '' if ref $tc->{functionCall} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $tc->{"functionCall"} eq "HASH" 24 87 111
Condition100%2/2
$tc->{"functionCall"}{"id"} // ""
l!l
213
MC/DC100%1/1
$tc->{"functionCall"}{"id"} // ""
$tc->{"functionCall"}{"id"}
Truth table100%2/2
A
A= $tc->{"functionCall"}{"id"}
Aresult
11
00
423 87 ▶ return $tc->{call_id} // $tc->{id} // '';
Condition100%5/5
($tc->{"call_id"} // $tc->{"id"}) // ""
l!l
798
$tc->{"call_id"} // $tc->{"id"}
l!l&&r!l&&!r
24558
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
424 }
425  
426 65 ▶sub _result_call_name {
Subroutine _result_call_name: called CC=7 SCAR=19.6
427 65 my ( $tc ) = @_;
428 65 ▶ return $tc->name if blessed $tc;
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($tc) 24 41 65
429 41 ▶ return $tc->{functionCall}{name} // '' if ref $tc->{functionCall} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $tc->{"functionCall"} eq "HASH" 24 17 41
Condition50%1/2
$tc->{"functionCall"}{"name"} // ""
l!l
240
MC/DC0%0/1
$tc->{"functionCall"}{"name"} // ""
$tc->{"functionCall"}{"name"}
Truth table50%1/2
A
A= $tc->{"functionCall"}{"name"}
Aresult
11
00
430 17 ▶ return $tc->{function}{name} // '' if ref $tc->{function} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $tc->{"function"} eq "HASH" 10 7 17
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
431 7 ▶ return $tc->{name} // '';
Condition100%2/2
$tc->{"name"} // ""
l!l
61
MC/DC100%1/1
$tc->{"name"} // ""
$tc->{"name"}
Truth table100%2/2
A
A= $tc->{"name"}
Aresult
11
00
432 }
433  
434 # The MCP call_tool result's payload as ToolResult constructor args: content
435 # plus structuredContent, which every format falls back to when content is
436 # empty (karr k326, k336).
437 214 ▶sub _result_payload {
Subroutine _result_payload: called CC=3 SCAR=11.1
438 214 my ( $result ) = @_;
439 return (
440 content => ( $result->{content} // [] ),
441 ( defined $result->{structuredContent}
442 214 ▶ ? ( structured_content => $result->{structuredContent} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
defined $result->{'structuredContent'} ? : 3 211 214
Condition50%1/2
$result->{"content"} // []
l!l
2140
MC/DC0%0/1
$result->{"content"} // []
$result->{"content"}
Truth table50%1/2
A
A= $result->{"content"}
Aresult
11
00
443 );
444 }
445  
446 # Tool-result images and PDFs ride natively (ToolResult's image_input /
447 # native_pdf options, karr k344, k359, k361) exactly when the engine claims
448 # tool_result_images / tool_result_pdf for the selected model (ADR 0039, karr
449 # k380): the public capability is the single source of truth, so what
450 # supports() tells a caller and what goes on the wire cannot disagree -- also on
451 # a forced tool_wire_format. The registry keeps the flags only on a wire with a
452 # native form (ToolResult->carries_native) and, where that form needs vision,
453 # for an image_input model (ToolResult->native_needs_vision); the engines add
454 # their own gates (Gemini 3 and later, AKIAnthropic, the anthropic source
455 # blocks). Both options are passed explicitly: native_pdf defaults to true on
456 # the anthropic wire (a bare to('anthropic') keeps its document block), so a
457 # missing claim must say 0 there. The tool loop sends what an MCP server
458 # returned, not what the caller chose, so without a claim an image or PDF keeps
459 # the k336 placeholder.
460 109 ▶sub _tool_result_media_opts {
Subroutine _tool_result_media_opts: called CC=1 SCAR=0.0
461 109 my ( $self ) = @_;
462 109 ▶ my $claims = sub { $self->can('supports') && $self->supports( $_[0] ) ? 1 : 0 };
Subroutine __ANON__: called CC=3 SCAR=11.1
Branch: 1 branch
BranchTrueFalseTotal
$self->can('supports') && $self->supports($_[0]) ? : 109 109 218
Condition66%2/3
$self->can("supports") and $self->supports($_[0])
!ll&&!rl&&r
0109109
MC/DC50%1/2
$self->can("supports") and $self->supports($_[0])
$self->can("supports") $self->supports($_[0])
Truth table66%2/3
A and B
A= $self->can("supports")B= $self->supports($_[0])
ABresult
0X0
100
111
463 return (
464 109 image_input => $claims->('tool_result_images'),
465 native_pdf => $claims->('tool_result_pdf'),
466 );
467 }
468  
469 # Whether the anthropic wire takes Anthropic's source blocks (document,
470 # search_result) inside a tool_result (karr k364, k366). First-party Anthropic
471 # documents them; a /anthropic shim that rejects them sets this to 0, and
472 # ToolResult then sends a text document as a text block, a PDF as the k336
473 # placeholder and a native document / search_result as its text. Wire truth,
474 # not a model question, so it stays a private predicate; the Anthropic family
475 # derives its public tool_result_pdf flag from it (AnthropicBase, ADR 0039; the
476 # PDF document block then also needs that flag), and it alone governs text
477 # documents and search_result blocks.
478 602 ▶sub _tool_result_source_blocks_on_wire { 1 }
Subroutine _tool_result_source_blocks_on_wire: called CC=1 SCAR=0.0
479  
480 # A native document / search_result is the caller's choice for the Anthropic
481 # wire, so turning it into text is worth one warning per engine instance (the
482 # ADR 0035 once-key pattern). An MCP resource becoming text is the normal path
483 # on these shims and stays quiet.
484 23 ▶sub _carp_degraded_source_blocks {
Subroutine _carp_degraded_source_blocks: called CC=3 SCAR=11.0
485 23 my ( $self, $result ) = @_;
486 23 ▶ my @types = $result->_native_source_block_types or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@types) = $result->_native_source_block_types or return 7 16 23
487 7 ▶ return unless $self->can('_langertha_carp');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("_langertha_carp") 0 7 7
488 7 $self->_langertha_carp( "".( ref $self ).": sending " . join( ' / ', @types )
489 . " blocks in a tool result as text -- this endpoint takes no document or"
490 . " search_result block inside a tool_result", 'tool_result_source_blocks' );
491 7 return;
492 }
493  
494 178 ▶sub format_tool_results {
Subroutine format_tool_results: called CC=22 SCAR=31.0
Pod documented
495 178 my ( $self, $data, $results ) = @_;
496 178 my $fmt = $self->tool_wire_format;
497  
498 178 ▶ if ( $fmt eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "anthropic") 50 128 178
499 50 my $source_blocks = $self->_tool_result_source_blocks_on_wire;
500 50 ▶ my @opts = ( $self->_tool_result_media_opts,
Branch: 1 branch
BranchTrueFalseTotal
$source_blocks ? : 27 23 50
501 ( $source_blocks ? () : ( source_blocks => 0 ) ) );
502 my @blocks = map {
503 50 my $result = Langertha::ToolResult->new(
504 id => _result_call_id( $_->{tool_call} ),
505 _result_payload( $_->{result} ),
506 57 ▶ is_error => ( $_->{result}{isError} ? 1 : 0 ),
Branch: 1 branch
BranchTrueFalseTotal
$_->{'result'}{'isError'} ? : 7 50 57
507 );
508 57 ▶ $self->_carp_degraded_source_blocks($result) unless $source_blocks;
Branch: 1 branch
BranchTrueFalseTotal
unless $source_blocks 23 34 57
509 57 $result->to( 'anthropic', @opts );
510 } @$results;
511 return (
512 { role => 'assistant', content => $data->{content} },
513 50 { role => 'user', content => \@blocks },
514 );
515 }
516  
517 128 ▶ if ( $fmt eq 'gemini' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "gemini") 33 95 128
518 33 my @opts = ( $self->_tool_result_media_opts );
519 my @parts = map {
520 33 Langertha::ToolResult->new(
521 name => _result_call_name( $_->{tool_call} ),
522 id => _result_call_id( $_->{tool_call} ),
523 36 _result_payload( $_->{result} ),
524 )->to( 'gemini', @opts )
525 } @$results;
526 33 my $candidate = $data->{candidates}[0];
527 return (
528 { role => 'model', parts => $candidate->{content}{parts} },
529 33 { role => 'user', parts => \@parts },
530 );
531 }
532  
533 95 ▶ if ( $fmt eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "ollama") 11 84 95
534 11 my $msg = $data->{message};
535 my %echo = (
536 role => 'assistant',
537 content => $msg->{content},
538 tool_calls => $msg->{tool_calls},
539 11 );
540 # Ollama returns the chain-of-thought in message.thinking; echo it back for
541 # the same reason the openai branch below echoes reasoning_content
542 # (karr k136).
543 11 ▶ $echo{thinking} = $msg->{thinking} if defined $msg->{thinking};
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg->{"thinking"} 1 10 11
544 return (
545 \%echo,
546 map {
547 11 Langertha::ToolResult->new(
548 name => _result_call_name( $_->{tool_call} ),
549 id => _result_call_id( $_->{tool_call} ),
550 15 _result_payload( $_->{result} ),
551 )->to('ollama')
552 } @$results,
553 );
554 }
555  
556 84 ▶ if ( $fmt eq 'responses' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "responses") 26 58 84
557 # The Responses API takes one flat item list: the model's own output items
558 # echoed back, then one function_call_output per result. It only accepts a
559 # function_call_output whose call_id was announced by a *top-level*
560 # function_call item, so hoist any call out of the legacy
561 # nested-inside-a-message shape that ToolCall->locate('responses') also
562 # walks. Returns a LIST like every other branch — every caller does
563 # `push @$conversation, $engine->format_tool_results(...)` (karr #85).
564 26 my @echo;
565 26 ▶ for my $item ( @{ $data->{output} // [] } ) {
Condition50%1/2
$data->{"output"} // []
l!l
260
MC/DC0%0/1
$data->{"output"} // []
$data->{"output"}
Truth table50%1/2
A
A= $data->{"output"}
Aresult
11
00
566 43 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 43 43
567 43 ▶ if ( ( $item->{type} // '' ) eq 'message' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($item->{"type"} // "") eq "message") 6 37 43
Condition50%1/2
$item->{"type"} // ""
l!l
430
MC/DC0%0/1
$item->{"type"} // ""
$item->{"type"}
Truth table50%1/2
A
A= $item->{"type"}
Aresult
11
00
568 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
569 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
570 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
571 6 ▶ push @echo, { %$item, content => \@rest } if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 4 2 6
572 6 push @echo, @calls;
573 6 next;
574 }
575 37 push @echo, $item;
576 }
577 # Which echoed items the wire takes back as input is the envelope's call:
578 # the ResponsesCompatible hook passes all through on OpenAI and filters to
579 # the Agent input schema on Perplexity (karr k213, ADR 0020).
580 26 ▶ @echo = map { $self->_responses_echo_item($_) } @echo
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_responses_echo_item") 23 3 26
581 if $self->can('_responses_echo_item');
582 26 my @opts = ( $self->_tool_result_media_opts );
583 return (
584 @echo,
585 map {
586 26 Langertha::ToolResult->new(
587 id => _result_call_id( $_->{tool_call} ),
588 26 _result_payload( $_->{result} ),
589 )->to( 'responses', @opts )
590 } @$results,
591 );
592 }
593  
594 58 ▶ if ( $fmt eq 'hermes' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hermes") 11 47 58
595 11 my $content = $self->hermes_extract_content($data);
596 11 my $res_tag = $self->hermes_response_tag;
597 return (
598 { role => 'assistant', content => $content },
599 map {
600 11 { role => 'tool',
601 content => Langertha::ToolResult->new(
602 name => _result_call_name( $_->{tool_call} ),
603 14 _result_payload( $_->{result} ),
604 )->to( 'hermes', response_tag => $res_tag ) }
605 } @$results,
606 );
607 }
608  
609 # openai (default)
610 47 my $msg = $data->{choices}[0]{message};
611 my %echo = (
612 role => 'assistant',
613 content => $msg->{content},
614 tool_calls => $msg->{tool_calls},
615 47 );
616 # Carry the provider's reasoning fields back into the assistant echo.
617 # DeepSeek returns HTTP 400 on the next iteration of a tool loop when
618 # reasoning_content is not sent back while tools are present; Moonshot
619 # (kimi) requires the same within one tool-call loop, OpenRouter requires
620 # reasoning_details to round-trip unmodified, Mistral loses output quality
621 # and xAI misses the prompt cache without it. Deliberately an allowlist and
622 # not the whole message: some OpenAI-compatible servers reject unknown keys
623 # on an inbound assistant message (karr k136).
624 47 for my $key (qw( reasoning_content reasoning reasoning_details )) {
625 141 ▶ $echo{$key} = $msg->{$key} if defined $msg->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg->{$key} 5 136 141
626 }
627 return (
628 \%echo,
629 map {
630 47 Langertha::ToolResult->new(
631 id => _result_call_id( $_->{tool_call} ),
632 66 _result_payload( $_->{result} ),
633 )->to('openai')
634 } @$results,
635 );
636 }
637  
638  
639 # One tool-loop turn's reply, read by the parser chat_f uses: chat_response
640 # croaks on an error-in-body 200 exactly as chat_f does (k301/k311/k317) and
641 # yields the same final text (Gemini thought parts out, content-chunk arrays
642 # joined, think tags filtered) -- karr k321, k322. The calls to run are
643 # Response.tool_calls (ADR 0003); hermes calls ride in the text and are lifted
644 # as chat_f lifts them, unless the engine's chat_response already did (AKI
645 # native). ->raw stays the wire body the assistant echo is built from.
646 # Shared by chat_with_tools_f and both Langertha::Chat tool loops.
647 # Public since k341 (ADR 0028): langertha-raider's loop reads its replies here
648 # instead of the raw body. Takes the HTTP::Response or the decoded body.
649 230 ▶sub tool_loop_response {
Subroutine tool_loop_response: called CC=4 SCAR=13.9
Pod documented
650 230 my ( $self, $reply ) = @_;
651 230 ▶ my $response = blessed $reply && $reply->isa('HTTP::Response')
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($reply) && $reply->isa('HTTP::Response') ? : 73 157 230
Condition66%2/3
builtin::blessed($reply) and $reply->isa("HTTP::Response")
!ll&&!rl&&r
157073
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
652 ? $self->chat_response($reply)
653 : $self->_chat_response_from_data($reply);
654 # A blocked prompt is an answer to chat_f (k301) but ends a tool loop, whose
655 # result is only text: '' would hide why -- karr k339.
656 207 my $blocked = $self->_tool_loop_block_reason($response);
657 207 ▶ croak "" . ( ref $self ) . " prompt blocked: $blocked" if defined $blocked;
Branch: 1 branch
BranchTrueFalseTotal
if defined $blocked 7 200 207
658 200 return $self->_hermes_lift($response);
659 }
660  
661 72 ▶sub _tool_loop_response { shift->tool_loop_response(@_) }
Subroutine _tool_loop_response: called CC=1 SCAR=0.0
662  
663  
664 # The hermes calls ride in the text: lifted as chat_f lifts them, unless the
665 # engine's chat_response already did (AKI native).
666 217 ▶sub _hermes_lift {
Subroutine _hermes_lift: called CC=5 SCAR=16.1
667 217 my ( $self, $response ) = @_;
668 return $response unless $self->tool_wire_format eq 'hermes'
669 217 ▶ && !( $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;} 174 43 217
Condition83%5/6
$self->tool_wire_format eq "hermes" and not $response->has_tool_calls && @{$response->tool_calls;}
!ll&&!rl&&r
172243
$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
670 43 my ( $clean, $calls ) = $self->_hermes_split_text( $response->content );
671 43 ▶ return @$calls ? $response->clone_with( content => $clean, tool_calls => $calls ) : $response;
Branch: 1 branch
BranchTrueFalseTotal
@$calls ? : 18 25 43
672 }
673  
674 # Why the provider refused the prompt itself, when a reply says so (Gemini's
675 # promptFeedback.blockReason); undef otherwise. Engines whose wire reports a
676 # blocked prompt override it -- karr k339.
677 177 ▶sub _tool_loop_block_reason { return }
Subroutine _tool_loop_block_reason: called CC=1 SCAR=0.0
678  
679 # The finish reasons that mean "the reply hit its token limit", as each wire
680 # spells it: OpenAI-compatible and Ollama 'length', Anthropic 'max_tokens',
681 # Gemini 'MAX_TOKENS', an incomplete Responses message 'incomplete'.
682 197 my %TOKEN_LIMIT_FINISH = map { $_ => 1 } qw( length max_tokens MAX_TOKENS incomplete );
683  
684 # The calls one tool-loop turn runs, and the wire body its assistant echo is
685 # built from. A reply cut off by its token limit can carry a call whose
686 # arguments string was cut too; it decodes to nothing, and running the tool on
687 # {} is wrong, so that call is dropped, as the stream parser drops an
688 # unfinished call. With no call left the loop croaks; otherwise the complete
689 # calls run, a carp names the dropped ones, and the echo leaves them out, so
690 # the next turn has no call without a result -- karr k324.
691 187 ▶sub tool_loop_calls {
Subroutine tool_loop_calls: called CC=8 SCAR=20.8
Pod documented
692 187 my ( $self, $reply, $data ) = @_;
693 187 ▶ $data //= $reply->raw;
Condition66%2/3
$data //= $reply->raw
l!l&&r!l&&!r
18520
MC/DC0%0/2
$data //= $reply->raw
$data $reply->raw
Truth table66%2/3
A //= B
A= $dataB= $reply->raw
ABresult
1X1
011
000
694 187 ▶ my @calls = $reply->has_tool_calls ? @{ $reply->tool_calls } : ();
Branch: 1 branch
BranchTrueFalseTotal
$reply->has_tool_calls ? : 92 95 187
695 187 my $reason = $reply->finish_reason;
696 return ( \@calls, $data )
697 187 ▶ unless @calls && defined $reason && $TOKEN_LIMIT_FINISH{$reason};
Branch: 1 branch
BranchTrueFalseTotal
unless @calls and defined $reason and $TOKEN_LIMIT_FINISH{$reason} 164 23 187
Condition100%6/6
@calls and defined $reason and $TOKEN_LIMIT_FINISH{$reason}
!ll&&!rl&&r
1055923
@calls and defined $reason
!ll&&!rl&&r
99682
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
698 23 my @dropped = grep { $_->arguments_undecodable } @calls;
699 23 ▶ return ( \@calls, $data ) unless @dropped;
Branch: 1 branch
BranchTrueFalseTotal
unless @dropped 3 20 23
700 20 my $class = ref $self;
701 20 ▶ croak "$class tool call arguments truncated (finish_reason $reason); raise response_size"
Branch: 1 branch
BranchTrueFalseTotal
if @dropped == @calls 16 4 20
702 if @dropped == @calls;
703 $self->_langertha_carp( "$class: dropped " . scalar(@dropped)
704 . " tool call(s) with truncated arguments (finish_reason $reason): "
705 4 . join( ', ', map { $_->name } @dropped ) . "; raise response_size" );
706 4 return ( [ grep { !$_->arguments_undecodable } @calls ],
707 $self->_echo_without_undecodable_calls($data) );
708 }
709  
710 62 ▶sub _tool_loop_calls { shift->tool_loop_calls(@_) }
Subroutine _tool_loop_calls: called CC=1 SCAR=0.0
711  
712  
713 # A copy of the wire body without the raw calls whose arguments do not
714 # decode; everything else is shared. Hermes calls ride in the text, and an
715 # unfinished <tool_call> block never became a call.
716 4 ▶sub _echo_without_undecodable_calls {
Subroutine _echo_without_undecodable_calls: called CC=5 SCAR=16.2
717 4 my ( $self, $data ) = @_;
718 4 my $fmt = $self->tool_wire_format;
719 4 ▶ return $data if $fmt eq 'hermes';
Branch: 1 branch
BranchTrueFalseTotal
if $fmt eq "hermes" 0 4 4
720 4 my %drop;
721 4 for my $raw ( @{ Langertha::ToolCall->locate( $fmt, $data ) } ) {
722 8 my $call = Langertha::ToolCall->from_fmt( $fmt, $raw );
723 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
724 }
725 4 return _without_refs( $data, \%drop );
726 }
727  
728 64 ▶sub _without_refs {
Subroutine _without_refs: called CC=4 SCAR=13.9
729 64 my ( $node, $drop ) = @_;
730 64 ▶ return { map { $_ => _without_refs( $node->{$_}, $drop ) } keys %$node }
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "HASH" 20 44 64
731 if ref $node eq 'HASH';
732 8 return [ map { _without_refs( $_, $drop ) }
733 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
734 if ref $node eq 'ARRAY';
735 36 return $node;
736 }
737  
738 # The tool list a tool loop sends and the server each name runs on, from
739 # ( [ $mcp, \@tools ], ... ) in mcp_servers order. A name two servers offer is
740 # sent once -- providers reject a request that declares one function twice --
741 # and runs on the first server; a carp names both -- karr k332.
742 144 ▶sub _tool_loop_tools {
Subroutine _tool_loop_tools: called CC=5 SCAR=16.1
743 144 my ( $self, @server_tools ) = @_;
744 144 my ( @all_tools, %tool_server_map, %server_no );
745 144 ▶ my $label = sub { "MCP server $server_no{ refaddr $_[0] } (" . ref( $_[0] ) . ")" };
Subroutine __ANON__: called CC=1 SCAR=0.0
746 144 my $no = 0;
747 144 for my $pair (@server_tools) {
748 147 my ( $mcp, $tools ) = @$pair;
749 147 ▶ $server_no{ refaddr $mcp } //= ++$no;
Condition50%1/2
$server_no{builtin::refaddr($mcp)} //= ++$no
l!l
0147
MC/DC0%0/1
$server_no{builtin::refaddr($mcp)} //= ++$no
$server_no{builtin::refaddr($mcp)}
Truth table50%1/2
A
A= $server_no{builtin::refaddr($mcp)}
Aresult
11
00
750 147 for my $tool (@$tools) {
751 157 my $name = $tool->{name};
752 157 ▶ if ( my $first = $tool_server_map{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $first = $tool_server_map{$name}) 3 154 157
753 3 $self->_langertha_carp( "" . ( ref $self ) . ": tool '$name' is offered by "
754 . $label->($first) . " and " . $label->($mcp) . "; using the first" );
755 3 next;
756 }
757 154 $tool_server_map{$name} = $mcp;
758 154 push @all_tools, $tool;
759 }
760 }
761 144 return ( \@all_tools, \%tool_server_map );
762 }
763  
764 # The result a tool loop answers a call to a tool no server offers: an error
765 # the model can recover from, not a die that loses the batch -- karr k332.
766 9 ▶sub _unknown_tool_result {
Subroutine _unknown_tool_result: called CC=2 SCAR=7.2
767 9 my ( $name ) = @_;
768 return {
769 9 ▶ content => [ { type => 'text', text => "unknown tool " . ( $name // '' ) } ],
Condition50%1/2
$name // ""
l!l
90
MC/DC0%0/1
$name // ""
$name
Truth table50%1/2
A
A= $name
Aresult
11
00
770 isError => JSON->true,
771 };
772 }
773  
774 # The result a tool loop answers a call whose arguments do not decode, or
775 # undef for a call whose arguments did. A call cut off by the token limit was
776 # already dropped by _tool_loop_calls; any other one would run the tool on {},
777 # so the model gets an error it can retry instead -- karr k345.
778 95 ▶sub _undecodable_arguments_result {
Subroutine _undecodable_arguments_result: called CC=3 SCAR=11.1
779 95 my ( $tc ) = @_;
780 95 ▶ return undef unless $tc->arguments_undecodable;
Branch: 1 branch
BranchTrueFalseTotal
unless $tc->arguments_undecodable 86 9 95
781 return {
782 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
783 text => "arguments are not valid JSON: " . ( $tc->arguments_error // 'not a JSON object' ) } ],
784 isError => JSON->true,
785 };
786 }
787  
788 49 ▶async sub chat_with_tools_f {
Subroutine chat_with_tools_f: called CC=10 SCAR=23.1
Pod documented
789 49 my ( $self, @messages ) = @_;
790  
791 49 ▶ croak "No MCP servers configured" unless @{$self->mcp_servers};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->mcp_servers;} 0 49 49
792  
793 # Gather tools from all MCP servers
794 49 my @server_tools;
795 49 for my $mcp (@{$self->mcp_servers}) {
796 50 push @server_tools, [ $mcp, await $mcp->list_tools ];
797 }
798 49 my ( $all_tools, $tool_server_map ) = $self->_tool_loop_tools(@server_tools);
799 49 my @all_tools = @$all_tools;
800  
801 49 my $formatted_tools = $self->format_tools(\@all_tools);
802 # URL images this engine inlines: fetched async, not by LWP in the loop (k274).
803 49 @messages = await $self->_prefetch_inline_images_f(@messages);
804 49 my $conversation = $self->chat_messages(@messages);
805  
806 $log->debugf("[%s] chat_with_tools_f: %d tools from %d MCP servers, max_iterations=%d",
807 49 ref $self, scalar @all_tools, scalar @{$self->mcp_servers}, $self->tool_max_iterations);
808  
809 49 for my $iteration (1..$self->tool_max_iterations) {
810 73 $log->debugf("[%s] Tool loop iteration %d/%d",
811 ref $self, $iteration, $self->tool_max_iterations);
812  
813 73 my $request = $self->build_tool_chat_request($conversation, $formatted_tools);
814 73 my $response = await $self->_async_do_request_f(request => $request);
815  
816 # A failed response records its rate limit before the die, as in chat_f
817 # (karr k300); a success does it in parse_response.
818 73 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 2 71 73
819 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
820 2 die $self->_request_failed_message( $response, 'tool chat request' );
821 }
822  
823 71 my $reply = $self->_tool_loop_response($response);
824 62 my ( $calls, $data ) = $self->_tool_loop_calls( $reply, $reply->raw );
825 57 my @tool_calls = @$calls;
826  
827 # No tool calls means the LLM is done — return final text
828 57 ▶ return $reply->content unless @tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless @tool_calls 33 24 57
829  
830 # Execute each tool call via the appropriate MCP server
831 24 my @results;
832 24 for my $tc (@tool_calls) {
833 31 my ( $name, $input ) = ( $tc->name, $tc->arguments );
834  
835 # A name no server offers is answered with an error result, so the
836 # batch runs to the end and the model can correct itself (k332).
837 31 my $mcp = $tool_server_map->{$name};
838 31 ▶ unless ($mcp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($mcp) 3 28 31
839 3 push @results, { tool_call => $tc, result => _unknown_tool_result($name) };
840 3 next;
841 }
842 28 ▶ if ( my $bad = _undecodable_arguments_result($tc) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bad = _undecodable_arguments_result($tc)) 3 25 28
843 3 push @results, { tool_call => $tc, result => $bad };
844 3 next;
845 }
846  
847 25 $log->debugf("[%s] Calling tool: %s", ref $self, $name);
848  
849 0 ▶ my $result = await $mcp->call_tool($name, $input)->else(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
850 0 my ( $error ) = @_;
851 0 Future->done({
852 content => [{ type => 'text', text => "Error calling tool '$name': $error" }],
853 isError => JSON->true,
854 });
855 25 });
856  
857 25 push @results, { tool_call => $tc, result => $result };
858 }
859  
860 # Append assistant message and tool results to conversation
861 24 push @$conversation, $self->format_tool_results($data, \@results);
862 }
863  
864 0 die "Tool calling loop exceeded ".$self->tool_max_iterations." iterations";
865 197 }
866  
867  
868  
869 197 1;
870  
871 __END__
« blib/lib/Langertha/Role/ResponseFormat.pm ↑ Summary blib/lib/Langertha/Tool.pm »