blib/lib/Langertha/ToolCall.pm

filter: Statementstmt 98.6% 151 / 153 Branchbran 76.6% 69 / 90 Conditioncond 66.1% 45 / 68 MC/DCmcdc 34.2% 12 / 35 Subroutinesub 96.4% 27 / 28 Podpod 25.0% 4 / 16 totaltotal 78.9% 308 / 390 CC 80 SCAR 23.4
CC
80
Cov
85%
locate
27.1
from_ollama
7.9
from_responses
7.8
CRAP 10.4
« blib/lib/Langertha/Role/ThinkTag.pm ↑ Summary blib/lib/Langertha/Runtime/Metrics/OTLP.pm »
1 package Langertha::ToolCall;
2 # ABSTRACT: Immutable canonical tool invocation emitted by an LLM
3 190 our $VERSION = '0.503';
4 190 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 190 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 190 ▶use Encode qw( encode_utf8 );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 190 ▶use JSON::MaybeXS qw( decode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Character-string codec for JSON nested inside a JSON body or model text
10 # (function.arguments, the hermes <tool_call> payload). The transport encodes
11 # the whole body to UTF-8 once; a byte string here would be encoded twice
12 # ("Köln" -> "Köln"). -- karr k252, ADR 0010
13 190 my $TEXT_JSON = JSON::MaybeXS->new( utf8 => 0, canonical => 1 );
14  
15 190 has name => (
16 is => 'ro',
17 isa => 'Str',
18 required => 1,
19 );
20  
21 has arguments => (
22 is => 'ro',
23 isa => 'HashRef',
24 0 ▶ default => sub { {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
25 190 );
26  
27 # Provider-specific call id (may be empty if the upstream didn't supply one).
28 190 has id => (
29 is => 'ro',
30 isa => 'Str',
31 default => '',
32 );
33  
34 # True when this call was synthesized by Langertha (e.g. forced-tool
35 # rewrite via response_format on engines without native named-tool
36 # forcing) rather than emitted directly by the model. Useful for
37 # callers that want to distinguish "the model decided to call this"
38 # from "we asked it to and parsed the result back into a tool_call".
39 190 has synthetic => (
40 is => 'ro',
41 isa => 'Bool',
42 default => 0,
43 );
44  
45  
46 # True when the wire sent arguments (a string or a non-object) that do not
47 # decode to an object -- a JSON string cut off by max_tokens, for one. The
48 # arguments are {} then, and the tool loops must not run the call on them
49 # (karr k324).
50 190 has arguments_undecodable => (
51 is => 'ro',
52 isa => 'Bool',
53 default => 0,
54 );
55  
56  
57 # Why the arguments did not decode: the JSON parser's message, or "not a JSON
58 # object". Set exactly when arguments_undecodable is (karr k345).
59 190 has arguments_error => (
60 is => 'ro',
61 isa => 'Str',
62 predicate => 'has_arguments_error',
63 );
64  
65  
66 # The constructor arguments for one raw arguments value: the decoded object
67 # ({} when there is none) plus arguments_undecodable when the value does not
68 # decode to an object. Argument strings reach us as Perl-Unicode (pulled out of
69 # an already-decoded response tree), so UTF-8-encode before the utf8 JSON
70 # decoder — same convention as Role::JSON's decode_json_text.
71 442 ▶sub _args_kwargs {
Subroutine _args_kwargs: called CC=7 SCAR=19.5
72 442 my ($args) = @_;
73 442 ▶ return ( arguments => {} ) unless defined $args;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args 1 441 442
74 441 ▶ return ( arguments => $args ) if ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $args eq "HASH" 229 212 441
75 212 ▶ return _undecodable('not a JSON object') if ref $args;
Branch: 1 branch
BranchTrueFalseTotal
if ref $args 10 202 212
76 202 ▶ return ( arguments => {} ) unless length $args;
Branch: 1 branch
BranchTrueFalseTotal
unless length $args 1 201 202
77 201 my $decoded = eval { decode_json( encode_utf8($args) ) };
78 201 ▶ return ( arguments => $decoded ) if ref($decoded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $decoded eq "HASH" 151 50 201
79 50 my $error = $@;
80 50 ▶ return _undecodable('not a JSON object') unless $error;
Branch: 1 branch
BranchTrueFalseTotal
unless $error 1 49 50
81 49 $error =~ s/ at \S+ line \d+\.?\n?\z//;
82 49 return _undecodable($error);
83 }
84  
85 60 ▶sub _undecodable {
Subroutine _undecodable: called CC=1 SCAR=0.0
86 60 my ($error) = @_;
87 60 return ( arguments => {}, arguments_undecodable => 1, arguments_error => $error );
88 }
89  
90 # --- Constructors from wire-format hashes ---
91  
92 129 ▶sub from_openai {
Subroutine from_openai: called CC=7 SCAR=20.1
Pod undocumented
93 129 my ($class, $hash) = @_;
94 129 ▶ return undef unless ref($hash) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hash eq "HASH" 0 129 129
95 129 ▶ my $fn = $hash->{function} || {};
Condition50%1/2
$hash->{'function'} || {}
l!l
1290
MC/DC0%0/1
$hash->{'function'} || {}
$hash->{'function'}
Truth table50%1/2
A
A= $hash->{'function'}
Aresult
11
00
96 129 ▶ return undef unless ref($fn) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fn eq "HASH" 0 129 129
97 129 ▶ my $name = $fn->{name} // '';
Condition100%2/2
$fn->{"name"} // ""
l!l
1272
MC/DC100%1/1
$fn->{"name"} // ""
$fn->{"name"}
Truth table100%2/2
A
A= $fn->{"name"}
Aresult
11
00
98 129 ▶ return undef unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 2 127 129
99 return $class->new(
100 name => $name,
101 _args_kwargs( $fn->{arguments} ),
102 127 ▶ id => ( $hash->{id} // '' ),
Condition50%1/2
$hash->{"id"} // ""
l!l
1270
MC/DC0%0/1
$hash->{"id"} // ""
$hash->{"id"}
Truth table50%1/2
A
A= $hash->{"id"}
Aresult
11
00
103 );
104 }
105  
106 44 ▶sub from_anthropic {
Subroutine from_anthropic: called CC=7 SCAR=20.2
Pod undocumented
107 44 my ($class, $block) = @_;
108 44 ▶ return undef unless ref($block) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $block eq "HASH" 0 44 44
109 44 ▶ return undef unless ( $block->{type} // '' ) eq 'tool_use';
Branch: 1 branch
BranchTrueFalseTotal
unless ($block->{"type"} // "") eq "tool_use" 0 44 44
Condition50%1/2
$block->{"type"} // ""
l!l
440
MC/DC0%0/1
$block->{"type"} // ""
$block->{"type"}
Truth table50%1/2
A
A= $block->{"type"}
Aresult
11
00
110 44 ▶ my $name = $block->{name} // '';
Condition100%2/2
$block->{"name"} // ""
l!l
422
MC/DC100%1/1
$block->{"name"} // ""
$block->{"name"}
Truth table100%2/2
A
A= $block->{"name"}
Aresult
11
00
111 44 ▶ return undef unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 2 42 44
112 # Real Anthropic ships input as an object, but the AKI.IO /anthropic shim
113 # ships it as a JSON string (like the OpenAI wire). Route input through the
114 # same decoder from_openai uses so a stringified object is decoded rather
115 # than silently dropped to {}. -- karr k124
116 return $class->new(
117 name => $name,
118 _args_kwargs( $block->{input} ),
119 42 ▶ id => ( $block->{id} // '' ),
Condition50%1/2
$block->{"id"} // ""
l!l
420
MC/DC0%0/1
$block->{"id"} // ""
$block->{"id"}
Truth table50%1/2
A
A= $block->{"id"}
Aresult
11
00
120 );
121 }
122  
123 12 ▶sub from_ollama {
Subroutine from_ollama: called CC=7 SCAR=20.7
Pod undocumented
124 12 my ($class, $hash) = @_;
125 12 ▶ return undef unless ref($hash) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hash eq "HASH" 0 12 12
126 12 ▶ my $fn = $hash->{function} || {};
Condition50%1/2
$hash->{'function'} || {}
l!l
120
MC/DC0%0/1
$hash->{'function'} || {}
$hash->{'function'}
Truth table50%1/2
A
A= $hash->{'function'}
Aresult
11
00
127 12 ▶ return undef unless ref($fn) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fn eq "HASH" 0 12 12
128 12 ▶ my $name = $fn->{name} // '';
Condition50%1/2
$fn->{"name"} // ""
l!l
120
MC/DC0%0/1
$fn->{"name"} // ""
$fn->{"name"}
Truth table50%1/2
A
A= $fn->{"name"}
Aresult
11
00
129 12 ▶ return undef unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 0 12 12
130 return $class->new(
131 name => $name,
132 _args_kwargs( $fn->{arguments} ),
133 12 ▶ id => ( $hash->{id} // '' ),
Condition100%2/2
$hash->{"id"} // ""
l!l
48
MC/DC100%1/1
$hash->{"id"} // ""
$hash->{"id"}
Truth table100%2/2
A
A= $hash->{"id"}
Aresult
11
00
134 );
135 }
136  
137 # Gemini: a single functionCall part inside candidates[0].content.parts[]:
138 # { "functionCall": { "name": "x", "args": { ... } } }
139 26 ▶sub from_gemini {
Subroutine from_gemini: called CC=6 SCAR=19.3
Pod undocumented
140 26 my ($class, $part) = @_;
141 26 ▶ return undef unless ref($part) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $part eq "HASH" 0 26 26
142 26 my $fc = $part->{functionCall};
143 26 ▶ return undef unless ref($fc) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fc eq "HASH" 0 26 26
144 26 ▶ my $name = $fc->{name} // '';
Condition50%1/2
$fc->{"name"} // ""
l!l
260
MC/DC0%0/1
$fc->{"name"} // ""
$fc->{"name"}
Truth table50%1/2
A
A= $fc->{"name"}
Aresult
11
00
145 26 ▶ return undef unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 0 26 26
146 # Google-native ships args as an object, but Vertex-style proxies / OpenRouter
147 # / LM Studio can ship it as a JSON string. Route args through the same decoder
148 # the other constructors use so a stringified object is decoded rather than
149 # silently dropped to {}. -- karr k131 (symmetric to k124's from_anthropic fix)
150 return $class->new(
151 name => $name,
152 _args_kwargs( $fc->{args} ),
153 26 ▶ id => ( $fc->{id} // '' ),
Condition50%1/2
$fc->{"id"} // ""
l!l
026
MC/DC0%0/1
$fc->{"id"} // ""
$fc->{"id"}
Truth table50%1/2
A
A= $fc->{"id"}
Aresult
11
00
154 );
155 }
156  
157 # OpenAI Responses API: function_call appears either as a top-level output[]
158 # item or nested inside output[type=message].content[]. Both shapes look like:
159 # { "type": "function_call", "call_id": "call_abc", "name": "foo", "arguments": "{...}" }
160 48 ▶sub from_responses {
Subroutine from_responses: called CC=7 SCAR=20.5
Pod undocumented
161 48 my ($class, $block) = @_;
162 48 ▶ return undef unless ref($block) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $block eq "HASH" 0 48 48
163 # locate('responses') pre-filters output[] items to function_call, and a
164 # located call passed to from_fmt may carry no type at all — only reject a
165 # block whose type is present AND wrong.
166 48 my $type = $block->{type};
167 48 ▶ return undef if defined $type && $type ne 'function_call';
Branch: 1 branch
BranchTrueFalseTotal
if defined $type and $type ne "function_call" 0 48 48
Condition66%2/3
defined $type and $type ne "function_call"
!ll&&!rl&&r
2460
MC/DC0%0/2
defined $type and $type ne "function_call"
defined $type $type ne "function_call"
Truth table66%2/3
A and B
A= defined $typeB= $type ne "function_call"
ABresult
0X0
100
111
168 48 ▶ my $name = $block->{name} // '';
Condition50%1/2
$block->{"name"} // ""
l!l
480
MC/DC0%0/1
$block->{"name"} // ""
$block->{"name"}
Truth table50%1/2
A
A= $block->{"name"}
Aresult
11
00
169 48 ▶ return undef unless length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 0 48 48
170 return $class->new(
171 name => $name,
172 _args_kwargs( $block->{arguments} ),
173 48 ▶ id => ( $block->{call_id} // '' ),
Condition100%2/2
$block->{"call_id"} // ""
l!l
462
MC/DC100%1/1
$block->{"call_id"} // ""
$block->{"call_id"}
Truth table100%2/2
A
A= $block->{"call_id"}
Aresult
11
00
174 );
175 }
176  
177 # Maps a tool_wire_format tag to the per-call constructor.
178 190 my %FROM_METHOD = (
179 openai => 'from_openai',
180 anthropic => 'from_anthropic',
181 gemini => 'from_gemini',
182 ollama => 'from_ollama',
183 responses => 'from_responses',
184 );
185  
186 # Construct a single ToolCall from one raw wire-format call hash, pinned to a
187 # format (no shape sniffing). Returns undef if the hash doesn't parse.
188 208 ▶sub from_fmt {
Subroutine from_fmt: called CC=4 SCAR=14.3
Pod undocumented
189 208 my ($class, $fmt, $hash) = @_;
190 208 ▶ my $method = $FROM_METHOD{ $fmt // '' }
Branch: 1 branch
BranchTrueFalseTotal
my $method = $FROM_METHOD{$fmt // ""} or croak(q[Langertha::ToolCall: unknown wire format '] . ($fmt // "") . q[']) 207 1 208
Condition50%2/4
$fmt // ""
l!l
2080
$fmt // ""
l!l
10
MC/DC0%0/1
$fmt // ""
$fmt
MC/DC0%0/1
$fmt // ""
$fmt
Truth table50%1/2
A
A= $fmt
Aresult
11
00
Truth table50%1/2
A
A= $fmt
Aresult
11
00
191 or croak "Langertha::ToolCall: unknown wire format '" . ( $fmt // '' ) . "'";
192 207 return $class->$method($hash);
193 }
194  
195 # Locate the raw tool-call structures inside an upstream response for a given
196 # format, WITHOUT parsing them into objects. Returns an arrayref of raw hashes
197 # (possibly empty). This is the per-format locator that engines used to carry
198 # as response_tool_calls.
199 688 ▶sub locate {
Subroutine locate: called CC=25 SCAR=33.0
Pod documented
200 688 my ($class, $fmt, $data) = @_;
201 688 ▶ $fmt //= '';
Condition50%1/2
$fmt //= ""
l!l
6880
MC/DC0%0/1
$fmt //= ""
$fmt
Truth table50%1/2
A
A= $fmt
Aresult
11
00
202 688 ▶ return [] unless ref($data) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 688 688
203  
204 688 ▶ if ( $fmt eq 'openai' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "openai") 398 290 688
205 398 ▶ my $msg = $data->{choices}[0]{message} or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $msg = $data->{"choices"}[0]{"message"} or return [] 397 1 398
206 397 ▶ return $msg->{tool_calls} // [];
Condition100%2/2
$msg->{"tool_calls"} // []
l!l
85312
MC/DC100%1/1
$msg->{"tool_calls"} // []
$msg->{"tool_calls"}
Truth table100%2/2
A
A= $msg->{"tool_calls"}
Aresult
11
00
207 }
208 290 ▶ if ( $fmt eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "ollama") 73 217 290
209 73 ▶ my $msg = $data->{message} or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $msg = $data->{"message"} or return [] 73 0 73
210 73 ▶ return $msg->{tool_calls} // [];
Condition100%2/2
$msg->{"tool_calls"} // []
l!l
1261
MC/DC100%1/1
$msg->{"tool_calls"} // []
$msg->{"tool_calls"}
Truth table100%2/2
A
A= $msg->{"tool_calls"}
Aresult
11
00
211 }
212 217 ▶ if ( $fmt eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "anthropic") 91 126 217
213 91 ▶ return [ grep { ( $_->{type} // '' ) eq 'tool_use' } @{ $data->{content} // [] } ];
Condition75%3/4
$_->{"type"} // ""
l!l
1190
$data->{"content"} // []
l!l
901
MC/DC0%0/1
$_->{"type"} // ""
$_->{"type"}
MC/DC100%1/1
$data->{"content"} // []
$data->{"content"}
Truth table50%1/2
A
A= $_->{"type"}
Aresult
11
00
Truth table100%2/2
A
A= $data->{"content"}
Aresult
11
00
214 }
215 126 ▶ if ( $fmt eq 'gemini' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "gemini") 111 15 126
216 111 ▶ my $candidates = $data->{candidates} || [];
Condition100%2/2
$data->{'candidates'} || []
l!l
1029
MC/DC100%1/1
$data->{'candidates'} || []
$data->{'candidates'}
Truth table100%2/2
A
A= $data->{'candidates'}
Aresult
11
00
217 111 ▶ return [] unless @$candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @$candidates 9 102 111
218 102 ▶ my $parts = $candidates->[0]{content}{parts} || [];
Condition50%1/2
$candidates->[0]{'content'}{'parts'} || []
l!l
1020
MC/DC0%0/1
$candidates->[0]{'content'}{'parts'} || []
$candidates->[0]{'content'}{'parts'}
Truth table50%1/2
A
A= $candidates->[0]{'content'}{'parts'}
Aresult
11
00
219 102 return [ grep { exists $_->{functionCall} } @$parts ];
220 }
221 15 ▶ if ( $fmt eq 'responses' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "responses") 15 0 15
222 # Server-side call items (web_search_call, mcp_call, ...) are never located:
223 # the provider already ran them (ADR 0003 Update k206). A client-actionable
224 # item Langertha cannot map croaks instead of being skipped (ADR 0030).
225 15 require Langertha::Tool;
226 15 my @calls;
227 15 ▶ for my $item ( @{ $data->{output} // [] } ) {
Condition50%1/2
$data->{"output"} // []
l!l
150
MC/DC0%0/1
$data->{"output"} // []
$data->{"output"}
Truth table50%1/2
A
A= $data->{"output"}
Aresult
11
00
228 24 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 24 24
229 24 Langertha::Tool->_croak_on_client_item($item);
230 18 ▶ my $type = $item->{type} // '';
Condition50%1/2
$item->{"type"} // ""
l!l
180
MC/DC0%0/1
$item->{"type"} // ""
$item->{"type"}
Truth table50%1/2
A
A= $item->{"type"}
Aresult
11
00
231 18 ▶ if ( $type eq 'function_call' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'function_call') { } 7 11 18
elsif ($type eq 'message') { } 8 3 11
232 7 push @calls, $item;
233 }
234 elsif ( $type eq 'message' ) {
235 push @calls,
236 8 ▶ grep { ( $_->{type} // '' ) eq 'function_call' } @{ $item->{content} // [] };
Condition50%2/4
$_->{"type"} // ""
l!l
80
$item->{"content"} // []
l!l
80
MC/DC0%0/1
$_->{"type"} // ""
$_->{"type"}
MC/DC0%0/1
$item->{"content"} // []
$item->{"content"}
Truth table50%1/2
A
A= $_->{"type"}
Aresult
11
00
Truth table50%1/2
A
A= $item->{"content"}
Aresult
11
00
237 }
238 }
239 9 return \@calls;
240 }
241 0 croak "Langertha::ToolCall: unknown wire format '$fmt'";
242 }
243  
244  
245 # THE canonical inbound entry point: pull every tool call out of an upstream
246 # response for a given wire format (locate + from_fmt). Engines pass their
247 # tool_wire_format. Returns a list of ToolCall objects (possibly empty). The
248 # per-format response-walking lives only in locate(). Callers with no format
249 # in scope use extract_sniff() instead.
250 652 ▶sub extract {
Subroutine extract: called CC=2 SCAR=6.9
Pod documented
251 652 my ( $class, $fmt, $data ) = @_;
252 652 ▶ croak "Langertha::ToolCall->extract requires (\$fmt, \$data)" if ref $fmt;
Branch: 1 branch
BranchTrueFalseTotal
if ref $fmt 1 651 652
253 168 return grep { defined }
254 651 map { $class->from_fmt( $fmt, $_ ) } @{ $class->locate( $fmt, $data ) };
255 }
256  
257  
258 # Detect the wire format from the top-level shape of a raw response, WITHOUT
259 # walking the per-format tool structures (that walking lives only in locate).
260 # Probe order matches the legacy self-sniffing extract. Returns a
261 # tool_wire_format tag, or undef if the shape matches nothing known.
262 my @SNIFF_PROBES = (
263 16 ▶ [ openai => sub { ref( $_[0]->{choices} ) eq 'ARRAY' } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
264 11 ▶ [ ollama => sub { ref( $_[0]->{message} ) eq 'HASH' } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
265 9 ▶ [ anthropic => sub { ref( $_[0]->{content} ) eq 'ARRAY' } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
266 6 ▶ [ gemini => sub { ref( $_[0]->{candidates} ) eq 'ARRAY' } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
267 4 ▶ [ responses => sub { ref( $_[0]->{output} ) eq 'ARRAY' } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
268 );
269  
270 16 ▶sub sniff_format {
Subroutine sniff_format: called CC=4 SCAR=13.9
Pod undocumented
271 16 my ( $class, $data ) = @_;
272 16 ▶ return undef unless ref($data) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 16 16
273 16 for my $probe (@SNIFF_PROBES) {
274 46 ▶ return $probe->[0] if $probe->[1]->($data);
Branch: 1 branch
BranchTrueFalseTotal
if $probe->[1]->($data) 14 32 46
275 }
276 2 return undef;
277 }
278  
279 # Format-agnostic inbound for callers that genuinely have no wire format in
280 # scope (the Langertha::Output::Tools back-compat facade): sniff the shape,
281 # then delegate to extract. Deliberately NOT named extract() so there is
282 # exactly one canonical inbound entry point — the format-pinned extract above.
283 10 ▶sub extract_sniff {
Subroutine extract_sniff: called CC=2 SCAR=6.9
Pod documented
284 10 my ( $class, $data ) = @_;
285 10 ▶ my $fmt = $class->sniff_format($data) or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $fmt = $class->sniff_format($data) or return () 9 1 10
286 9 return $class->extract( $fmt, $data );
287 }
288  
289  
290 # Hermes-style XML embedded in plain text. Returns ($cleaned_text, \@calls).
291 # The one hermes text lift: Role::Tools delegates here with the engine's
292 # hermes_call_tag (karr k255). Only a well-formed call (a JSON object with a
293 # non-empty name) becomes a ToolCall and leaves the text (k163); a block that
294 # carries no call stays in the text where it was -- what the model wrote is
295 # not dropped (k253).
296 258 ▶sub extract_hermes_from_text {
Subroutine extract_hermes_from_text: called CC=7 SCAR=19.5
Pod documented
297 258 my ( $class, $text, %opts ) = @_;
298 258 ▶ my $tag = defined $opts{tag} && length $opts{tag} ? $opts{tag} : 'tool_call';
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'tag'} && length $opts{'tag'} ? : 237 21 258
Condition66%2/3
defined $opts{"tag"} and length $opts{"tag"}
!ll&&!rl&&r
210237
MC/DC50%1/2
defined $opts{"tag"} and length $opts{"tag"}
defined $opts{"tag"} length $opts{"tag"}
Truth table66%2/3
A and B
A= defined $opts{"tag"}B= length $opts{"tag"}
ABresult
0X0
100
111
299 258 ▶ my $clean = defined($text) ? $text : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 258 0 258
300 258 my @calls;
301 258 $clean =~ s{(<\Q$tag\E>\s*(.*?)\s*</\Q$tag\E>)}{
302 225 my ( $block, $json ) = ( $1, $2 );
303 225 my $obj = eval { $TEXT_JSON->decode($json) };
304 ( ref($obj) eq 'HASH' && defined $obj->{name} && length $obj->{name} )
305 225 ▶ ? do {
Branch: 1 branch
BranchTrueFalseTotal
ref $obj eq 'HASH' && defined $obj->{'name'} && length $obj->{'name'} ? : 187 38 225
Condition100%6/6
ref $obj eq "HASH" and defined $obj->{"name"} and length $obj->{"name"}
!ll&&!rl&&r
353187
ref $obj eq "HASH" and defined $obj->{"name"}
!ll&&!rl&&r
269190
MC/DC100%3/3
ref $obj eq "HASH" and defined $obj->{"name"} and length $obj->{"name"}
ref $obj eq "HASH" defined $obj->{"name"} length $obj->{"name"}
Truth table100%4/4
A and B and C
A= ref $obj eq "HASH"B= defined $obj->{"name"}C= length $obj->{"name"}
ABCresult
0XX0
10X0
1100
1111
306 # Route arguments through the same decoder the wire constructors use
307 # (from_openai & co.): a non-object or a value that does not decode to
308 # an object becomes {} with arguments_undecodable / arguments_error
309 # set, so the tool loop answers the model an error result it can retry
310 # rather than running the tool on {} -- karr k350 (the k345 mechanism).
311 push @calls, $class->new(
312 name => $obj->{name},
313 187 _args_kwargs( $obj->{arguments} ),
314 );
315 187 '';
316 }
317 : $block;
318 }seg;
319 258 $clean =~ s/^\s+|\s+$//g;
320 258 return ( $clean, \@calls );
321 }
322  
323  
324 # --- Serializers to wire-format hashes ---
325  
326 5 ▶sub to_openai {
Subroutine to_openai: called CC=3 SCAR=11.1
Pod undocumented
327 5 my ($self, %opts) = @_;
328 5 ▶ my $id = length( $self->id ) ? $self->id : ( $opts{fallback_id} // 'call_langertha' );
Branch: 1 branch
BranchTrueFalseTotal
length $self->id ? : 4 1 5
Condition50%1/2
$opts{"fallback_id"} // "call_langertha"
l!l
10
MC/DC0%0/1
$opts{"fallback_id"} // "call_langertha"
$opts{"fallback_id"}
Truth table50%1/2
A
A= $opts{"fallback_id"}
Aresult
11
00
329 return {
330 5 id => $id,
331 type => 'function',
332 function => {
333 name => $self->name,
334 arguments => $TEXT_JSON->encode( $self->arguments ),
335 },
336 };
337 }
338  
339 2 ▶sub to_anthropic_block {
Subroutine to_anthropic_block: called CC=3 SCAR=13.1
Pod undocumented
340 2 my ($self, %opts) = @_;
341 2 ▶ my $id = length( $self->id ) ? $self->id : ( $opts{fallback_id} // 'toolu_langertha' );
Branch: 1 branch
BranchTrueFalseTotal
length $self->id ? : 2 0 2
Condition0%0/2
$opts{"fallback_id"} // "toolu_langertha"
l!l
00
MC/DC0%0/1
$opts{"fallback_id"} // "toolu_langertha"
$opts{"fallback_id"}
Truth table0%0/2
A
A= $opts{"fallback_id"}
Aresult
11
00
342 return {
343 2 type => 'tool_use',
344 id => $id,
345 name => $self->name,
346 input => $self->arguments,
347 };
348 }
349  
350 3 ▶sub to_ollama {
Subroutine to_ollama: called CC=2 SCAR=7.2
Pod undocumented
351 3 my ($self) = @_;
352 return {
353 3 ▶ function => {
Branch: 1 branch
BranchTrueFalseTotal
length $self->id ? : 3 0 3
354 name => $self->name,
355 arguments => $self->arguments,
356 },
357 ( length( $self->id ) ? ( id => $self->id ) : () ),
358 };
359 }
360  
361 42 ▶sub to_hash {
Subroutine to_hash: called CC=2 SCAR=6.9
Pod undocumented
362 42 my ($self) = @_;
363 return {
364 42 ▶ id => $self->id,
Branch: 1 branch
BranchTrueFalseTotal
$self->synthetic ? : 2 40 42
365 name => $self->name,
366 arguments => $self->arguments,
367 synthetic => $self->synthetic ? 1 : 0,
368 };
369 }
370  
371 # Make the object transparent to any JSON encoder configured with
372 # convert_blessed => 1 (the house default, see Langertha::Plugin::Langfuse).
373 # Response.tool_calls is an ArrayRef of these, so consumers hit them without
374 # ever asking for a ToolCall by name. Plain delegator to to_hash: TO_JSON must
375 # not become a second, divergent shape.
376 4 ▶sub TO_JSON { shift->to_hash }
Subroutine TO_JSON: called CC=1 SCAR=0.0
Pod undocumented
377  
378 190 __PACKAGE__->meta->make_immutable;
379 190 1;
380  
381 __END__
382  
383 =pod
384  
385 =encoding UTF-8
386  
387 =head1 NAME
388  
389 Langertha::ToolCall - Immutable canonical tool invocation emitted by an LLM
390  
391 =head1 VERSION
392  
393 version 0.503
394  
395 =head2 synthetic
396  
397 Boolean. True when the tool call was synthesized by Langertha — for
398 example when L<Langertha::Role::Chat/chat_f> rewrote a forced named
399 tool into a C<response_format> JSON Schema request and parsed the
400 output back into a C<ToolCall>. False (the default) for native model
401 output.
402  
403 C<to_hash> (and therefore C<TO_JSON>) always carries this flag, so a
404 serialized trace can tell a synthesized call apart from a native one —
405 without it a forced-tool fallback would look exactly like a call the
406 model decided to make.
407  
408 =head2 arguments_undecodable
409  
410 Boolean. True when the provider sent arguments that do not decode to a JSON
411 object (typically a JSON string cut off when the reply hit its token limit);
412 L</arguments> is then C<{}>. The MCP tool loops do not run such a call: when
413 the reply ended on its token limit they drop it, otherwise they answer it with
414 an error result naming L</arguments_error>. Missing or empty arguments are not
415 undecodable.
416  
417 =head2 arguments_error
418  
419 The reason the arguments did not decode, set whenever
420 L</arguments_undecodable> is true: the JSON parser's message (without its
421 source location) or C<not a JSON object>.
422  
423 =head2 locate
424  
425 my $raw_calls = Langertha::ToolCall->locate( $fmt, $data );
426  
427 Returns an ArrayRef of the raw tool-call structures in a decoded response for
428 the wire C<$fmt>, without parsing them. Only calls the client must execute are
429 located; a server-side call item (C<web_search_call>, C<mcp_call>, ...) never
430 is (see L<Langertha::ServerToolCall>). On C<responses> it croaks on an output
431 item the client must answer that Langertha does not map --
432 C<custom_tool_call>, C<computer_call>, C<local_shell_call>,
433 C<apply_patch_call>, C<mcp_approval_request>, a C<tool_search_call> with
434 C<< execution => 'client' >> -- rather than report no calls. Croaks on an
435 unknown C<$fmt>.
436  
437 =head2 extract
438  
439 my @calls = Langertha::ToolCall->extract( $fmt, $data );
440  
441 The canonical inbound door: every tool call the client must execute in a
442 decoded response, as C<Langertha::ToolCall> objects (possibly none). Built on
443 L</locate>, so on the C<responses> wire it B<croaks> on a client-actionable
444 output item Langertha cannot map (C<mcp_approval_request>, C<computer_call>,
445 C<custom_tool_call>, C<local_shell_call>, C<apply_patch_call>, a client
446 C<tool_search_call>) instead of returning an empty list that looks like "the
447 model is done". Croaks when C<$fmt> is a reference.
448  
449 =head2 extract_sniff
450  
451 my @calls = Langertha::ToolCall->extract_sniff( $data );
452  
453 L</extract> for a caller with no wire format in scope: sniffs the format from
454 the top-level shape, then extracts. Returns an empty list for an unknown shape.
455 Croaks like L</extract>, including on a client-actionable C<responses> item.
456  
457 =head2 extract_hermes_from_text
458  
459 my ( $clean, $calls ) = Langertha::ToolCall->extract_hermes_from_text($text);
460 my ( $clean, $calls ) = Langertha::ToolCall->extract_hermes_from_text(
461 $text, tag => 'function_call' );
462  
463 Lifts Hermes-style C<< <tool_call>{"name":...,"arguments":{...}}</tool_call> >>
464 blocks out of model text. Returns the trimmed text without the lifted blocks
465 and an ArrayRef of C<Langertha::ToolCall>. C<tag> names the call tag (default
466 C<tool_call>); engines pass their C<hermes_call_tag>. A block that carries no
467 call (invalid JSON, a non-object, an object without a C<name>) stays in the
468 text where it was. C<arguments> that are not a JSON object (or a string that
469 does not decode to one) become C<{}> with L</arguments_undecodable> and
470 L</arguments_error> set, exactly as the wire constructors flag them.
471  
472 =head1 SUPPORT
473  
474 =head2 Issues
475  
476 Please report bugs and feature requests on GitHub at
477 L<https://github.com/Getty/langertha/issues>.
478  
479 =head2 IRC
480  
481 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
482  
483 =head1 CONTRIBUTING
484  
485 Contributions are welcome! Please fork the repository and submit a pull request.
486  
487 =head1 AUTHOR
488  
489 Torsten Raudssus <getty@cpan.org>
490  
491 =head1 COPYRIGHT AND LICENSE
492  
493 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
494  
495 This is free software; you can redistribute it and/or modify it under
496 the same terms as the Perl 5 programming language system itself.
497  
498 =cut
« blib/lib/Langertha/Role/ThinkTag.pm ↑ Summary blib/lib/Langertha/Runtime/Metrics/OTLP.pm »