blib/lib/Langertha/Role/Chat.pm

filter: Statementstmt 86.7% 575 / 663 Branchbran 75.4% 344 / 456 Conditioncond 62.7% 261 / 416 MC/DCmcdc 48.0% 108 / 225 Subroutinesub 86.0% 68 / 79 Podpod 100% 18 / 18 totaltotal 73.9% 1374 / 1857 CC 575 SCAR 35.7
CC
575
Cov
77%
_normalize_content_blocks
233.3
_normalize_content_blocks
233.3
chat_f
38.7
CRAP 35.6
« blib/lib/Langertha/Engine/LMStudio.pm ↑ Summary blib/lib/Langertha/Role/ThinkTag.pm »
1 package Langertha::Role::Chat;
2 # ABSTRACT: Role for APIs with normal chat functionality
3 194 our $VERSION = '0.505';
4 194 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 194 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 194 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 194 ▶use Carp qw( carp croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 194 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 194 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 194 ▶use Scalar::Util qw( blessed refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 194 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 194 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 194 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 194 ▶use Langertha::ServerTool;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 194 ▶use Langertha::Role::Capabilities;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 194 requires qw(
18 chat_request
19 chat_response
20 );
21  
22  
23 # Defaults to the OpenAI dialect; AnthropicBase (via AnthropicCompatible),
24 # ResponsesCompatible, Engine::Gemini, Engine::Ollama and Engine::LMStudio
25 # override it. The POD =method above documents the same override points from
26 # the engine-user perspective.
27 551 ▶sub content_format { 'openai' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod documented
28  
29 # Internal wire truth, deliberately not a capability flag (karr k267): true on
30 # engines whose endpoint rejects remote image URLs (base64 / data: URLs only).
31 # URL-sourced Content::Image blocks are then inlined -- fetched, as to_gemini
32 # always does -- before serialization, and a failed fetch croaks before any
33 # request is sent.
34 630 ▶sub _content_inline_images_only { 0 }
Subroutine _content_inline_images_only: called CC=1 SCAR=0.0
35  
36  
37 194 with 'Langertha::Role::Capabilities';
38  
39  
40 194 has chat_model => (
41 is => 'ro',
42 isa => 'Maybe[Str]',
43 lazy_build => 1,
44 );
45 3359 ▶sub _build_chat_model {
Subroutine _build_chat_model: called CC=3 SCAR=16.5
46 0 ▶ my ( $self ) = @_;
Subroutine _build_chat_model: not called CC=3 SCAR=16.5
47 0 ▶ croak "".(ref $self)." can't handle models!" unless $self->does('Langertha::Role::Models');
Branch: 2 branches
BranchTrueFalseTotal
unless $self->does("Langertha::Role::Models") 0 3359 3359
unless $self->does("Langertha::Role::Models") 0 0 0
48 0 ▶ return $self->default_chat_model if $self->can('default_chat_model');
Branch: 2 branches
BranchTrueFalseTotal
if $self->can("default_chat_model") 0 3359 3359
if $self->can("default_chat_model") 0 0 0
49 0 return $self->model;
50 }
51  
52  
53 # Adds a key/value pair into an existing timing hashref (or new one).
54 # Used to layer client-measured ttft_seconds / total_seconds onto a
55 # Response that may already carry provider-native stages (e.g. Ollama's
56 # *_seconds). Never overwrites an existing key — first-write-wins so a
57 # provider-supplied duration (e.g. Ollama's total_seconds) trumps the
58 # client measurement.
59 323 ▶sub _merge_timing_field {
Subroutine _merge_timing_field: called CC=3 SCAR=16.5
60 0 ▶ my ( $existing, $key, $value ) = @_;
Subroutine _merge_timing_field: not called CC=3 SCAR=16.5
61 0 ▶ my $t = $existing ? { %$existing } : {};
Branch: 2 branches
BranchTrueFalseTotal
$existing ? : 0 323 323
$existing ? : 0 0 0
62 0 ▶ $t->{$key} = $value unless exists $t->{$key};
Branch: 2 branches
BranchTrueFalseTotal
unless exists $t->{$key} 323 0 323
unless exists $$t{$key} 0 0 0
63 0 return $t;
64 }
65  
66 298 ▶sub chat {
Subroutine chat: called CC=1 SCAR=1.2
Pod documented
67 0 ▶ my ( $self, @messages ) = @_;
Subroutine chat: not called CC=1 SCAR=1.2
Pod documented
68 0 return $self->chat_request($self->chat_messages(@messages));
69 }
70  
71  
72 1117 ▶sub chat_messages {
Subroutine chat_messages: called CC=3 SCAR=14.2
Pod documented
73 0 ▶ my ( $self, @messages ) = @_;
Subroutine chat_messages: not called CC=3 SCAR=14.2
Pod documented
74 0 $self->_warn_control_message_args(@messages);
75 0 my @out = $self->_system_messages;
76 0 for my $m (@messages) {
77 0 ▶ my $msg = ref $m ? $m : { role => 'user', content => $m };
Branch: 2 branches
BranchTrueFalseTotal
ref $m ? : 351 855 1206
ref $m ? : 0 0 0
78 0 push @out, $self->_normalize_content_blocks($msg);
79 }
80 0 return \@out;
81 }
82  
83 # The leading system messages this engine prepends to a conversation. An
84 # explicit $system_prompt replaces the engine's own system_prompt; engine
85 # prefixes (NousResearch's reasoning prompt) wrap this method and still apply.
86 # Shared by chat_messages and Langertha::Chat (karr k277).
87 1247 ▶sub _system_messages {
Subroutine _system_messages: called CC=4 SCAR=17.9
88 0 ▶ my ( $self, @override ) = @_;
Subroutine _system_messages: not called CC=4 SCAR=17.9
89 0 ▶ my $prompt = @override ? $override[0]
Branch: 4 branches
BranchTrueFalseTotal
@override ? : 17 1230 1247
$self->has_system_prompt ? : 57 1173 1230
@override ? : 0 0 0
$self->has_system_prompt ? : 0 0 0
90 : $self->has_system_prompt ? $self->system_prompt : undef;
91 0 ▶ return defined $prompt ? ( { role => 'system', content => $prompt } ) : ();
Branch: 2 branches
BranchTrueFalseTotal
defined $prompt ? : 74 1173 1247
defined $prompt ? : 0 0 0
92 }
93  
94 1336 ▶sub _normalize_content_blocks {
Subroutine _normalize_content_blocks: called CC=34 SCAR=54.5
95 0 ▶ my ( $self, $msg ) = @_;
Subroutine _normalize_content_blocks: not called CC=34 SCAR=54.5
96 0 my $content = $msg->{content};
97 0 ▶ return $msg unless ref $content eq 'ARRAY';
Branch: 2 branches
BranchTrueFalseTotal
unless ref $content eq "ARRAY" 1229 107 1336
unless ref $content eq "ARRAY" 0 0 0
98  
99 0 my $needs_convert = 0;
100 0 for my $b (@$content) {
101 0 ▶ if ( blessed($b) && $b->does('Langertha::Content') ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($b) and $b->does("Langertha::Content")) 72 114 186
if (builtin::blessed($b) and $b->does("Langertha::Content")) 0 0 0
Condition33%2/6
builtin::blessed($b) and $b->does("Langertha::Content")
!ll&&!rl&&r
114072
builtin::blessed($b) and $b->does("Langertha::Content")
!ll&&!rl&&r
000
MC/DC50%1/2
builtin::blessed($b) and $b->does("Langertha::Content")
builtin::blessed($b) $b->does("Langertha::Content")
MC/DC0%0/2
builtin::blessed($b) and $b->does("Langertha::Content")
builtin::blessed($b) $b->does("Langertha::Content")
Truth table66%2/3
A and B
A= builtin::blessed($b)B= $b->does("Langertha::Content")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= builtin::blessed($b)B= $b->does("Langertha::Content")
ABresult
0X0
100
111
102 0 $needs_convert = 1;
103 0 last;
104 }
105 }
106 0 my $fmt = $self->content_format;
107 # Gemini has no string-or-array content field: every array becomes parts,
108 # Content object or not (karr k269). Ollama native content is a string: a
109 # text-part array is joined, never sent as an array (karr k331).
110 0 ▶ return $msg unless $needs_convert || $fmt eq 'gemini' || $fmt eq 'ollama';
Branch: 2 branches
BranchTrueFalseTotal
unless $needs_convert or $fmt eq "gemini" or $fmt eq "ollama" 13 94 107
unless $needs_convert or $fmt eq "gemini" or $fmt eq "ollama" 0 0 0
Condition50%6/12
$needs_convert or $fmt eq "gemini" or $fmt eq "ollama"
l!l&&r!l&&!r
89513
$needs_convert or $fmt eq "gemini"
l!l&&r!l&&!r
721718
$needs_convert or $fmt eq "gemini" or $fmt eq "ollama"
l!l&&r!l&&!r
000
$needs_convert or $fmt eq "gemini"
l!l&&r!l&&!r
000
MC/DC100%3/3
$needs_convert or $fmt eq "gemini" or $fmt eq "ollama"
$needs_convert $fmt eq "gemini" $fmt eq "ollama"
MC/DC0%0/3
$needs_convert or $fmt eq "gemini" or $fmt eq "ollama"
$needs_convert $fmt eq "gemini" $fmt eq "ollama"
Truth table100%4/4
A or B or C
A= $needs_convertB= $fmt eq "gemini"C= $fmt eq "ollama"
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
A or B or C
A= $needs_convertB= $fmt eq "gemini"C= $fmt eq "ollama"
ABCresult
1XX1
01X1
0011
0000
111  
112 0 my $method = "to_$fmt";
113 0 ▶ my $role = $msg->{role} // 'user';
Condition25%1/4
$msg->{"role"} // "user"
l!l
940
$$msg{"role"} // "user"
l!l
00
MC/DC0%0/1
$msg->{"role"} // "user"
$msg->{"role"}
MC/DC0%0/1
$$msg{"role"} // "user"
$$msg{"role"}
Truth table50%1/2
A
A= $msg->{"role"}
Aresult
11
00
Truth table0%0/2
A
A= $$msg{"role"}
Aresult
11
00
114 # Only the URL-capable formats take the inline switch; gemini / ollama /
115 # lmstudio always inline.
116 0 ▶ my @opt = ( $self->_content_inline_images_only
Branch: 2 branches
BranchTrueFalseTotal
$self->_content_inline_images_only && ($fmt eq 'openai' || $fmt eq 'responses') ? : 20 74 94
$self->_content_inline_images_only && ($fmt eq 'openai' || $fmt eq 'responses') ? : 0 0 0
Condition41%5/12
$self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
!ll&&!rl&&r
67720
$fmt eq "openai" or $fmt eq "responses"
l!l&&r!l&&!r
2007
$self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
!ll&&!rl&&r
000
$fmt eq "openai" or $fmt eq "responses"
l!l&&r!l&&!r
000
MC/DC66%2/3
$self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
$self->_content_inline_images_only $fmt eq "openai" $fmt eq "responses"
MC/DC0%0/3
$self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
$self->_content_inline_images_only $fmt eq "openai" $fmt eq "responses"
Truth table75%3/4
A and B or C
A= $self->_content_inline_images_onlyB= $fmt eq "openai"C= $fmt eq "responses"
ABCresult
0XX0
1000
11X1
1011
Truth table0%0/4
A and B or C
A= $self->_content_inline_images_onlyB= $fmt eq "openai"C= $fmt eq "responses"
ABCresult
0XX0
1000
11X1
1011
117 && ( $fmt eq 'openai' || $fmt eq 'responses' ) ) ? ( inline => 1 ) : ();
118  
119 # Ollama native /api/chat: content is a string, images a sibling base64 array.
120 0 ▶ if ( $fmt eq 'ollama' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($fmt eq "ollama") 14 80 94
if ($fmt eq "ollama") 0 0 0
121 0 my ( @text, @images );
122 0 for my $part (@$content) {
123 0 ▶ if ( blessed($part) && $part->does('Langertha::Content') ) {
Branch: 8 branches
BranchTrueFalseTotal
if (builtin::blessed($part) and $part->does('Langertha::Content')) { } 8 18 26
elsif (not ref $part) { } 9 9 18
elsif (ref $part eq 'HASH' and ($part->{'type'} // '') eq 'text' and defined $part->{'text'}) { } 6 3 9
elsif (my $img = $self->_image_url_part_image($part)) { } 1 2 3
if (builtin::blessed($part) and $part->does('Langertha::Content')) { } 0 0 0
elsif (not ref $part) { } 0 0 0
elsif (ref $part eq 'HASH' and ($$part{'type'} // '') eq 'text' and defined $$part{'text'}) { } 0 0 0
elsif (my $img = $self->_image_url_part_image($part)) { } 0 0 0
Condition33%2/6
builtin::blessed($part) and $part->does("Langertha::Content")
!ll&&!rl&&r
1808
builtin::blessed($part) and $part->does("Langertha::Content")
!ll&&!rl&&r
000
MC/DC50%1/2
builtin::blessed($part) and $part->does("Langertha::Content")
builtin::blessed($part) $part->does("Langertha::Content")
MC/DC0%0/2
builtin::blessed($part) and $part->does("Langertha::Content")
builtin::blessed($part) $part->does("Langertha::Content")
Truth table66%2/3
A and B
A= builtin::blessed($part)B= $part->does("Langertha::Content")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= builtin::blessed($part)B= $part->does("Langertha::Content")
ABresult
0X0
100
111
124 0 push @images, $self->_content_block( $part, $method );
125 }
126 elsif ( !ref $part ) {
127 0 push @text, $part;
128 }
129 ▶ elsif ( ref $part eq 'HASH' && ( $part->{type} // '' ) eq 'text' && defined $part->{text} ) {
Condition31%5/16
ref $part eq "HASH" and ($part->{"type"} // "") eq "text" and defined $part->{"text"}
!ll&&!rl&&r
306
ref $part eq "HASH" and ($part->{"type"} // "") eq "text"
!ll&&!rl&&r
036
$part->{"type"} // ""
l!l
90
ref $part eq "HASH" and ($$part{"type"} // "") eq "text" and defined $$part{"text"}
!ll&&!rl&&r
000
ref $part eq "HASH" and ($$part{"type"} // "") eq "text"
!ll&&!rl&&r
000
$$part{"type"} // ""
l!l
00
MC/DC0%0/3
ref $part eq "HASH" and ($part->{"type"} // "") eq "text" and defined $part->{"text"}
ref $part eq "HASH" $part->{"type"} defined $part->{"text"}
MC/DC0%0/3
ref $part eq "HASH" and ($$part{"type"} // "") eq "text" and defined $$part{"text"}
ref $part eq "HASH" $$part{"type"} defined $$part{"text"}
Truth table25%1/4
A and B and C
A= ref $part eq "HASH"B= $part->{"type"}C= defined $part->{"text"}
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= ref $part eq "HASH"B= $$part{"type"}C= defined $$part{"text"}
ABCresult
0XX0
10X0
1100
1111
130 0 push @text, $part->{text};
131 }
132 elsif ( my $img = $self->_image_url_part_image($part) ) {
133 0 push @images, $self->_content_block( $img, $method );
134 }
135 else {
136 0 croak ref($self).": Ollama native /api/chat takes a string message content; "
137 . "a content part may be a string, a { type => 'text' } or { type => 'image_url' } hash "
138 . "or a Langertha::Content object";
139 }
140 }
141 return { %$msg, content => join( "\n", @text ),
142 ( @images || $msg->{images} )
143 0 ▶ ? ( images => [ @{ $msg->{images} // [] }, @images ] ) : () };
Branch: 2 branches
BranchTrueFalseTotal
@images || $msg->{'images'} ? : 6 3 9
@images || $$msg{'images'} ? : 0 0 0
Condition30%3/10
@images or $msg->{"images"}
l!l&&r!l&&!r
603
$msg->{"images"} // []
l!l
06
@images or $$msg{"images"}
l!l&&r!l&&!r
000
$$msg{"images"} // []
l!l
00
MC/DC50%1/2
@images or $msg->{"images"}
@images $msg->{"images"}
MC/DC0%0/1
$msg->{"images"} // []
$msg->{"images"}
MC/DC0%0/2
@images or $$msg{"images"}
@images $$msg{"images"}
MC/DC0%0/1
$$msg{"images"} // []
$$msg{"images"}
Truth table66%2/3
A or B
A= @imagesB= $msg->{"images"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $msg->{"images"}
Aresult
11
00
Truth table0%0/3
A or B
A= @imagesB= $$msg{"images"}
ABresult
1X1
011
000
Truth table0%0/2
A
A= $$msg{"images"}
Aresult
11
00
144 }
145  
146 0 ▶ my $text_type = $fmt ne 'responses' ? 'text'
Branch: 4 branches
BranchTrueFalseTotal
$fmt ne 'responses' ? : 73 7 80
$role eq 'assistant' ? : 2 5 7
$fmt ne 'responses' ? : 0 0 0
$role eq 'assistant' ? : 0 0 0
147 : $role eq 'assistant' ? 'output_text'
148 : 'input_text';
149  
150 my @blocks = map {
151 0 ▶ if ( blessed($_) && $_->does('Langertha::Content') ) {
Branch: 6 branches
BranchTrueFalseTotal
if (builtin::blessed($_) and $_->does('Langertha::Content')) { } 69 84 153
elsif (not ref $_) { } 57 27 84
elsif ($fmt eq 'gemini') { } 27 0 27
if (builtin::blessed($_) and $_->does('Langertha::Content')) { } 0 0 0
elsif (not ref $_) { } 0 0 0
elsif ($fmt eq 'gemini') { } 0 0 0
Condition33%2/6
builtin::blessed($_) and $_->does("Langertha::Content")
!ll&&!rl&&r
84069
builtin::blessed($_) and $_->does("Langertha::Content")
!ll&&!rl&&r
000
MC/DC50%1/2
builtin::blessed($_) and $_->does("Langertha::Content")
builtin::blessed($_) $_->does("Langertha::Content")
MC/DC0%0/2
builtin::blessed($_) and $_->does("Langertha::Content")
builtin::blessed($_) $_->does("Langertha::Content")
Truth table66%2/3
A and B
A= builtin::blessed($_)B= $_->does("Langertha::Content")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= builtin::blessed($_)B= $_->does("Langertha::Content")
ABresult
0X0
100
111
152 0 $self->_content_block( $_, $method, @opt );
153 }
154 elsif ( !ref $_ ) {
155 0 ▶ $fmt eq 'gemini'
Branch: 2 branches
BranchTrueFalseTotal
$fmt eq 'gemini' ? : 19 38 57
$fmt eq 'gemini' ? : 0 0 0
156 ? { text => $_ }
157 : { type => $text_type, text => $_ };
158 }
159 elsif ( $fmt eq 'gemini' ) {
160 0 $self->_gemini_part( $_, $method );
161 }
162 else {
163 0 $_;
164 }
165 } @$content;
166  
167 0 ▶ if ( $fmt eq 'gemini' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($fmt eq "gemini") 22 46 68
if ($fmt eq "gemini") 0 0 0
168 0 ▶ return { role => ( $role eq 'assistant' ? 'model' : $role ), parts => \@blocks };
Branch: 2 branches
BranchTrueFalseTotal
$role eq 'assistant' ? : 2 20 22
$role eq 'assistant' ? : 0 0 0
169 }
170 0 return { %$msg, content => \@blocks };
171 }
172  
173 # One hash part of a Gemini message. A part without `type` is already native
174 # (text, inline_data / inlineData, fileData / file_data, functionCall, ...) and
175 # passes through; the OpenAI-style text and image_url parts are translated, an
176 # image through Content::Image so it gets the same inline_data a Content object
177 # gets. Any other typed part has no Gemini counterpart and croaks (karr k269).
178 27 ▶sub _gemini_part {
Subroutine _gemini_part: called CC=6 SCAR=24.9
179 0 ▶ my ( $self, $part, $method ) = @_;
Subroutine _gemini_part: not called CC=6 SCAR=24.9
180 0 ▶ return $part unless ref $part eq 'HASH' && defined $part->{type};
Branch: 2 branches
BranchTrueFalseTotal
unless ref $part eq "HASH" and defined $part->{"type"} 12 15 27
unless ref $part eq "HASH" and defined $$part{"type"} 0 0 0
Condition33%2/6
ref $part eq "HASH" and defined $part->{"type"}
!ll&&!rl&&r
01215
ref $part eq "HASH" and defined $$part{"type"}
!ll&&!rl&&r
000
MC/DC50%1/2
ref $part eq "HASH" and defined $part->{"type"}
ref $part eq "HASH" defined $part->{"type"}
MC/DC0%0/2
ref $part eq "HASH" and defined $$part{"type"}
ref $part eq "HASH" defined $$part{"type"}
Truth table66%2/3
A and B
A= ref $part eq "HASH"B= defined $part->{"type"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= ref $part eq "HASH"B= defined $$part{"type"}
ABresult
0X0
100
111
181 0 my $type = $part->{type};
182 0 ▶ return { text => $part->{text} } if $type eq 'text' && defined $part->{text};
Branch: 2 branches
BranchTrueFalseTotal
if $type eq "text" and defined $part->{"text"} 5 10 15
if $type eq "text" and defined $$part{"text"} 0 0 0
Condition33%2/6
$type eq "text" and defined $part->{"text"}
!ll&&!rl&&r
1005
$type eq "text" and defined $$part{"text"}
!ll&&!rl&&r
000
MC/DC50%1/2
$type eq "text" and defined $part->{"text"}
$type eq "text" defined $part->{"text"}
MC/DC0%0/2
$type eq "text" and defined $$part{"text"}
$type eq "text" defined $$part{"text"}
Truth table66%2/3
A and B
A= $type eq "text"B= defined $part->{"text"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $type eq "text"B= defined $$part{"text"}
ABresult
0X0
100
111
183 0 ▶ if ( my $img = $self->_image_url_part_image($part) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $img = $self->_image_url_part_image($part)) 7 2 9
if (my $img = $self->_image_url_part_image($part)) 0 0 0
184 0 return $self->_content_block( $img, $method );
185 }
186 0 croak ref($self).": a Gemini message content part may be a string, a native Gemini part, "
187 . "a { type => 'text' } or { type => 'image_url' } hash or a Langertha::Content object; "
188 . "got type '$type'";
189 }
190  
191 # The Langertha::Content::Image for an OpenAI-style { type => 'image_url' }
192 # hash part (a data URL becomes base64), or undef for any other part. Shared by
193 # the wires without an image_url part of their own (gemini, ollama).
194 13 ▶sub _image_url_part_image {
Subroutine _image_url_part_image: called CC=8 SCAR=29.8
195 0 ▶ my ( $self, $part ) = @_;
Subroutine _image_url_part_image: not called CC=8 SCAR=29.8
196 0 ▶ return undef unless ref $part eq 'HASH' && ( $part->{type} // '' ) eq 'image_url';
Branch: 2 branches
BranchTrueFalseTotal
unless ref $part eq "HASH" and ($part->{"type"} // "") eq "image_url" 3 10 13
unless ref $part eq "HASH" and ($$part{"type"} // "") eq "image_url" 0 0 0
Condition30%3/10
ref $part eq "HASH" and ($part->{"type"} // "") eq "image_url"
!ll&&!rl&&r
0310
$part->{"type"} // ""
l!l
130
ref $part eq "HASH" and ($$part{"type"} // "") eq "image_url"
!ll&&!rl&&r
000
$$part{"type"} // ""
l!l
00
MC/DC0%0/2
ref $part eq "HASH" and ($part->{"type"} // "") eq "image_url"
ref $part eq "HASH" $part->{"type"}
MC/DC0%0/2
ref $part eq "HASH" and ($$part{"type"} // "") eq "image_url"
ref $part eq "HASH" $$part{"type"}
Truth table33%1/3
A and B
A= ref $part eq "HASH"B= $part->{"type"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= ref $part eq "HASH"B= $$part{"type"}
ABresult
0X0
100
111
197 0 ▶ my $url = ref $part->{image_url} eq 'HASH' ? $part->{image_url}{url} : $part->{image_url};
Branch: 2 branches
BranchTrueFalseTotal
ref $part->{'image_url'} eq 'HASH' ? : 7 3 10
ref $$part{'image_url'} eq 'HASH' ? : 0 0 0
198 0 ▶ return undef unless defined $url && length $url;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $url and length $url 1 9 10
unless defined $url and length $url 0 0 0
Condition33%2/6
defined $url and length $url
!ll&&!rl&&r
109
defined $url and length $url
!ll&&!rl&&r
000
MC/DC50%1/2
defined $url and length $url
defined $url length $url
MC/DC0%0/2
defined $url and length $url
defined $url length $url
Truth table66%2/3
A and B
A= defined $urlB= length $url
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $urlB= length $url
ABresult
0X0
100
111
199 0 require Langertha::Content::Image;
200 0 ▶ return $url =~ m{\Adata:([^;,]+);base64,(.*)\z}s
Branch: 2 branches
BranchTrueFalseTotal
$url =~ /\Adata:([^;,]+);base64,(.*)\z/s ? : 7 2 9
$url =~ /\Adata:([^;,]+);base64,(.*)\z/s ? : 0 0 0
201 ? Langertha::Content::Image->from_base64( $2, media_type => $1 )
202 : Langertha::Content::Image->from_url($url);
203 }
204  
205 # Serializes one Langertha::Content block. A URL-only image that has to be
206 # inlined (fetched) and cannot be says so in the engine's name before any
207 # request is built (karr k267).
208 85 ▶sub _content_block {
Subroutine _content_block: called CC=10 SCAR=32.1
209 0 ▶ my ( $self, $block, $method, @opt ) = @_;
Subroutine _content_block: not called CC=10 SCAR=32.1
210 0 my %opt = @opt;
211 # The serializers fetch through ensure_base64 without arguments (30s); fetch
212 # first with the engine's timeout instead (karr k279).
213 my $prefetch = $block->isa('Langertha::Content::Image')
214 && $block->has_url && !$block->has_base64
215 0 ▶ && ( $opt{inline} || $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/ );
Condition50%12/24
$block->isa('Langertha::Content::Image') && $block->has_url && !$block->has_base64 && ($opt{'inline'} || $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/)
!ll&&!rl&&r
511321
$block->isa("Langertha::Content::Image") and $block->has_url and not $block->has_base64
!ll&&!rl&&r
391234
$block->isa("Langertha::Content::Image") and $block->has_url
!ll&&!rl&&r
43546
$opt{"inline"} or $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/
l!l&&r!l&&!r
101113
$block->isa('Langertha::Content::Image') && $block->has_url && !$block->has_base64 && ($opt{'inline'} || $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/)
!ll&&!rl&&r
000
$block->isa("Langertha::Content::Image") and $block->has_url and not $block->has_base64
!ll&&!rl&&r
000
$block->isa("Langertha::Content::Image") and $block->has_url
!ll&&!rl&&r
000
$opt{"inline"} or $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/
l!l&&r!l&&!r
000
MC/DC100%5/5
$block->isa('Langertha::Content::Image') && $block->has_url && !$block->has_base64 && ($opt{'inline'} || $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/)
$block->isa("Langertha::Content::Image") $block->has_url not $block->has_base64 $opt{"inline"} $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/
MC/DC0%0/5
$block->isa('Langertha::Content::Image') && $block->has_url && !$block->has_base64 && ($opt{'inline'} || $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/)
$block->isa("Langertha::Content::Image") $block->has_url not $block->has_base64 $opt{"inline"} $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/
Truth table100%6/6
A and B and not(C) && D or E
A= $block->isa("Langertha::Content::Image")B= $block->has_urlC= not $block->has_base64D= $opt{"inline"}E= $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
Truth table0%0/6
A and B and not(C) && D or E
A= $block->isa("Langertha::Content::Image")B= $block->has_urlC= not $block->has_base64D= $opt{"inline"}E= $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
216 0 my $out;
217 0 ▶ return $out if eval {
Branch: 2 branches
BranchTrueFalseTotal
if eval { do { $block->ensure_base64("timeout", $self->inline_image_fetch_timeout, $self->_inline_image_fetch_limits) if $prefetch; $out = $block->$method(@opt); 1 } } 73 12 85
if eval { do { $block->ensure_base64("timeout", $self->inline_image_fetch_timeout, $self->_inline_image_fetch_limits) if $prefetch; $out = $block->$method(@opt); 1 } } 0 0 0
218 0 ▶ $block->ensure_base64( timeout => $self->inline_image_fetch_timeout,
Branch: 2 branches
BranchTrueFalseTotal
if $prefetch 21 64 85
if $prefetch 0 0 0
219 $self->_inline_image_fetch_limits ) if $prefetch;
220 0 $out = $block->$method(@opt);
221 0 1;
222 };
223 0 my $err = $@;
224 0 ▶ croak $self->_inline_image_error($err)
Branch: 2 branches
BranchTrueFalseTotal
if $block->can("has_url") and $block->has_url and not $block->has_base64 9 3 12
if $block->can("has_url") and $block->has_url and not $block->has_base64 0 0 0
Condition33%4/12
$block->can("has_url") and $block->has_url and not $block->has_base64
!ll&&!rl&&r
309
$block->can("has_url") and $block->has_url
!ll&&!rl&&r
309
$block->can("has_url") and $block->has_url and not $block->has_base64
!ll&&!rl&&r
000
$block->can("has_url") and $block->has_url
!ll&&!rl&&r
000
MC/DC33%1/3
$block->can("has_url") and $block->has_url and not $block->has_base64
$block->can("has_url") $block->has_url not $block->has_base64
MC/DC0%0/3
$block->can("has_url") and $block->has_url and not $block->has_base64
$block->can("has_url") $block->has_url not $block->has_base64
Truth table50%2/4
A and B and not(C)
A= $block->can("has_url")B= $block->has_urlC= not $block->has_base64
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and not(C)
A= $block->can("has_url")B= $block->has_urlC= not $block->has_base64
ABCresult
0XX0
10X0
1100
1111
225 if $block->can('has_url') && $block->has_url && !$block->has_base64;
226 0 die $err;
227 }
228  
229 19 ▶sub _inline_image_error {
Subroutine _inline_image_error: called CC=1 SCAR=1.2
230 0 ▶ my ( $self, $err ) = @_;
Subroutine _inline_image_error: not called CC=1 SCAR=1.2
231 0 $err =~ s/ at \S+ line \d+.*//s;
232 0 $err =~ s/\s+\z//;
233 0 return ref($self).": this endpoint takes only inline images (base64 or a data: URL) "
234 . "and the image URL could not be inlined ($err); pass the image as base64 "
235 . "or from a local file instead";
236 }
237  
238 194 has inline_image_fetch_timeout => (
239 isa => 'Int',
240 is => 'ro',
241 default => 30,
242 );
243  
244  
245 194 has inline_image_max_bytes => (
246 isa => 'Int',
247 is => 'ro',
248 default => 20_971_520,
249 );
250  
251  
252 194 has inline_image_url_filter => (
253 isa => 'Maybe[CodeRef]',
254 is => 'ro',
255 );
256  
257  
258 # The ensure_base64(_f) options for the two attributes above (karr k337).
259 43 ▶sub _inline_image_fetch_limits {
Subroutine _inline_image_fetch_limits: called CC=1 SCAR=1.2
260 0 ▶ my ($self) = @_;
Subroutine _inline_image_fetch_limits: not called CC=1 SCAR=1.2
261 0 return ( max_bytes => $self->inline_image_max_bytes,
262 url_filter => $self->inline_image_url_filter );
263 }
264  
265 # The _f paths fetch every URL image this engine has to inline through its
266 # async backend (_async_http: injected client, Net::Async::HTTP or the sync
267 # LWP shim, ADR 0027) before the request is built, all at once, so the build
268 # finds base64 on the object and does no blocking LWP GET inside the event
269 # loop (karr k274). Returns @messages, with Gemini's image_url hash parts
270 # swapped for the fetched Content::Image they would have become in
271 # _gemini_part. A failed fetch fails with the error _content_block croaks.
272 # Each fetch races inline_image_fetch_timeout on the backend's loop (karr
273 # k276): Net::Async::HTTP has no timeout of its own, so a host that accepts
274 # and never answers would stall the call forever. wait_any cancels the loser:
275 # the fetch (Net::Async::HTTP closes its connection) or the timer.
276 663 ▶async sub _prefetch_inline_images_f {
Subroutine _prefetch_inline_images_f: called CC=29 SCAR=34.5
277 663 my ( $self, @messages ) = @_;
278 663 my $fmt = $self->content_format;
279 663 ▶ return @messages unless $fmt eq 'gemini' || $fmt eq 'ollama' || $fmt eq 'lmstudio'
Branch: 1 branch
BranchTrueFalseTotal
unless $fmt eq "gemini" or $fmt eq "ollama" or $fmt eq "lmstudio" or $self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses" 563 100 663
Condition80%12/15
$fmt eq "gemini" or $fmt eq "ollama" or $fmt eq "lmstudio" or $self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
l!l&&r!l&&!r
8119563
$fmt eq "gemini" or $fmt eq "ollama" or $fmt eq "lmstudio"
l!l&&r!l&&!r
801582
$fmt eq "gemini" or $fmt eq "ollama"
l!l&&r!l&&!r
5921583
$self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
!ll&&!rl&&r
563019
$fmt eq "openai" or $fmt eq "responses"
l!l&&r!l&&!r
1900
MC/DC66%4/6
$fmt eq "gemini" or $fmt eq "ollama" or $fmt eq "lmstudio" or $self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
$fmt eq "gemini" $fmt eq "ollama" $fmt eq "lmstudio" $self->_content_inline_images_only $fmt eq "openai" $fmt eq "responses"
Truth table71%5/7
A or B or C or D and E or F
A= $fmt eq "gemini"B= $fmt eq "ollama"C= $fmt eq "lmstudio"D= $self->_content_inline_images_onlyE= $fmt eq "openai"F= $fmt eq "responses"
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
00011X1
0001011
0000XX0
0001000
280 || ( $self->_content_inline_images_only && ( $fmt eq 'openai' || $fmt eq 'responses' ) );
281  
282 100 my ( @out, @fetch, %seen, %by_url );
283 100 for my $msg (@messages) {
284 100 ▶ unless ( ref $msg eq 'HASH' && ref $msg->{content} eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $msg eq "HASH" and ref $msg->{"content"} eq "ARRAY") 78 22 100
Condition100%3/3
ref $msg eq "HASH" and ref $msg->{"content"} eq "ARRAY"
!ll&&!rl&&r
572122
MC/DC100%2/2
ref $msg eq "HASH" and ref $msg->{"content"} eq "ARRAY"
ref $msg eq "HASH" ref $msg->{"content"} eq "ARRAY"
Truth table100%3/3
A and B
A= ref $msg eq "HASH"B= ref $msg->{"content"} eq "ARRAY"
ABresult
0X0
100
111
285 78 push @out, $msg;
286 78 next;
287 }
288 22 my $swapped;
289 my @content;
290 22 for my $part ( @{ $msg->{content} } ) {
291 43 my $out = $part;
292 43 ▶ if ( blessed($part) && $part->isa('Langertha::Content::Image') ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($part) and $part->isa('Langertha::Content::Image')) { } 23 20 43
elsif ($fmt eq 'gemini' and ref $part eq 'HASH' and ($part->{'type'} // '') eq 'image_url') { } 2 36 38
Condition66%2/3
builtin::blessed($part) and $part->isa("Langertha::Content::Image")
!ll&&!rl&&r
20023
MC/DC50%1/2
builtin::blessed($part) and $part->isa("Langertha::Content::Image")
builtin::blessed($part) $part->isa("Langertha::Content::Image")
Truth table66%2/3
A and B
A= builtin::blessed($part)B= $part->isa("Langertha::Content::Image")
ABresult
0X0
100
111
293 push @fetch, $part
294 23 ▶ if $part->has_url && !$part->has_base64 && !$seen{ refaddr $part }++;
Branch: 1 branch
BranchTrueFalseTotal
if $part->has_url and not $part->has_base64 and not $seen{builtin::refaddr($part)}++ 21 2 23
Condition66%4/6
$part->has_url and not $part->has_base64 and not $seen{builtin::refaddr($part)}++
!ll&&!rl&&r
2021
$part->has_url and not $part->has_base64
!ll&&!rl&&r
2021
MC/DC33%1/3
$part->has_url and not $part->has_base64 and not $seen{builtin::refaddr($part)}++
$part->has_url not $part->has_base64 not $seen{builtin::refaddr($part)}++
Truth table50%2/4
A and not(B) and not(C)
A= $part->has_urlB= not $part->has_base64C= not $seen{builtin::refaddr($part)}++
ABCresult
0XX0
10X0
1100
1111
295 }
296 ▶ elsif ( $fmt eq 'gemini' && ref $part eq 'HASH' && ( $part->{type} // '' ) eq 'image_url' ) {
Condition75%6/8
$fmt eq "gemini" and ref $part eq "HASH" and ($part->{"type"} // "") eq "image_url"
!ll&&!rl&&r
1802
$fmt eq "gemini" and ref $part eq "HASH"
!ll&&!rl&&r
992
$part->{"type"} // ""
l!l
20
MC/DC66%2/3
$fmt eq "gemini" and ref $part eq "HASH" and ($part->{"type"} // "") eq "image_url"
$fmt eq "gemini" ref $part eq "HASH" $part->{"type"}
Truth table75%3/4
A and B and C
A= $fmt eq "gemini"B= ref $part eq "HASH"C= $part->{"type"}
ABCresult
0XX0
10X0
1100
1111
297 2 ▶ my $url = ref $part->{image_url} eq 'HASH' ? $part->{image_url}{url} : $part->{image_url};
Branch: 1 branch
BranchTrueFalseTotal
ref $part->{'image_url'} eq 'HASH' ? : 2 0 2
298 2 ▶ if ( defined $url && length $url && $url !~ m{\Adata:[^;,]+;base64,}s ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $url and length $url and not $url =~ /\Adata:[^;,]+;base64,/s) 2 0 2
Condition33%2/6
defined $url and length $url and not $url =~ /\Adata:[^;,]+;base64,/s
!ll&&!rl&&r
002
defined $url and length $url
!ll&&!rl&&r
002
MC/DC0%0/3
defined $url and length $url and not $url =~ /\Adata:[^;,]+;base64,/s
defined $url length $url not $url =~ /\Adata:[^;,]+;base64,/s
Truth table25%1/4
A and B and not(C)
A= defined $urlB= length $urlC= not $url =~ /\Adata:[^;,]+;base64,/s
ABCresult
0XX0
10X0
1100
1111
299 2 require Langertha::Content::Image;
300 2 ▶ $out = $by_url{$url} //= do {
Condition66%2/3
$by_url{$url} //= do { my $img = "Langertha::Content::Image"->from_url($url); push @fetch, $img; $img }
l!l&&r!l&&!r
011
MC/DC50%1/2
$by_url{$url} //= do { my $img = "Langertha::Content::Image"->from_url($url); push @fetch, $img; $img }
$by_url{$url} do { my $img = "Langertha::Content::Image"->from_url($url); push @fetch, $img; $img }
Truth table66%2/3
A //= B
A= $by_url{$url}B= do { my $img = "Langertha::Content::Image"->from_url($url); push @fetch, $img; $img }
ABresult
1X1
011
000
301 2 my $img = Langertha::Content::Image->from_url($url);
302 1 push @fetch, $img;
303 1 $img;
304 };
305 1 $swapped = 1;
306 }
307 }
308 42 push @content, $out;
309 }
310 21 ▶ push @out, $swapped ? { %$msg, content => \@content } : $msg;
Branch: 1 branch
BranchTrueFalseTotal
$swapped ? : 1 20 21
311 }
312 99 ▶ return @messages unless @fetch;
Branch: 1 branch
BranchTrueFalseTotal
unless @fetch 80 19 99
313  
314 19 my $http = $self->_async_http;
315 19 my $loop = $self->async_loop;
316 19 my $secs = $self->inline_image_fetch_timeout;
317 await Future->needs_all( map {
318 19 my $url = $_->url;
319 22 my $fetch = $_->ensure_base64_f( $http, $self->_inline_image_fetch_limits );
320 22 ▶ $fetch = Future->wait_any( $fetch, $loop->delay_future( after => $secs )
Branch: 1 branch
BranchTrueFalseTotal
if $loop and $secs 7 15 22
Condition100%3/3
$loop and $secs
!ll&&!rl&&r
1417
MC/DC100%2/2
$loop and $secs
$loop $secs
Truth table100%3/3
A and B
A= $loopB= $secs
ABresult
0X0
100
111
321 ->then_fail("ensure_base64: failed to fetch $url: timed out after ${secs}s\n") )
322 if $loop && $secs;
323 10 ▶ $fetch->else( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
324 10 Future->fail( $self->_inline_image_error( $_[0] ) . "\n" );
325 22 } );
326 } @fetch );
327 9 return @out;
328 194 }
329  
330  
331 64 ▶sub simple_chat {
Subroutine simple_chat: called CC=6 SCAR=19.9
Pod documented
332 64 my ( $self, @messages ) = @_;
333 64 ▶ $log->debugf("[%s] simple_chat with %d message(s), model=%s",
Condition50%1/2
$self->chat_model // "default"
l!l
640
MC/DC0%0/1
$self->chat_model // "default"
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
334 ref $self, scalar @messages, $self->chat_model // 'default');
335 64 my $t0 = [gettimeofday];
336 64 my $request = $self->chat(@messages);
337 64 my $response = $self->user_agent->request($request);
338 64 my $elapsed = tv_interval($t0);
339 64 my $result = $request->response_call->($response);
340 51 ▶ if (ref $result && $result->isa('Langertha::Response')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result and $result->isa("Langertha::Response")) 51 0 51
Condition33%1/3
ref $result and $result->isa("Langertha::Response")
!ll&&!rl&&r
0051
MC/DC0%0/2
ref $result and $result->isa("Langertha::Response")
ref $result $result->isa("Langertha::Response")
Truth table33%1/3
A and B
A= ref $resultB= $result->isa("Langertha::Response")
ABresult
0X0
100
111
341 51 $result = $result->clone_with(
342 timing => _merge_timing_field($result->timing, total_seconds => $elapsed),
343 );
344 51 ▶ if ($self->can('has_rate_limit') && $self->has_rate_limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can("has_rate_limit") and $self->has_rate_limit) 0 51 51
Condition33%1/3
$self->can("has_rate_limit") and $self->has_rate_limit
!ll&&!rl&&r
0510
MC/DC0%0/2
$self->can("has_rate_limit") and $self->has_rate_limit
$self->can("has_rate_limit") $self->has_rate_limit
Truth table33%1/3
A and B
A= $self->can("has_rate_limit")B= $self->has_rate_limit
ABresult
0X0
100
111
345 0 $result = $result->clone_with(rate_limit => $self->rate_limit);
346 }
347 }
348 51 return $result;
349 }
350  
351  
352 31 ▶sub chat_stream {
Subroutine chat_stream: called CC=2 SCAR=7.1
Pod documented
353 31 my ( $self, @messages ) = @_;
354 31 ▶ croak "".(ref $self)." does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_stream_request") 0 31 31
355 unless $self->can('chat_stream_request');
356 31 return $self->chat_stream_request($self->chat_messages(@messages));
357 }
358  
359  
360 6 ▶sub simple_chat_stream {
Subroutine simple_chat_stream: called CC=4 SCAR=14.1
Pod documented
361 6 my ( $self, $callback, @messages ) = @_;
362 6 ▶ croak "simple_chat_stream requires a callback as first argument"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 6 6
363 unless ref $callback eq 'CODE';
364 6 $log->debugf("[%s] simple_chat_stream (%s format)", ref $self, $self->stream_format);
365 6 my $request = $self->chat_stream(@messages);
366 6 my ( $chunks, $timing ) = $self->execute_streaming_request($request, $callback);
367 $log->debugf("[%s] Stream completed: %d chunks (%.3fs)",
368 3 ▶ ref $self, scalar @$chunks, $timing->{total_seconds} // 0);
Condition50%1/2
$timing->{"total_seconds"} // 0
l!l
30
MC/DC0%0/1
$timing->{"total_seconds"} // 0
$timing->{"total_seconds"}
Truth table50%1/2
A
A= $timing->{"total_seconds"}
Aresult
11
00
369 3 my $content = join('', map { $_->content } @$chunks);
370 3 my $thinking = $self->aggregate_thinking($chunks);
371 3 ▶ return wantarray ? ( $content, $thinking ) : $content;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 3 0 3
372 }
373  
374  
375 1 ▶sub simple_chat_stream_iterator {
Subroutine simple_chat_stream_iterator: called CC=2 SCAR=7.0
Pod documented
376 1 my ( $self, @messages ) = @_;
377 1 require Langertha::Stream;
378 1 my $request = $self->chat_stream(@messages);
379 1 my ( $chunks, $timing ) = $self->execute_streaming_request($request);
380 $log->debugf("[%s] Stream completed: %d chunks (%.3fs)",
381 1 ▶ ref $self, scalar @$chunks, $timing->{total_seconds} // 0);
Condition50%1/2
$timing->{"total_seconds"} // 0
l!l
10
MC/DC0%0/1
$timing->{"total_seconds"} // 0
$timing->{"total_seconds"}
Truth table50%1/2
A
A= $timing->{"total_seconds"}
Aresult
11
00
382 1 return Langertha::Stream->new(chunks => $chunks);
383 }
384  
385  
386 # Future-based async methods. The _async_http backend (and its _async_loop)
387 # come from Langertha::Role::AsyncHTTP (composed below): injected client >
388 # Net::Async::HTTP > synchronous LWP fallback.
389  
390 52 ▶async sub simple_chat_f {
Subroutine simple_chat_f: called CC=1 SCAR=0.0
Pod documented
391 52 my ( $self, @messages ) = @_;
392 52 $log->debugf("[%s] simple_chat_f with %d message(s)", ref $self, scalar @messages);
393 52 return await $self->chat_f( messages => \@messages );
394 194 }
395  
396 # Canonical per-request controls (karr #46). chat_f normalizes these like
397 # messages/tools instead of spreading them as raw target-wire kwargs: each
398 # engine's chat_request consumes the `controls` hash and places them via the
399 # same value objects the engine attributes use (Langertha::Reasoning,
400 # Langertha::PromptCache) or the engine's own placement logic (Ollama options,
401 # Gemini generationConfig). Unknown keys still pass straight through.
402 194 my %CANONICAL_CONTROLS = map { $_ => 1 } qw(
403 temperature
404 max_tokens
405 response_format
406 seed
407 parallel_tool_use
408 reasoning_effort
409 thinking_enabled
410 thinking_budget
411 thinking_display
412 prompt_cache
413 prompt_cache_ttl
414 prompt_cache_key
415 prefix_cache_salt
416 cache_prompt
417 n_cache_reuse
418 id_slot
419 priority
420 return_cached_tokens_details
421 extra_key
422 );
423  
424 542 ▶sub _extract_controls {
Subroutine _extract_controls: called CC=3 SCAR=11.0
425 542 my ( $self, $opts ) = @_;
426 542 my %controls;
427 542 for my $key ( keys %CANONICAL_CONTROLS ) {
428 10298 ▶ $controls{$key} = delete $opts->{$key} if exists $opts->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{$key} 87 10211 10298
429 }
430 542 return \%controls;
431 }
432  
433  
434 # karr #122: simple_chat / simple_chat_f / chat funnel their positional
435 # @messages through chat_messages, which turns every non-ref scalar into a
436 # { role => 'user' } turn. A caller who mistakes those methods for chat_f and
437 # appends a control as a kwarg tail -- simple_chat($prompt, reasoning_effort =>
438 # 'high') -- silently sends the control name and its value as extra user
439 # messages, with no error and no effect (the project hit this twice in its own
440 # docs). This is a diagnostic only: warn once (never die) when a plain-scalar
441 # message exactly matches a canonical control name; behaviour is otherwise
442 # unchanged (the strings still become messages as before). A control name has
443 # no legitimate use as a whole user turn, so this has no false positives in
444 # practice. The broader unknown-constructor-arg finding (karr #101) is out of
445 # scope here.
446 1117 ▶sub _warn_control_message_args {
Subroutine _warn_control_message_args: called CC=4 SCAR=13.9
447 1117 my ( $self, @messages ) = @_;
448 1117 my %seen;
449 my @hits =
450 15 grep { !$seen{$_}++ }
451 1117 ▶ grep { defined $_ && !ref $_ && $CANONICAL_CONTROLS{$_} } @messages;
Condition83%5/6
defined $_ && !ref($_) && $CANONICAL_CONTROLS{$_}
!ll&&!rl&&r
35184015
defined $_ and not ref $_
!ll&&!rl&&r
0351855
MC/DC66%2/3
defined $_ && !ref($_) && $CANONICAL_CONTROLS{$_}
defined $_ not ref $_ $CANONICAL_CONTROLS{$_}
Truth table75%3/4
A and not(B) && C
A= defined $_B= not ref $_C= $CANONICAL_CONTROLS{$_}
ABCresult
0XX0
10X0
1100
1111
452 1117 ▶ return unless @hits;
Branch: 1 branch
BranchTrueFalseTotal
unless @hits 1104 13 1117
453 carp sprintf(
454 "%s: message argument(s) %s match a chat_f control name and are being "
455 . "sent as plain user message text. Per-request controls such as "
456 . "reasoning_effort, temperature and response_format are named "
457 . "arguments to chat_f (or engine constructor attributes), not "
458 . "simple_chat/chat message arguments.",
459 ref $self,
460 13 join( ', ', map { "'$_'" } @hits ),
461 );
462 13 return;
463 }
464  
465 # Drop warnings (karr k247, ADR 0025): a request builder that leaves a value
466 # off the wire says so, but the carp fires in a private helper several
467 # Langertha frames below the caller's chat_f / chat / simple_chat_f call, and
468 # Carp skips only one frame. For the duration of this one warning every
469 # Langertha, Moose, Class::MOP, Eval::Closure and Future package on the stack
470 # is marked Carp-internal, so the message names the first frame outside that
471 # plumbing: the user's own call site (the rule of Role::AsyncHTTP's
472 # _caller_location). croak keeps Carp's normal location. Under an event loop
473 # the stack may hold no user frame; Carp then reports what it finds, it never
474 # dies.
475 #
476 # $once is set when the dropped value comes from an engine attribute: that
477 # value is the same on every request (and every chat_with_tools_f iteration),
478 # so it warns once per engine instance per key. A per-request value warns
479 # every time. The seen-set lives on the instance, never in a global.
480 has _warned_drops => (
481 is => 'ro',
482 isa => 'HashRef',
483 init_arg => undef,
484 lazy => 1,
485 132 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
486 194 );
487  
488 194 my $LANGERTHA_INTERNAL = qr/\A(?:Langertha|Moose|Class::MOP|Eval::Closure|Future)(?:::|\z)/;
489  
490 295 ▶sub _langertha_carp {
Subroutine _langertha_carp: called CC=5 SCAR=16.1
491 295 my ( $self, $message, $once ) = @_;
492 295 ▶ return if defined $once && $self->_warned_drops->{$once}++;
Branch: 1 branch
BranchTrueFalseTotal
if defined $once and $self->_warned_drops->{$once}++ 22 273 295
Condition100%3/3
defined $once and $self->_warned_drops->{$once}++
!ll&&!rl&&r
14113222
MC/DC100%2/2
defined $once and $self->_warned_drops->{$once}++
defined $once $self->_warned_drops->{$once}++
Truth table100%3/3
A and B
A= defined $onceB= $self->_warned_drops->{$once}++
ABresult
0X0
100
111
493 273 my %internal;
494 273 ▶ for ( my $level = 0; my ($package) = caller $level; $level++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($package) = caller $level) 1857 273 2130
495 1857 ▶ $internal{$package} = 1 if $package =~ $LANGERTHA_INTERNAL;
Branch: 1 branch
BranchTrueFalseTotal
if $package =~ /$LANGERTHA_INTERNAL/ 715 1142 1857
496 }
497 273 local @Carp::Internal{ keys %internal } = (1) x keys %internal;
498 273 carp $message;
499 273 return;
500 }
501  
502 # karr #148 / #184: a couple of OpenAI-compatible serving stacks reject a
503 # request that combines tools and a structured-output response_format with an
504 # opaque HTTP 400 and no body. No boolean capability flag can express a mutual
505 # exclusion between two capabilities in one request (ADR 0021). The constraint
506 # is a property of the serving STACK, not of the model: Groq and Cerebras
507 # enforce it across every model they serve, while AKI serves gpt-oss-120b with
508 # tools + a json_schema response_format at HTTP 200 (live 2026-09-19) — so each
509 # affected engine declares its own all-models rule and there is no shared base
510 # rule to over-fire on the unaffected stacks.
511 #
512 # The seam mirrors ADR 0019's model_capability_corrections: an ORDERED list of
513 # ( $matcher => $rule ) pairs keyed on chat_model. $matcher is an exact
514 # model-id string (matched with eq) or a qr// regex (matched against
515 # chat_model). $rule is a CODEREF — the concrete seam, deliberately NOT a
516 # declarative constraint DSL (karr #148) — invoked as $self->$rule(%request)
517 # with has_tools / tool_choice_forced / response_format / streaming; it croaks
518 # when the request hits the combination the stack rejects. The default is an
519 # empty list, so engines that constrain nothing pay nothing; an engine whose
520 # serving stack rejects the combination declares an all-models rule by
521 # overriding model_capability_exclusions (Groq, Cerebras, SGLang).
522 515 ▶sub model_capability_exclusions { return () }
Subroutine model_capability_exclusions: called CC=1 SCAR=0.0
Pod documented
523  
524 # Consulted by chat_f (streaming => 0) and chat_stream_realtime_f
525 # (streaming => 1) after the effective post-rewrite request is built (ADR 0021),
526 # so an ADR 0005 rewrite that already collapsed the body to a single path
527 # pre-empts it. Walks the per-model exclusion table for the selected chat_model
528 # and lets each matching rule convert a known provider 400 into a clear local
529 # croak. A no-op when the table is empty or no matcher hits.
530 569 ▶sub _check_capability_exclusions {
Subroutine _check_capability_exclusions: called CC=2 SCAR=6.9
531 569 my ( $self, %request ) = @_;
532 569 $self->$_(%request) for $self->_matched_capability_exclusions;
533 541 return;
534 }
535  
536 # The rules of model_capability_exclusions whose matcher hits chat_model, in
537 # table order. Shared by _check_capability_exclusions and the per-request model
538 # override warning (karr k352), which compares the matched set for two models.
539 591 ▶sub _matched_capability_exclusions {
Subroutine _matched_capability_exclusions: called CC=7 SCAR=19.5
540 591 my ( $self ) = @_;
541 591 my @rules = $self->model_capability_exclusions;
542 591 ▶ return unless @rules;
Branch: 1 branch
BranchTrueFalseTotal
unless @rules 515 76 591
543 # chat_model is the model that actually carries tools / response_format on the
544 # wire; guard for the rare consumer that has no model surface at all.
545 # An empty or undef chat_model is matched as '', the same as
546 # model_capability_corrections (karr k223), so an all-models qr// rule
547 # (Groq, Cerebras) still holds for model => ''.
548 76 ▶ return unless $self->can('chat_model');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_model") 0 76 76
549 76 ▶ my $model = $self->chat_model // '';
Condition50%1/2
$self->chat_model // ""
l!l
760
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
550 76 my @matched;
551 76 ▶ while ( @rules >= 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rules >= 2) 76 76 152
552 76 my ( $matcher, $rule ) = splice @rules, 0, 2;
553 76 ▶ my $hit = ref $matcher eq 'Regexp' ? ( $model =~ $matcher )
Branch: 1 branch
BranchTrueFalseTotal
ref $matcher eq 'Regexp' ? : 72 4 76
554 : ( $model eq $matcher );
555 76 ▶ push @matched, $rule if $hit;
Branch: 1 branch
BranchTrueFalseTotal
if $hit 75 1 76
556 }
557 76 return @matched;
558 }
559  
560  
561 # True when the request asks for tools — either a tools array or a
562 # forced named tool_choice. Used to feed the capability-exclusion hook.
563 569 ▶sub _chat_tools_requested {
Subroutine _chat_tools_requested: called CC=6 SCAR=18.2
564 569 my ( $self, $opts ) = @_;
565 # An empty tools => [] sends zero tools on the wire, so it must NOT trip the
566 # capability-exclusion guard (which would croak on Cerebras/Groq for a request
567 # that combines tools with a structured-output response_format). Only a
568 # non-empty tools array counts as "tools requested" here.
569 569 ▶ return 1 if ref $opts->{tools} eq 'ARRAY' && @{ $opts->{tools} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};} 279 290 569
Condition100%3/3
ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};}
!ll&&!rl&&r
2873279
MC/DC100%2/2
ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};}
ref $opts->{"tools"} eq "ARRAY" @{$opts->{"tools"};}
Truth table100%3/3
A and B
A= ref $opts->{"tools"} eq "ARRAY"B= @{$opts->{"tools"};}
ABresult
0X0
100
111
570 290 ▶ return 0 unless exists $opts->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"tool_choice"} 288 2 290
571 2 my $tc = Langertha::ToolChoice->from_hash( $opts->{tool_choice} );
572 2 ▶ return ( $tc && $tc->type eq 'tool' ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$tc && $tc->type eq 'tool' ? : 2 0 2
Condition33%1/3
$tc and $tc->type eq "tool"
!ll&&!rl&&r
002
MC/DC0%0/2
$tc and $tc->type eq "tool"
$tc $tc->type eq "tool"
Truth table33%1/3
A and B
A= $tcB= $tc->type eq "tool"
ABresult
0X0
100
111
573 }
574  
575 # True when the request forces a tool call: tool_choice any (wire 'required')
576 # or a named tool (karr k245). Read from the caller's tool_choice before any
577 # tool_choice gate runs, so an exclusion rule sees what was asked; after the
578 # ADR 0005 rewrite (which deletes tool_choice) it is 0. Feeds the
579 # capability-exclusion hook as tool_choice_forced.
580 569 ▶sub _chat_tool_choice_forced {
Subroutine _chat_tool_choice_forced: called CC=5 SCAR=16.1
581 569 my ( $self, $opts ) = @_;
582 569 ▶ return 0 unless defined $opts->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $opts->{"tool_choice"} 534 35 569
583 35 my $tc = Langertha::ToolChoice->from_hash( $opts->{tool_choice} );
584 35 ▶ return ( $tc && ( $tc->type eq 'any' || $tc->type eq 'tool' ) ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$tc && ($tc->type eq 'any' || $tc->type eq 'tool') ? : 27 8 35
Condition83%5/6
$tc and $tc->type eq "any" || $tc->type eq "tool"
!ll&&!rl&&r
0827
$tc->type eq "any" or $tc->type eq "tool"
l!l&&r!l&&!r
15128
MC/DC66%2/3
$tc and $tc->type eq "any" || $tc->type eq "tool"
$tc $tc->type eq "any" $tc->type eq "tool"
Truth table75%3/4
A and B or C
A= $tcB= $tc->type eq "any"C= $tc->type eq "tool"
ABCresult
0XX0
1000
11X1
1011
585 }
586  
587 # The response_format the request builders will put on the wire (karr k249):
588 # the per-request value when the caller passed the key, else the engine
589 # attribute (Role::ResponseFormat) -- the same precedence as
590 # OpenAICompatible's chat_request / chat_stream_request, AnthropicCompatible's
591 # _take_response_format and ResponsesCompatible. Feeds the capability-exclusion
592 # hook, so a rule also fires for an engine-level response_format. Always a
593 # scalar (undef when neither is set): it is called in a hash-list position.
594 641 ▶sub _chat_effective_response_format {
Subroutine _chat_effective_response_format: called CC=4 SCAR=13.9
595 641 my ( $self, $opts ) = @_;
596 my $rf = exists $opts->{response_format} ? $opts->{response_format}
597 641 ▶ : ( $self->can('has_response_format') && $self->has_response_format ) ? $self->response_format
Branch: 2 branches
BranchTrueFalseTotal
exists $opts->{'response_format'} ? : 87 554 641
$self->can('has_response_format') && $self->has_response_format ? : 12 542 554
Condition100%3/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
3850412
MC/DC100%2/2
$self->can("has_response_format") and $self->has_response_format
$self->can("has_response_format") $self->has_response_format
Truth table100%3/3
A and B
A= $self->can("has_response_format")B= $self->has_response_format
ABresult
0X0
100
111
598 : undef;
599 641 return $rf;
600 }
601  
602 # The ADR 0005 forced-tool rewrite sets a per-request response_format, which
603 # replaces any other one (karr k250). A structured response_format the caller
604 # passed in the same request is a conflicting intent: croak. One that only
605 # comes from the engine attribute yields to the request's forced tool: carp.
606 # A `text` response_format asks for no structure, so it is no conflict.
607 31 ▶sub _chat_rewrite_replaces_response_format {
Subroutine _chat_rewrite_replaces_response_format: called CC=7 SCAR=19.9
608 31 my ( $self, $opts, $name ) = @_;
609 31 my $rf = $self->_chat_effective_response_format($opts);
610 31 ▶ return unless defined $rf;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rf 12 19 31
611 19 ▶ my $type = ref $rf eq 'HASH' ? $rf->{type} : $rf;
Branch: 1 branch
BranchTrueFalseTotal
ref $rf eq 'HASH' ? : 19 0 19
612 19 ▶ return if defined $type && !ref $type && $type eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
if defined $type and not ref $type and $type eq "text" 6 13 19
Condition50%3/6
defined $type and not ref $type and $type eq "text"
!ll&&!rl&&r
0136
defined $type and not ref $type
!ll&&!rl&&r
0019
MC/DC33%1/3
defined $type and not ref $type and $type eq "text"
defined $type not ref $type $type eq "text"
Truth table50%2/4
A and not(B) and C
A= defined $typeB= not ref $typeC= $type eq "text"
ABCresult
0XX0
10X0
1100
1111
613 croak "".(ref $self).": chat_f got both a forced tool_choice '$name' and a "
614 . "response_format; this engine carries a forced tool as a response_format "
615 . "(no native named tool_choice), so the two conflict -- pick one"
616 13 ▶ if exists $opts->{response_format};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"response_format"} 9 4 13
617 4 $self->_langertha_carp( "".(ref $self).": the forced tool_choice '$name' is sent as a "
618 . "response_format (no native named tool_choice); the engine's "
619 . "response_format is replaced for this request",
620 "response_format replaced by tool_choice $name" );
621 4 return;
622 }
623  
624 # karr k352 (split from k238): a `model` passed to chat_f or
625 # chat_stream_realtime_f is no canonical control; it rides %extra into the
626 # request builder and replaces the body's model field. Every model-scoped wire
627 # decision still reads chat_model: the layer-3 capability corrections and the
628 # learned facts (ADR 0019 / 0032, and a model-aware layer 2 such as Gemini's),
629 # the exclusion rules (ADR 0024), the reasoning profile (ADR 0023), the
630 # reasoning temperature gate (ADR 0025), the per-model tool_wire_format (ADR
631 # 0033) and the per-model body shape (completion-length key, response-size
632 # default, native structured output). Langertha does not re-scope a request to
633 # its override (that is a second engine); it warns when the override would get
634 # a different decision, naming which.
635 #
636 # Quiet unless something flips: an override equal to chat_model costs nothing,
637 # and only the decisions THIS request consults are compared. A capability flag
638 # named here is compared only when one of its request features is in play;
639 # image_input never (it reports what the model sees and gates nothing, ADR
640 # 0019 k266 Update); any other flag always, so a new model-scoped flag errs
641 # toward a warning, not toward silence.
642 194 my %CAP_CONSULTED_BY = (
643 tools_native => ['tools'],
644 tools_hermes => ['tools'],
645 server_tools => ['tools'],
646 tool_choice_auto => ['tool_choice'],
647 tool_choice_any => ['tool_choice'],
648 tool_choice_none => ['tool_choice'],
649 tool_choice_named => ['tool_choice'],
650 response_format_json_object => ['response_format'],
651 # the ADR 0005 forced-tool rewrite consults it too
652 response_format_json_schema => [ 'response_format', 'tool_choice' ],
653 temperature => ['temperature'],
654 reasoning_effort => ['reasoning'],
655 thinking_budget => ['reasoning'],
656 parallel_tool_use => ['parallel_tool_use'],
657 streaming => ['streaming'],
658 # Gemini's per-generation flag: consulted only with a bound cachedContent
659 cached_content => ['cached_content'],
660 image_input => [],
661 # the tool-result form (ADR 0039): only a tool loop sends tool results
662 tool_result_images => ['tools'],
663 tool_result_pdf => ['tools'],
664 );
665  
666 # The request features that decide which model-scoped decisions a request
667 # consults: from the per-request options, else the engine attribute.
668 41 ▶sub _chat_request_features {
Subroutine _chat_request_features: called CC=14 SCAR=26.5
669 41 my ( $self, $opts, $streaming ) = @_;
670 281 ▶ my $attr_set = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
671 281 my $predicate = 'has_' . $_[0];
672 281 ▶ return $self->can($predicate) && $self->$predicate;
Condition100%3/3
$self->can($predicate) && $self->$predicate
!ll&&!rl&&r
362423
MC/DC100%2/2
$self->can($predicate) && $self->$predicate
$self->can($predicate) $self->$predicate
Truth table100%3/3
A && B
A= $self->can($predicate)B= $self->$predicate
ABresult
0X0
100
111
673 41 };
674 41 my %features;
675 41 ▶ $features{tools} = 1 if ref $opts->{tools} eq 'ARRAY' && @{ $opts->{tools} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};} 11 30 41
Condition66%2/3
ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};}
!ll&&!rl&&r
30011
MC/DC50%1/2
ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};}
ref $opts->{"tools"} eq "ARRAY" @{$opts->{"tools"};}
Truth table66%2/3
A and B
A= ref $opts->{"tools"} eq "ARRAY"B= @{$opts->{"tools"};}
ABresult
0X0
100
111
676 41 ▶ $features{tool_choice} = 1 if defined $opts->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"tool_choice"} 1 40 41
677 41 ▶ $features{response_format} = 1 if defined $self->_chat_effective_response_format($opts);
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->_chat_effective_response_format($opts) 0 41 41
678 41 ▶ $features{temperature} = 1 if exists $opts->{temperature} || $attr_set->('temperature');
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"temperature"} or &$attr_set("temperature") 4 37 41
Condition100%3/3
exists $opts->{"temperature"} or &$attr_set("temperature")
l!l&&r!l&&!r
3137
MC/DC100%2/2
exists $opts->{"temperature"} or &$attr_set("temperature")
exists $opts->{"temperature"} &$attr_set("temperature")
Truth table100%3/3
A or B
A= exists $opts->{"temperature"}B= &$attr_set("temperature")
ABresult
1X1
011
000
679 $features{reasoning} = 1
680 41 ▶ if grep { exists $opts->{$_} || $attr_set->($_) } qw( reasoning_effort thinking_enabled thinking_budget thinking_display );
Branch: 1 branch
BranchTrueFalseTotal
if grep {exists $opts->{$_} or &$attr_set($_);} "reasoning_effort", "thinking_enabled", "thinking_budget", "thinking_display" 4 37 41
Condition100%3/3
exists $opts->{$_} || &$attr_set($_)
l!l&&r!l&&!r
31160
MC/DC100%2/2
exists $opts->{$_} || &$attr_set($_)
exists $opts->{$_} &$attr_set($_)
Truth table100%3/3
A || B
A= exists $opts->{$_}B= &$attr_set($_)
ABresult
1X1
011
000
681 41 ▶ $features{parallel_tool_use} = 1 if exists $opts->{parallel_tool_use} || $attr_set->('parallel_tool_use');
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"parallel_tool_use"} or &$attr_set("parallel_tool_use") 0 41 41
Condition33%1/3
exists $opts->{"parallel_tool_use"} or &$attr_set("parallel_tool_use")
l!l&&r!l&&!r
0041
MC/DC0%0/2
exists $opts->{"parallel_tool_use"} or &$attr_set("parallel_tool_use")
exists $opts->{"parallel_tool_use"} &$attr_set("parallel_tool_use")
Truth table33%1/3
A or B
A= exists $opts->{"parallel_tool_use"}B= &$attr_set("parallel_tool_use")
ABresult
1X1
011
000
682 41 ▶ $features{max_tokens} = 1 if exists $opts->{max_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"max_tokens"} 5 36 41
683 41 ▶ $features{streaming} = 1 if $streaming;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming 2 39 41
684 41 ▶ $features{cached_content} = 1 if $attr_set->('cached_content');
Branch: 1 branch
BranchTrueFalseTotal
if &$attr_set("cached_content") 1 40 41
685 41 return \%features;
686 }
687  
688 # The model-scoped decisions this engine takes for a request with $features,
689 # as label => value. Read-only: no warning, no request. An engine with a
690 # model-scoped decision of its own adds it with an `around` (NousResearch's
691 # reasoning prompt).
692 82 ▶sub _model_scoped_wire_decisions {
Subroutine _model_scoped_wire_decisions: called CC=23 SCAR=31.9
693 82 my ( $self, $features, $opts ) = @_;
694 82 my %decision;
695 82 my $caps = $self->engine_capabilities;
696 82 for my $cap ( grep { $caps->{$_} } keys %$caps ) {
697 1315 my $by = $CAP_CONSULTED_BY{$cap};
698 1315 ▶ next if $by && !grep { $features->{$_} } @$by;
Branch: 1 branch
BranchTrueFalseTotal
if $by and not grep({$features->{$_};} @$by) 839 476 1315
Condition100%3/3
$by and not grep({$features->{$_};} @$by)
!ll&&!rl&&r
42353839
MC/DC100%2/2
$by and not grep({$features->{$_};} @$by)
$by not grep({$features->{$_};} @$by)
Truth table100%3/3
A and not(B)
A= $byB= not grep({$features->{$_};} @$by)
ABresult
0X0
100
111
699 476 $decision{"supports('$cap')"} = 1;
700 }
701 82 ▶ my $tools = $features->{tools} || $features->{tool_choice};
Condition66%2/3
$features->{'tools'} || $features->{'tool_choice'}
l!l&&r!l&&!r
22060
MC/DC50%1/2
$features->{'tools'} || $features->{'tool_choice'}
$features->{'tools'} $features->{'tool_choice'}
Truth table66%2/3
A || B
A= $features->{'tools'}B= $features->{'tool_choice'}
ABresult
1X1
011
000
702 82 ▶ $decision{tool_wire_format} = $self->tool_wire_format
Branch: 1 branch
BranchTrueFalseTotal
if $tools and $self->can("tool_wire_format") 22 60 82
Condition66%2/3
$tools and $self->can("tool_wire_format")
!ll&&!rl&&r
60022
MC/DC50%1/2
$tools and $self->can("tool_wire_format")
$tools $self->can("tool_wire_format")
Truth table66%2/3
A and B
A= $toolsB= $self->can("tool_wire_format")
ABresult
0X0
100
111
703 if $tools && $self->can('tool_wire_format');
704 1 $decision{model_capability_exclusions} = join ',', map { refaddr $_ } $self->_matched_capability_exclusions
705 82 ▶ if $tools || $features->{response_format};
Branch: 1 branch
BranchTrueFalseTotal
if $tools or $features->{"response_format"} 22 60 82
Condition66%2/3
$tools or $features->{"response_format"}
l!l&&r!l&&!r
22060
MC/DC50%1/2
$tools or $features->{"response_format"}
$tools $features->{"response_format"}
Truth table66%2/3
A or B
A= $toolsB= $features->{"response_format"}
ABresult
1X1
011
000
706 82 ▶ if ( $features->{reasoning} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($features->{"reasoning"}) 8 74 82
707 8 require Langertha::Reasoning::Profile;
708 8 $decision{'reasoning profile'} =
709 refaddr( Langertha::Reasoning::Profile->for_model( $self->_capability_model ) );
710 }
711 $decision{'temperature gate'} = $self->_temperature_rejected_by_reasoning($opts) ? 1 : 0
712 82 ▶ if $features->{temperature} && $self->can('_temperature_rejected_by_reasoning');
Branch: 2 branches
BranchTrueFalseTotal
if $features->{"temperature"} and $self->can("_temperature_rejected_by_reasoning") 2 80 82
$self->_temperature_rejected_by_reasoning($opts) ? : 1 1 2
Condition100%3/3
$features->{"temperature"} and $self->can("_temperature_rejected_by_reasoning")
!ll&&!rl&&r
7462
MC/DC100%2/2
$features->{"temperature"} and $self->can("_temperature_rejected_by_reasoning")
$features->{"temperature"} $self->can("_temperature_rejected_by_reasoning")
Truth table100%3/3
A and B
A= $features->{"temperature"}B= $self->can("_temperature_rejected_by_reasoning")
ABresult
0X0
100
111
713 82 ▶ my $size = $self->can('get_response_size') ? $self->get_response_size : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->can('get_response_size') ? : 82 0 82
714 $decision{'response_size default'} = $size // ''
715 82 ▶ if !$features->{max_tokens} && $self->can('get_response_size');
Branch: 1 branch
BranchTrueFalseTotal
if not $features->{"max_tokens"} and $self->can("get_response_size") 72 10 82
Condition80%4/5
not $features->{"max_tokens"} and $self->can("get_response_size")
!ll&&!rl&&r
10072
$size // ""
l!l
3042
MC/DC50%1/2
not $features->{"max_tokens"} and $self->can("get_response_size")
not $features->{"max_tokens"} $self->can("get_response_size")
MC/DC100%1/1
$size // ""
$size
Truth table66%2/3
not(A) and B
A= not $features->{"max_tokens"}B= $self->can("get_response_size")
ABresult
0X0
100
111
Truth table100%2/2
A
A= $size
Aresult
11
00
716 $decision{'completion-length key'} = $self->_max_tokens_key
717 82 ▶ if ( $features->{max_tokens} || $size ) && $self->can('_max_tokens_key');
Branch: 1 branch
BranchTrueFalseTotal
if $features->{"max_tokens"} || $size and $self->can("_max_tokens_key") 16 66 82
Condition100%6/6
$features->{"max_tokens"} || $size and $self->can("_max_tokens_key")
!ll&&!rl&&r
422416
$features->{"max_tokens"} or $size
l!l&&r!l&&!r
103042
MC/DC100%3/3
$features->{"max_tokens"} || $size and $self->can("_max_tokens_key")
$features->{"max_tokens"} $size $self->can("_max_tokens_key")
Truth table80%4/5
A or B and C
A= $features->{"max_tokens"}B= $sizeC= $self->can("_max_tokens_key")
ABCresult
00X0
1X00
0100
1X11
0111
718 $decision{'native structured output'} = $self->_native_structured_output_for_model ? 1 : 0
719 81 ▶ if $features->{response_format} && $self->can('_native_structured_output_for_model');
Branch: 2 branches
BranchTrueFalseTotal
if $features->{"response_format"} and $self->can("_native_structured_output_for_model") 0 81 81
$self->_native_structured_output_for_model ? : 0 0 0
Condition33%1/3
$features->{"response_format"} and $self->can("_native_structured_output_for_model")
!ll&&!rl&&r
8100
MC/DC0%0/2
$features->{"response_format"} and $self->can("_native_structured_output_for_model")
$features->{"response_format"} $self->can("_native_structured_output_for_model")
Truth table33%1/3
A and B
A= $features->{"response_format"}B= $self->can("_native_structured_output_for_model")
ABresult
0X0
100
111
720 81 return %decision;
721 }
722  
723 # Warns when the request's model override flips a decision (see above). The
724 # decisions for the override are read off an in-memory clone whose chat_model
725 # is the override, as Manifest::Builder probes a model (a builder-made
726 # tool_wire_format is resolved again, a constructor one kept, karr k251). A
727 # per-request value, so it warns on every request (karr k247). Diagnostic
728 # only: if the decisions cannot be computed, the request goes on unwarned and
729 # its own path reports the error.
730 594 ▶sub _warn_model_override {
Subroutine _warn_model_override: called CC=12 SCAR=24.9
731 594 my ( $self, $method, $opts, $streaming ) = @_;
732 594 my $override = $opts->{model};
733 594 ▶ return unless defined $override && !ref $override && length $override;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $override and not ref $override and length $override 550 44 594
Condition83%5/6
defined $override and not ref $override and length $override
!ll&&!rl&&r
549144
defined $override and not ref $override
!ll&&!rl&&r
549045
MC/DC66%2/3
defined $override and not ref $override and length $override
defined $override not ref $override length $override
Truth table75%3/4
A and not(B) and C
A= defined $overrideB= not ref $overrideC= length $override
ABCresult
0XX0
10X0
1100
1111
734 44 ▶ return unless $self->can('chat_model');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_model") 0 44 44
735 44 ▶ my $configured = $self->_capability_model // '';
Condition50%1/2
$self->_capability_model // ""
l!l
440
MC/DC0%0/1
$self->_capability_model // ""
$self->_capability_model
Truth table50%1/2
A
A= $self->_capability_model
Aresult
11
00
736 44 ▶ return if $override eq $configured;
Branch: 1 branch
BranchTrueFalseTotal
if $override eq $configured 3 41 44
737 41 my @flipped;
738 {
739 41 local $@;
740 41 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $features = $self->_chat_request_features($opts, $streaming); my $probe = $self->meta->clone_object($self, "chat_model", $override); $probe->_reset_derived_tool_wire_format if $probe->can("_reset_derived_tool_wire_format"); my(%mine) = $self->_model_scoped_wire_decisions($features, $opts); my(%theirs) = $probe->_model_scoped_wire_decisions($features, $opts); my(%labels) = (%mine, %theirs); @flipped = grep({($mine{$_} // "") ne ($theirs{$_} // "");} sort(keys %labels)); 1 } } or return 40 1 41
741 41 my $features = $self->_chat_request_features( $opts, $streaming );
742 41 my $probe = $self->meta->clone_object( $self, chat_model => $override );
743 41 ▶ $probe->_reset_derived_tool_wire_format if $probe->can('_reset_derived_tool_wire_format');
Branch: 1 branch
BranchTrueFalseTotal
if $probe->can("_reset_derived_tool_wire_format") 41 0 41
744 41 my %mine = $self->_model_scoped_wire_decisions( $features, $opts );
745 41 my %theirs = $probe->_model_scoped_wire_decisions( $features, $opts );
746 40 my %labels = ( %mine, %theirs );
747 40 ▶ @flipped = grep { ( $mine{$_} // '' ) ne ( $theirs{$_} // '' ) } sort keys %labels;
Condition100%4/4
$mine{$_} // ""
l!l
3087
$theirs{$_} // ""
l!l
30411
MC/DC100%1/1
$mine{$_} // ""
$mine{$_}
MC/DC100%1/1
$theirs{$_} // ""
$theirs{$_}
Truth table100%2/2
A
A= $mine{$_}
Aresult
11
00
Truth table100%2/2
A
A= $theirs{$_}
Aresult
11
00
748 40 1;
749 } or return;
750 }
751 40 ▶ return unless @flipped;
Branch: 1 branch
BranchTrueFalseTotal
unless @flipped 15 25 40
752 25 $self->_langertha_carp( "".(ref $self).": $method got a per-request model '$override' "
753 . "that differs from chat_model '$configured'; model-scoped wire decisions follow "
754 . "chat_model, and these differ for '$override': " . join( ', ', @flipped )
755 . " -- use an engine whose chat_model is '$override'" );
756 25 return;
757 }
758  
759 # The model a request goes to on a wire that names it in the URL (Gemini's
760 # models/{model}:generateContent, AKI native's /api/call/{model}): the
761 # per-request override when there is one (the same test as
762 # _warn_model_override), else chat_model. The `model` key is taken out of
763 # %extra either way: there it would only ride the body as an unknown field
764 # while the URL still named chat_model (karr k357).
765 338 ▶sub _url_model {
Subroutine _url_model: called CC=4 SCAR=13.9
766 338 my ( $self, $extra ) = @_;
767 338 my $override = delete $extra->{model};
768 338 ▶ return $override if defined $override && !ref $override && length $override;
Branch: 1 branch
BranchTrueFalseTotal
if defined $override and not ref $override and length $override 11 327 338
Condition83%5/6
defined $override and not ref $override and length $override
!ll&&!rl&&r
325211
defined $override and not ref $override
!ll&&!rl&&r
325013
MC/DC66%2/3
defined $override and not ref $override and length $override
defined $override not ref $override length $override
Truth table75%3/4
A and not(B) and C
A= defined $overrideB= not ref $overrideC= length $override
ABCresult
0XX0
10X0
1100
1111
769 327 return $self->chat_model;
770 }
771  
772 358 ▶async sub chat_f {
Subroutine chat_f: called CC=36 SCAR=36.6
Pod documented
773 358 my ( $self, %opts ) = @_;
774  
775 358 ▶ my $messages = delete $opts{messages} // [];
Condition100%2/2
delete $opts{"messages"} // []
l!l
3562
MC/DC100%1/1
delete $opts{"messages"} // []
delete $opts{"messages"}
Truth table100%2/2
A
A= delete $opts{"messages"}
Aresult
11
00
776 358 ▶ my @messages = ref $messages eq 'ARRAY' ? @$messages : ($messages);
Branch: 1 branch
BranchTrueFalseTotal
ref $messages eq 'ARRAY' ? : 358 0 358
777  
778 # Before any decision is taken for chat_model (karr k352).
779 358 $self->_warn_model_override( 'chat_f', \%opts, 0 );
780  
781 # A Langertha::ServerTool needs a wire that takes server-side tools (k206).
782 358 Langertha::ServerTool->check_engine( $self, $opts{tools} );
783  
784 # Auto-fallback: forced named tool on an engine that cannot do
785 # native named-tool-forcing but supports json_schema response_format.
786 # Rewrite tools+tool_choice into a response_format and remember the
787 # tool name so we can synthesize a tool_calls entry afterwards.
788 352 my $synth_tool_name;
789 352 ▶ if ( exists $opts{tool_choice}
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named") and $self->supports("response_format_json_schema")) 41 311 352
Condition100%9/9
exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named") and $self->supports("response_format_json_schema")
!ll&&!rl&&r
310141
exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named")
!ll&&!rl&&r
2902042
exists $opts{"tool_choice"} and exists $opts{"tools"}
!ll&&!rl&&r
288262
MC/DC100%4/4
exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named") and $self->supports("response_format_json_schema")
exists $opts{"tool_choice"} exists $opts{"tools"} not $self->supports("tool_choice_named") $self->supports("response_format_json_schema")
Truth table100%5/5
A and B and not(C) and D
A= exists $opts{"tool_choice"}B= exists $opts{"tools"}C= not $self->supports("tool_choice_named")D= $self->supports("response_format_json_schema")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
790 && exists $opts{tools}
791 && !$self->supports('tool_choice_named')
792 && $self->supports('response_format_json_schema')
793 ) {
794 41 my $tc = Langertha::ToolChoice->from_hash( $opts{tool_choice} );
795 41 ▶ if ( $tc && $tc->type eq 'tool' && defined $tc->name && length $tc->name ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc and $tc->type eq "tool" and defined $tc->name and length $tc->name) 32 9 41
Condition77%7/9
$tc and $tc->type eq "tool" and defined $tc->name and length $tc->name
!ll&&!rl&&r
9032
$tc and $tc->type eq "tool" and defined $tc->name
!ll&&!rl&&r
9032
$tc and $tc->type eq "tool"
!ll&&!rl&&r
1832
MC/DC50%2/4
$tc and $tc->type eq "tool" and defined $tc->name and length $tc->name
$tc $tc->type eq "tool" defined $tc->name length $tc->name
Truth table60%3/5
A and B and C and D
A= $tcB= $tc->type eq "tool"C= defined $tc->nameD= length $tc->name
ABCDresult
0XXX0
10XX0
110X0
11100
11111
796 32 my $name = $tc->name;
797 my ($tool) =
798 33 ▶ grep { defined $_ && $_->name eq $name }
Condition66%2/3
defined $_ && $_->name eq $name
!ll&&!rl&&r
0231
MC/DC50%1/2
defined $_ && $_->name eq $name
defined $_ $_->name eq $name
Truth table66%2/3
A && B
A= defined $_B= $_->name eq $name
ABresult
0X0
100
111
799 33 map { Langertha::Tool->from_hash($_) }
800 32 @{ $opts{tools} };
801 32 ▶ if ($tool) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tool) 31 1 32
802 31 $self->_chat_rewrite_replaces_response_format( \%opts, $name );
803 22 delete $opts{tools};
804 22 delete $opts{tool_choice};
805 $opts{response_format} = {
806 type => 'json_schema',
807 json_schema => {
808 22 %{ $tool->to_json_schema },
809 strict => JSON->true,
810 },
811 };
812 22 $synth_tool_name = $name;
813 22 $log->debugf("[%s] forced-tool fallback: tool '%s' rerouted via response_format",
814 ref $self, $name);
815 }
816 }
817 }
818  
819 # Provider mutual-exclusion guard (karr #148). Consulted after the
820 # forced-tool fallback (which may have set response_format) so it sees the
821 # effective request; walks the per-model exclusion table for the selected
822 # chat_model and croaks on a combination the model rejects with an opaque 400.
823 $self->_check_capability_exclusions(
824 343 has_tools => $self->_chat_tools_requested(\%opts),
825 tool_choice_forced => $self->_chat_tool_choice_forced(\%opts),
826 response_format => $self->_chat_effective_response_format(\%opts),
827 streaming => 0,
828 );
829  
830 # Extract the canonical controls (after the forced-tool fallback, which may
831 # have set response_format) and hand them to chat_request under `controls`.
832 320 my $controls = $self->_extract_controls(\%opts);
833  
834 320 @messages = await $self->_prefetch_inline_images_f(@messages);
835 309 my ( $conversation, $hermes_prompted ) =
836 $self->_hermes_prompt_tools( \%opts, $self->chat_messages(@messages) );
837 308 ▶ $opts{tools} = $self->_wire_tools( $opts{tools} ) if ref $opts{tools} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts{"tools"} eq "ARRAY" 92 216 308
838  
839 308 $conversation = $self->_hermes_prompt_schema( $controls, $conversation );
840  
841 308 my $t0 = [gettimeofday];
842 308 ▶ my $request = $self->chat_request( $conversation,
Branch: 1 branch
BranchTrueFalseTotal
%$controls ? : 68 240 308
843 ( %$controls ? ( controls => $controls ) : () ),
844 %opts );
845  
846 308 my $response = await $self->_async_do_request_f( request => $request );
847  
848 # A failed response records its rate limit before the die (a success does it
849 # in parse_response), so a caller can back off from a 429 (karr k300).
850 305 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 26 279 305
851 26 ▶ $self->_update_rate_limit($response) if $self->can('_update_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_update_rate_limit") 26 0 26
852 # The sync croak's text, body included (karr k312).
853 26 die $self->_request_failed_message( $response, 'request' );
854 }
855  
856 279 my $elapsed = tv_interval($t0);
857 279 my $result = $request->response_call->($response);
858  
859 272 ▶ if ( blessed($result) && $result->isa('Langertha::Response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->isa("Langertha::Response")) 272 0 272
Condition33%1/3
builtin::blessed($result) and $result->isa("Langertha::Response")
!ll&&!rl&&r
00272
MC/DC0%0/2
builtin::blessed($result) and $result->isa("Langertha::Response")
builtin::blessed($result) $result->isa("Langertha::Response")
Truth table33%1/3
A and B
A= builtin::blessed($result)B= $result->isa("Langertha::Response")
ABresult
0X0
100
111
860 272 $result = $result->clone_with(
861 timing => _merge_timing_field( $result->timing, total_seconds => $elapsed ),
862 );
863 }
864  
865 # One chat_with_tools_f turn on hermes (k231): the <tool_call> blocks the
866 # model wrote go onto Response.tool_calls (ADR 0003), out of content. An
867 # engine whose chat_response already lifted them (AKI native) is left alone.
868 272 ▶ if ( $hermes_prompted && blessed($result) && $result->isa('Langertha::Response')
Branch: 1 branch
BranchTrueFalseTotal
if ($hermes_prompted and builtin::blessed($result) and $result->isa("Langertha::Response") and not $result->has_tool_calls && @{$result->tool_calls;}) 31 241 272
Condition75%9/12
$hermes_prompted and builtin::blessed($result) and $result->isa("Langertha::Response") and not $result->has_tool_calls && @{$result->tool_calls;}
!ll&&!rl&&r
240131
$hermes_prompted and builtin::blessed($result) and $result->isa("Langertha::Response")
!ll&&!rl&&r
240032
$hermes_prompted and builtin::blessed($result)
!ll&&!rl&&r
240032
$result->has_tool_calls && @{$result->tool_calls;}
!ll&&!rl&&r
3101
MC/DC40%2/5
$hermes_prompted and builtin::blessed($result) and $result->isa("Langertha::Response") and not $result->has_tool_calls && @{$result->tool_calls;}
$hermes_prompted builtin::blessed($result) $result->isa("Langertha::Response") $result->has_tool_calls @{$result->tool_calls;}
Truth table50%3/6
A and B and C and not(D && E)
A= $hermes_promptedB= builtin::blessed($result)C= $result->isa("Langertha::Response")D= $result->has_tool_callsE= @{$result->tool_calls;}
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
869 1 && !( $result->has_tool_calls && @{ $result->tool_calls } ) ) {
870 31 my ( $clean, $calls ) = $self->_hermes_split_text( $result->content );
871 31 ▶ if (@$calls) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$calls) 14 17 31
872 # The reply ended to call tools: report that over the wire's stop, as the
873 # OpenAI dialect does for native calls (k248); ->raw keeps the wire value.
874 14 my $reason = $result->finish_reason;
875 14 ▶ $result = $result->clone_with( content => $clean, tool_calls => $calls,
Branch: 1 branch
BranchTrueFalseTotal
!length($reason // '') || $reason eq 'stop' ? : 13 1 14
Condition60%3/5
not length($reason // "") or $reason eq "stop"
l!l&&r!l&&!r
0131
$reason // ""
l!l
140
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
876 ( !length( $reason // '' ) || $reason eq 'stop' ) ? ( finish_reason => 'tool_calls' ) : () );
877 }
878 }
879  
880 272 ▶ if ( $synth_tool_name && blessed($result) && $result->isa('Langertha::Response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($synth_tool_name and builtin::blessed($result) and $result->isa("Langertha::Response")) 22 250 272
Condition66%4/6
$synth_tool_name and builtin::blessed($result) and $result->isa("Langertha::Response")
!ll&&!rl&&r
250022
$synth_tool_name and builtin::blessed($result)
!ll&&!rl&&r
250022
MC/DC33%1/3
$synth_tool_name and builtin::blessed($result) and $result->isa("Langertha::Response")
$synth_tool_name builtin::blessed($result) $result->isa("Langertha::Response")
Truth table50%2/4
A and B and C
A= $synth_tool_nameB= builtin::blessed($result)C= $result->isa("Langertha::Response")
ABCresult
0XX0
10X0
1100
1111
881 22 my $args = $self->decode_loose_json( $result->content );
882 # A tool's arguments are a JSON object. Only synthesize the ToolCall when the
883 # model actually returned one — a non-object result (e.g. a bare JSON array)
884 # would otherwise be coerced to empty {} in Response BUILDARGS and the
885 # synthetic call would falsely claim success with no arguments. Leaving
886 # tool_calls unset lets the caller see the gap (the raw content is still on
887 # Response.content) instead of a hollow success.
888 22 ▶ if ( ref $args eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args eq 'HASH') { } 19 3 22
889 19 $result = $result->clone_with(
890 tool_calls => [{
891 name => $synth_tool_name,
892 arguments => $args,
893 synthetic => 1,
894 }],
895 );
896 }
897 else {
898 3 $log->debugf(
899 "[%s] forced-tool fallback: '%s' response was not a JSON object; no synthetic tool_call attached",
900 ref $self, $synth_tool_name);
901 }
902 }
903  
904 272 ▶ if ( $self->can('has_rate_limit') && $self->has_rate_limit
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")) 6 266 272
Condition66%6/9
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")
!ll&&!rl&&r
26606
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result
!ll&&!rl&&r
26606
$self->can("has_rate_limit") and $self->has_rate_limit
!ll&&!rl&&r
02666
MC/DC25%1/4
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")
$self->can("has_rate_limit") $self->has_rate_limit ref $result $result->isa("Langertha::Response")
Truth table40%2/5
A and B and C and D
A= $self->can("has_rate_limit")B= $self->has_rate_limitC= ref $resultD= $result->isa("Langertha::Response")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
905 && ref $result && $result->isa('Langertha::Response') ) {
906 6 $result = $result->clone_with( rate_limit => $self->rate_limit );
907 }
908 272 return $result;
909 194 }
910  
911  
912  
913 1 ▶sub simple_chat_stream_f {
Subroutine simple_chat_stream_f: called CC=1 SCAR=0.0
Pod documented
914 1 my ($self, @messages) = @_;
915 1 return $self->simple_chat_stream_realtime_f(undef, @messages);
916 }
917  
918  
919 7 ▶async sub simple_chat_stream_realtime_f {
Subroutine simple_chat_stream_realtime_f: called CC=1 SCAR=0.0
Pod documented
920 7 my ($self, $chunk_callback, @messages) = @_;
921  
922 7 return await $self->chat_stream_realtime_f(
923 messages => \@messages,
924 chunk_callback => $chunk_callback,
925 );
926 194 }
927  
928 227 ▶async sub chat_stream_realtime_f {
Subroutine chat_stream_realtime_f: called CC=16 SCAR=27.9
Pod documented
929 227 my ( $self, %opts ) = @_;
930  
931 227 my $chunk_callback = delete $opts{chunk_callback};
932 227 ▶ my $messages = delete $opts{messages} // [];
Condition50%1/2
delete $opts{"messages"} // []
l!l
2270
MC/DC0%0/1
delete $opts{"messages"} // []
delete $opts{"messages"}
Truth table50%1/2
A
A= delete $opts{"messages"}
Aresult
11
00
933 227 ▶ my @messages = ref $messages eq 'ARRAY' ? @$messages : ($messages);
Branch: 1 branch
BranchTrueFalseTotal
ref $messages eq 'ARRAY' ? : 227 0 227
934  
935 227 ▶ croak "".(ref $self)." does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_stream_request") 1 226 227
936 unless $self->can('chat_stream_request');
937  
938 # Before any decision is taken for chat_model (karr k352).
939 226 $self->_warn_model_override( 'chat_stream_realtime_f', \%opts, 1 );
940  
941 # A Langertha::ServerTool needs a wire that takes server-side tools (k206).
942 226 Langertha::ServerTool->check_engine( $self, $opts{tools} );
943  
944 # Provider mutual-exclusion guard (karr #148) — streaming path. Same per-model
945 # seam as chat_f; the streaming flag lets a rule refuse a combination that is
946 # rejected only when streaming (e.g. Groq structured outputs, which do not
947 # support streaming at all).
948 226 $self->_check_capability_exclusions(
949 has_tools => $self->_chat_tools_requested(\%opts),
950 tool_choice_forced => $self->_chat_tool_choice_forced(\%opts),
951 response_format => $self->_chat_effective_response_format(\%opts),
952 streaming => 1,
953 );
954  
955 # Same canonical-control extraction as chat_f (karr #46).
956 221 my $controls = $self->_extract_controls(\%opts);
957  
958 221 @messages = await $self->_prefetch_inline_images_f(@messages);
959 221 my ( $conversation, $hermes_prompted ) =
960 $self->_hermes_prompt_tools( \%opts, $self->chat_messages(@messages) );
961 221 $conversation = $self->_hermes_prompt_schema( $controls, $conversation );
962 221 ▶ $opts{tools} = $self->_wire_tools( $opts{tools} ) if ref $opts{tools} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts{"tools"} eq "ARRAY" 7 214 221
963  
964 221 ▶ my $request = $self->chat_stream_request( $conversation,
Branch: 1 branch
BranchTrueFalseTotal
%$controls ? : 3 218 221
965 ( %$controls ? ( controls => $controls ) : () ),
966 %opts );
967 215 my @all_chunks;
968 215 my $buffer = '';
969 215 my %stream_state; # this stream's parse state (tool-call fragments, karr k221)
970 215 my $format = $self->stream_format;
971 215 my $response_status;
972 my $error_content; # the body of a non-2xx response
973 215 my $t0 = [gettimeofday];
974 215 my $ttft_seconds;
975  
976 # Every parsed chunk goes out through here. When the tools rode the hermes
977 # prompt, the <tool_call> blocks are withheld from the text and their calls
978 # land on the final chunk, as chat_f lifts them from its reply (karr k253).
979 my %hermes_state;
980 # $flush (no chunk) asks the lift for what a stream without a final chunk
981 # still owes.
982 1911 ▶ my $deliver = sub {
Subroutine __ANON__: called CC=7 SCAR=19.6
983 1911 my ( $chunk, $flush ) = @_;
984 1911 ▶ $ttft_seconds = tv_interval($t0) unless defined $ttft_seconds || $flush;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ttft_seconds or $flush 198 1713 1911
Condition66%2/3
defined $ttft_seconds or $flush
l!l&&r!l&&!r
17130198
MC/DC50%1/2
defined $ttft_seconds or $flush
defined $ttft_seconds $flush
Truth table66%2/3
A or B
A= defined $ttft_secondsB= $flush
ABresult
1X1
011
000
985 1911 ▶ if ($hermes_prompted) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hermes_prompted) 1649 262 1911
986 1649 $chunk = $self->_hermes_stream_chunk( \%hermes_state, $chunk, $flush );
987 1649 ▶ return unless $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless $chunk 1154 495 1649
988 }
989 757 ▶ $ttft_seconds //= tv_interval($t0);
Condition33%1/3
$ttft_seconds //= tv_interval($t0)
l!l&&r!l&&!r
75700
MC/DC0%0/2
$ttft_seconds //= tv_interval($t0)
$ttft_seconds tv_interval($t0)
Truth table33%1/3
A //= B
A= $ttft_secondsB= tv_interval($t0)
ABresult
1X1
011
000
990 757 push @all_chunks, $chunk;
991 757 ▶ $chunk_callback->($chunk) if $chunk_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_callback 611 146 757
992 215 };
993  
994 # A die in the chunk-sub (a malformed stream line, or the caller's
995 # chunk_callback) must fail this request's future on every backend, and must
996 # not unwind into the backend: Net::Async::HTTP runs the chunk-sub inside
997 # the loop's read handler, where a die escapes the loop and leaves this
998 # request pending (karr k194, ADR 0027).
999 215 my ( $request_f, $stream_error );
1000 $request_f = $self->_async_do_request_f(
1001 request => $request,
1002 212 ▶ on_header => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1003 212 my ($response) = @_;
1004 212 $response_status = $response;
1005  
1006 # A non-2xx body is the provider's error, not a stream: keep it for the
1007 # error text (the sync croak shows it, karr k312) instead of parsing it.
1008 # Net::Async::HTTP hands the header response without the body.
1009 212 ▶ unless ( $response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 10 202 212
1010 10 $error_content = '';
1011 10 ▶ return sub { $error_content .= $_[0] if defined $_[0] };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[0] 10 10 20
1012 }
1013  
1014 # Return a callback that handles each body chunk
1015 2116 ▶ return sub {
Subroutine __ANON__: called CC=10 SCAR=23.0
1016 2116 my ($data) = @_;
1017 2116 ▶ return if $stream_error; # already failed; drop the rest
Branch: 1 branch
BranchTrueFalseTotal
if $stream_error 15 2101 2116
1018 2101 ▶ return unless defined $data; # undef signals end of body
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 181 1920 2101
1019  
1020 1920 my $ok = eval {
1021 1920 $buffer .= $data;
1022 1920 my $chunks = $self->_process_stream_buffer(\$buffer, $format, 0, \%stream_state);
1023 1912 $deliver->($_) for @$chunks;
1024 1902 1;
1025 };
1026 1920 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 1902 18 1920
1027 18 ▶ $stream_error = [ $@ || "streaming callback died\n", http => $response, $request ];
Condition50%1/2
$@ || "streaming callback died\n"
l!l
180
MC/DC0%0/1
$@ || "streaming callback died\n"
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1028  
1029 # A synchronous backend (Langertha::Request::SyncHTTP) runs the
1030 # chunk-sub before do_request returns: die again so it stops reading
1031 # and fails its own future with the original exception.
1032 18 ▶ die $stream_error->[0] unless $request_f;
Branch: 1 branch
BranchTrueFalseTotal
unless $request_f 5 13 18
1033  
1034 # An event-loop backend must not be stopped from in here. Cancelling
1035 # a Net::Async::HTTP request closes its connection, and doing that
1036 # inside its read handler leaves the rest of an already-read burst
1037 # in the buffer of a connection with no request left, which
1038 # Net::Async::HTTP then dies on ("Spurious on_read"). Cancel on the
1039 # next loop iteration instead, once this read is fully processed; if
1040 # the response completes within this read there is nothing to cancel.
1041 # A future without an IO::Async-style loop (an injected client with
1042 # no loop, or one from another event system) is drained.
1043 13 ▶ my $loop = $request_f->can('loop') && $request_f->loop;
Condition66%2/3
$request_f->can('loop') && $request_f->loop
!ll&&!rl&&r
1012
MC/DC50%1/2
$request_f->can('loop') && $request_f->loop
$request_f->can('loop') $request_f->loop
Truth table66%2/3
A && B
A= $request_f->can('loop')B= $request_f->loop
ABresult
0X0
100
111
1044 11 ▶ $loop->later(sub { $request_f->cancel unless $request_f->is_ready })
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless $request_f->is_ready 5 6 11
1045 13 ▶ if $loop && $loop->can('later');
Branch: 1 branch
BranchTrueFalseTotal
if $loop and $loop->can("later") 11 2 13
Condition100%3/3
$loop and $loop->can("later")
!ll&&!rl&&r
1111
MC/DC100%2/2
$loop and $loop->can("later")
$loop $loop->can("later")
Truth table100%3/3
A and B
A= $loopB= $loop->can("later")
ABresult
0X0
100
111
1046 13 return;
1047 202 };
1048 },
1049 215 );
1050  
1051 # Wait for the transfer to end however it ends: done, failed, or cancelled
1052 # above. A cancel from our own caller still stops the transfer.
1053 215 my $transfer_f = $request_f->new;
1054 215 ▶ $request_f->on_ready(sub { $transfer_f->done unless $transfer_f->is_ready });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
unless $transfer_f->is_ready 215 0 215
1055 215 ▶ $transfer_f->on_cancel(sub { $request_f->cancel unless $request_f->is_ready });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
unless $request_f->is_ready 3 0 3
1056 215 await $transfer_f;
1057 # The headers arrived, so their rate limit is this response's, whatever
1058 # happens to the body or the status next (karr k300). Taken here, not in
1059 # on_header, which may run inside the event loop's read handler.
1060 212 ▶ $self->_update_rate_limit($response_status)
Branch: 1 branch
BranchTrueFalseTotal
if $response_status and $self->can("_update_rate_limit") 210 2 212
Condition66%2/3
$response_status and $self->can("_update_rate_limit")
!ll&&!rl&&r
20210
MC/DC50%1/2
$response_status and $self->can("_update_rate_limit")
$response_status $self->can("_update_rate_limit")
Truth table66%2/3
A and B
A= $response_statusB= $self->can("_update_rate_limit")
ABresult
0X0
100
111
1061 if $response_status && $self->can('_update_rate_limit');
1062 # The exception that stopped the stream wins over any transport failure
1063 # seen afterwards (from the cancel, a drain, or the connection itself).
1064 212 ▶ await Future->fail(@$stream_error) if $stream_error;
Branch: 1 branch
BranchTrueFalseTotal
if $stream_error 18 194 212
1065 194 ▶ await $request_f if $request_f->is_failed;
Branch: 1 branch
BranchTrueFalseTotal
if $request_f->is_failed 2 192 194
1066  
1067 192 ▶ unless ($response_status->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response_status->is_success) 10 181 191
1068 10 my $failed = $response_status->clone;
1069 10 ▶ $failed->content($error_content) if defined $error_content;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error_content 10 0 10
1070 10 die $self->_request_failed_message( $failed, 'streaming request' );
1071 }
1072  
1073 # Process remaining buffer
1074 181 ▶ if ($buffer ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffer ne "") 0 181 181
1075 0 my $chunks = $self->_process_stream_buffer(\$buffer, $format, 1, \%stream_state);
1076 0 $deliver->($_) for @$chunks;
1077 }
1078 # A hermes stream that ended without a final chunk still owes its held text
1079 # (a partial or unclosed tag is text) and the calls of its closed blocks.
1080 181 ▶ $deliver->( undef, 1 ) if $hermes_prompted;
Branch: 1 branch
BranchTrueFalseTotal
if $hermes_prompted 119 62 181
1081 # The stream ended: let the dialect report what it could not finish (a
1082 # tool call that never saw its finish_reason, karr k221).
1083 181 ▶ $self->_finish_stream_state(\%stream_state) if $self->can('_finish_stream_state');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_finish_stream_state") 179 2 181
1084  
1085 181 my $content = join('', map { $_->content } @all_chunks);
1086 181 my $thinking = $self->aggregate_thinking(\@all_chunks);
1087 181 my $total_seconds = tv_interval($t0);
1088 181 return ($content, \@all_chunks, {
1089 ttft_seconds => $ttft_seconds,
1090 total_seconds => $total_seconds,
1091 }, $thinking);
1092 194 }
1093  
1094 # Decides a caller's tool_choice against supports('tool_choice_*'), in place,
1095 # for every request builder whose wire field may be missing (karr k239, the
1096 # k233 Responses rule generalized; ADR 0002: field emission follows the
1097 # claimed capability). Returns the Langertha::ToolChoice to serialize when the
1098 # engine supports its kind; the builder calls ->to($fmt) itself, since only it
1099 # knows its envelope. Otherwise the field is deleted: undef or 'auto' (the
1100 # wire default) silently; 'none' withholds the request's tools too, so "call
1101 # no tool" holds without the field, with a carp when there were tools to
1102 # withhold (none without tools is silent, as on the hermes wire, k246); a
1103 # forced choice (any /
1104 # named) with a carp, the model then decides. chat_f's ADR 0005 rewrite runs
1105 # first and has already taken a forced named tool it could reroute. A value
1106 # ToolChoice cannot read (a provider-native choice) stays as given where the
1107 # wire has a tool_choice field at all, and is dropped with a carp where not.
1108 2483 ▶sub _gate_tool_choice {
Subroutine _gate_tool_choice: called CC=14 SCAR=26.4
1109 2483 my ( $self, $extra ) = @_;
1110 2483 ▶ return unless exists $extra->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $extra->{"tool_choice"} 2376 107 2483
1111 107 my $has_field = grep { $self->supports("tool_choice_$_") } qw( auto any none named );
1112 107 ▶ unless ( defined $extra->{tool_choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $extra->{"tool_choice"}) 4 103 107
1113 4 ▶ delete $extra->{tool_choice} unless $has_field;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_field 4 0 4
1114 4 return;
1115 }
1116 103 my $tc = Langertha::ToolChoice->from_hash( $extra->{tool_choice} );
1117 103 ▶ unless ($tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tc) 5 98 103
1118 5 ▶ return if $has_field;
Branch: 1 branch
BranchTrueFalseTotal
if $has_field 3 2 5
1119 2 delete $extra->{tool_choice};
1120 2 $self->_langertha_carp( "".( ref $self ).": dropping tool_choice -- this engine has no tool_choice "
1121 . "field and the value is not one Langertha can read; the model decides whether to call a tool" );
1122 2 return;
1123 }
1124 98 ▶ my $cap = $tc->type eq 'tool' ? 'tool_choice_named' : 'tool_choice_' . $tc->type;
Branch: 1 branch
BranchTrueFalseTotal
$tc->type eq 'tool' ? : 26 72 98
1125 98 ▶ return $tc if $self->supports($cap);
Branch: 1 branch
BranchTrueFalseTotal
if $self->supports($cap) 36 62 98
1126 62 delete $extra->{tool_choice};
1127 62 ▶ if ( $tc->type eq 'none' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc->type eq "none") 24 38 62
1128 24 my $tools = delete $extra->{tools};
1129 24 ▶ $self->_langertha_carp( "".( ref $self ).": dropping tool_choice 'none' -- this engine does not "
Branch: 1 branch
BranchTrueFalseTotal
if ref $tools eq "ARRAY" and @$tools 10 14 24
Condition100%3/3
ref $tools eq "ARRAY" and @$tools
!ll&&!rl&&r
10410
MC/DC100%2/2
ref $tools eq "ARRAY" and @$tools
ref $tools eq "ARRAY" @$tools
Truth table100%3/3
A and B
A= ref $tools eq "ARRAY"B= @$tools
ABresult
0X0
100
111
1130 . "support('tool_choice_none'); the request's tools are withheld instead" )
1131 if ref $tools eq 'ARRAY' && @$tools;
1132 24 return;
1133 }
1134 38 ▶ $self->_langertha_carp( "".( ref $self ).": dropping tool_choice '"
Branch: 2 branches
BranchTrueFalseTotal
unless $tc->type eq "auto" 25 13 38
$tc->type eq 'tool' ? : 13 12 25
Condition50%1/2
$tc->name // ""
l!l
130
MC/DC0%0/1
$tc->name // ""
$tc->name
Truth table50%1/2
A
A= $tc->name
Aresult
11
00
1135 . ( $tc->type eq 'tool' ? 'tool ' . ( $tc->name // '' ) : $tc->type )
1136 . "' -- this engine does not support('$cap'); the model decides whether to call a tool" )
1137 unless $tc->type eq 'auto';
1138 38 return;
1139 }
1140  
1141 # parallel_tool_use -> parallel_tool_calls, in place, for the Chat Completions
1142 # and Responses builders alike (streaming too, karr k240); Ollama native and
1143 # Gemini call it only for the drop carp (flag cleared, k241). Only when tools are
1144 # present. A per-request control beats the engine attribute; an explicit
1145 # parallel_tool_calls kwarg is the caller's wire intent and wins over both.
1146 # Emitted only where the engine supports('parallel_tool_use') (karr k241, ADR
1147 # 0002); a value the caller set that the gate drops carps (ADR 0025
1148 # drop+carp), nothing set stays silent.
1149 2782 ▶sub _parallel_tool_calls_kwarg {
Subroutine _parallel_tool_calls_kwarg: called CC=10 SCAR=23.0
1150 2782 my ( $self, $extra, $controls ) = @_;
1151 2782 ▶ return unless exists $extra->{tools} && !exists $extra->{parallel_tool_calls};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $extra->{"tools"} and not exists $extra->{"parallel_tool_calls"} 2331 451 2782
Condition100%3/3
exists $extra->{"tools"} and not exists $extra->{"parallel_tool_calls"}
!ll&&!rl&&r
231912451
MC/DC100%2/2
exists $extra->{"tools"} and not exists $extra->{"parallel_tool_calls"}
exists $extra->{"tools"} not exists $extra->{"parallel_tool_calls"}
Truth table100%3/3
A and not(B)
A= exists $extra->{"tools"}B= not exists $extra->{"parallel_tool_calls"}
ABresult
0X0
100
111
1152 451 my ( $ptu, $from_attr );
1153 451 ▶ if ( exists $controls->{parallel_tool_use} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $controls->{'parallel_tool_use'}) { } 41 410 451
elsif ($self->can('has_parallel_tool_use') and $self->has_parallel_tool_use) { } 24 386 410
1154 41 $ptu = $controls->{parallel_tool_use};
1155 }
1156 ▶ elsif ( $self->can('has_parallel_tool_use') && $self->has_parallel_tool_use ) {
Condition66%2/3
$self->can("has_parallel_tool_use") and $self->has_parallel_tool_use
!ll&&!rl&&r
038624
MC/DC50%1/2
$self->can("has_parallel_tool_use") and $self->has_parallel_tool_use
$self->can("has_parallel_tool_use") $self->has_parallel_tool_use
Truth table66%2/3
A and B
A= $self->can("has_parallel_tool_use")B= $self->has_parallel_tool_use
ABresult
0X0
100
111
1157 24 $ptu = $self->parallel_tool_use;
1158 24 $from_attr = 1;
1159 }
1160 451 ▶ return unless defined $ptu;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ptu 386 65 451
1161 65 ▶ unless ( $self->supports('parallel_tool_use') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->supports("parallel_tool_use")) 45 20 65
1162 45 ▶ $self->_langertha_carp( "".( ref $self ).": dropping parallel_tool_use -- this engine does not "
Branch: 1 branch
BranchTrueFalseTotal
$from_attr ? : 20 25 45
1163 . "support('parallel_tool_use'); the provider decides how many tool calls a turn has",
1164 $from_attr ? "parallel_tool_use=$ptu" : undef );
1165 45 return;
1166 }
1167 20 ▶ $extra->{parallel_tool_calls} = $ptu ? JSON->true : JSON->false;
Branch: 1 branch
BranchTrueFalseTotal
$ptu ? : 9 11 20
1168 20 return;
1169 }
1170  
1171 # The one path that puts a caller's tools list on the wire, for chat_f and
1172 # chat_stream_realtime_f alike (karr k221, k227; ADR 0001). A tools list is
1173 # often built by hand: Langertha::Tool / ServerTool objects next to hashes of
1174 # any shape. The JSON encoder would put an object on the wire in its canonical
1175 # to_hash shape, which only the Anthropic wire reads, so the value objects
1176 # shape the list for this engine's tool_wire_format, item by item and in the
1177 # caller's order (Langertha::Tool->request_list): objects serialize, hashes
1178 # already in the wire's shape pass through verbatim (extras and built-ins
1179 # included), other function-tool hashes convert. Order is caller intent, and
1180 # an Anthropic cache_control breakpoint caches the prefix of the list.
1181 # Left alone: an engine without Role::Tools, and the Responses envelope,
1182 # which already decides per item itself and needs the ServerTool objects for
1183 # its engine hook and default-tool dedup (_responses_tools_kwarg, k210/k206).
1184 # The hermes wire never gets here: _hermes_prompt_tools took the list off.
1185 101 ▶sub _wire_tools {
Subroutine _wire_tools: called CC=3 SCAR=11.0
1186 101 my ( $self, $tools ) = @_;
1187 101 ▶ return $tools unless $self->can('tool_wire_format');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("tool_wire_format") 0 101 101
1188 101 my $fmt = $self->tool_wire_format;
1189 101 ▶ return $tools if $fmt eq 'responses';
Branch: 1 branch
BranchTrueFalseTotal
if $fmt eq "responses" 8 93 101
1190 93 return Langertha::Tool->request_list( $fmt, $tools );
1191 }
1192  
1193 # The hermes wire has no tools or tool_choice body key: the tools ride the
1194 # system prompt (Role::HermesTools). A chat_f / chat_stream_realtime_f turn is
1195 # built as one chat_with_tools_f turn (karr k231, ADR 0001): the list goes
1196 # through the same format_tools and prompt builder, and neither key reaches
1197 # the body. tool_choice none withholds the tools (no prompt, so no reply
1198 # lift either; the Responses rule of k233). The prompt cannot force a tool,
1199 # so any other choice but auto (or undef, no choice) is ignored with a carp.
1200 # Returns the conversation to send and whether the tool prompt was put in
1201 # front of it.
1202 530 ▶sub _hermes_prompt_tools {
Subroutine _hermes_prompt_tools: called CC=12 SCAR=24.9
1203 530 my ( $self, $opts, $conversation ) = @_;
1204 530 ▶ return ( $conversation, 0 )
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("tool_wire_format") and $self->tool_wire_format eq "hermes" 352 178 530
Condition100%3/3
$self->can("tool_wire_format") and $self->tool_wire_format eq "hermes"
!ll&&!rl&&r
1351178
MC/DC100%2/2
$self->can("tool_wire_format") and $self->tool_wire_format eq "hermes"
$self->can("tool_wire_format") $self->tool_wire_format eq "hermes"
Truth table100%3/3
A and B
A= $self->can("tool_wire_format")B= $self->tool_wire_format eq "hermes"
ABresult
0X0
100
111
1205 unless $self->can('tool_wire_format') && $self->tool_wire_format eq 'hermes';
1206 178 my $tools = delete $opts->{tools};
1207 178 my $given = delete $opts->{tool_choice};
1208 178 ▶ my $choice = defined $given ? Langertha::ToolChoice->from_hash($given) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $given ? : 8 170 178
1209 178 ▶ my $type = $choice ? $choice->type : '';
Branch: 1 branch
BranchTrueFalseTotal
$choice ? : 8 170 178
1210 178 ▶ if ( $type eq 'none' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "none") 3 175 178
1211 3 ▶ $self->_langertha_carp( "".(ref $self).": tool_choice none on the hermes tool wire: "
Branch: 1 branch
BranchTrueFalseTotal
if ref $tools eq "ARRAY" and @$tools 3 0 3
Condition33%1/3
ref $tools eq "ARRAY" and @$tools
!ll&&!rl&&r
003
MC/DC0%0/2
ref $tools eq "ARRAY" and @$tools
ref $tools eq "ARRAY" @$tools
Truth table33%1/3
A and B
A= ref $tools eq "ARRAY"B= @$tools
ABresult
0X0
100
111
1212 . "the tools were withheld from the system prompt" )
1213 if ref $tools eq 'ARRAY' && @$tools;
1214 3 return ( $conversation, 0 );
1215 }
1216 175 ▶ $self->_langertha_carp( "".(ref $self).": tool_choice is ignored on the hermes tool wire "
Branch: 1 branch
BranchTrueFalseTotal
if defined $given and $type ne "auto" 3 172 175
Condition100%3/3
defined $given and $type ne "auto"
!ll&&!rl&&r
17023
MC/DC100%2/2
defined $given and $type ne "auto"
defined $given $type ne "auto"
Truth table100%3/3
A and B
A= defined $givenB= $type ne "auto"
ABresult
0X0
100
111
1217 . "(tools ride the system prompt, which cannot force a tool)" )
1218 if defined $given && $type ne 'auto';
1219 175 ▶ return ( $conversation, 0 ) unless ref $tools eq 'ARRAY' && @$tools;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tools eq "ARRAY" and @$tools 20 155 175
Condition100%3/3
ref $tools eq "ARRAY" and @$tools
!ll&&!rl&&r
191155
MC/DC100%2/2
ref $tools eq "ARRAY" and @$tools
ref $tools eq "ARRAY" @$tools
Truth table100%3/3
A and B
A= ref $tools eq "ARRAY"B= @$tools
ABresult
0X0
100
111
1220 155 return ( $self->_hermes_tool_messages( $conversation, $self->format_tools($tools) ), 1 );
1221 }
1222  
1223 # On the hermes wire a json_schema response_format -- the caller's, the
1224 # engine's, or the ADR 0005 rewrite's -- also rides a leading system message
1225 # (karr k234), so a backend that ignores response_format still sees the
1226 # schema. Only on an engine whose wire takes response_format (NousResearch).
1227 529 ▶sub _hermes_prompt_schema {
Subroutine _hermes_prompt_schema: called CC=7 SCAR=19.5
1228 529 my ( $self, $controls, $conversation ) = @_;
1229 529 ▶ return $conversation
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("tool_wire_format") and $self->tool_wire_format eq "hermes" and $self->supports("response_format_json_schema") 355 174 529
Condition100%6/6
$self->can("tool_wire_format") and $self->tool_wire_format eq "hermes" and $self->supports("response_format_json_schema")
!ll&&!rl&&r
3523174
$self->can("tool_wire_format") and $self->tool_wire_format eq "hermes"
!ll&&!rl&&r
1351177
MC/DC100%3/3
$self->can("tool_wire_format") and $self->tool_wire_format eq "hermes" and $self->supports("response_format_json_schema")
$self->can("tool_wire_format") $self->tool_wire_format eq "hermes" $self->supports("response_format_json_schema")
Truth table100%4/4
A and B and C
A= $self->can("tool_wire_format")B= $self->tool_wire_format eq "hermes"C= $self->supports("response_format_json_schema")
ABCresult
0XX0
10X0
1100
1111
1230 unless $self->can('tool_wire_format') && $self->tool_wire_format eq 'hermes'
1231 && $self->supports('response_format_json_schema');
1232 my $format = exists $controls->{response_format} ? $controls->{response_format}
1233 174 ▶ : ( $self->can('has_response_format') && $self->has_response_format ) ? $self->response_format
Branch: 2 branches
BranchTrueFalseTotal
exists $controls->{'response_format'} ? : 14 160 174
$self->can('has_response_format') && $self->has_response_format ? : 1 159 160
Condition66%2/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
01591
MC/DC50%1/2
$self->can("has_response_format") and $self->has_response_format
$self->can("has_response_format") $self->has_response_format
Truth table66%2/3
A and B
A= $self->can("has_response_format")B= $self->has_response_format
ABresult
0X0
100
111
1234 : undef;
1235 174 return $self->_hermes_schema_messages( $conversation, $format );
1236 }
1237  
1238 146 ▶sub aggregate_tool_calls {
Subroutine aggregate_tool_calls: called CC=4 SCAR=13.9
Pod documented
1239 146 my ( $self, $chunks ) = @_;
1240 146 ▶ return [] unless ref($chunks) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $chunks eq "ARRAY" 0 146 146
1241 146 my @tcs;
1242 146 for my $c (@$chunks) {
1243 604 ▶ next unless eval { $c->has_tool_calls };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $c->has_tool_calls } } 464 140 604
1244 140 push @tcs, @{ $c->tool_calls };
1245 }
1246 146 return \@tcs;
1247 }
1248  
1249  
1250 197 ▶sub aggregate_thinking {
Subroutine aggregate_thinking: called CC=6 SCAR=17.9
Pod documented
1251 197 my ( $self, $chunks ) = @_;
1252 197 ▶ return undef unless ref($chunks) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $chunks eq "ARRAY" 1 196 197
1253 196 my $thinking = '';
1254 196 my $seen = 0;
1255 196 for my $c (@$chunks) {
1256 790 ▶ my $t = eval { $c->has_thinking ? $c->thinking : undef };
Branch: 1 branch
BranchTrueFalseTotal
$c->has_thinking ? : 25 765 790
1257 790 ▶ next unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 765 25 790
1258 25 $thinking .= $t;
1259 25 $seen = 1;
1260 }
1261 196 ▶ return $seen ? $thinking : undef;
Branch: 1 branch
BranchTrueFalseTotal
$seen ? : 12 184 196
1262 }
1263  
1264  
1265 # Every dialect reports cumulative usage, but not always on the final chunk:
1266 # the OpenAI include_usage frame arrives after it (karr k298). The last chunk
1267 # that carries usage has the stream's totals.
1268 11 ▶sub aggregate_usage {
Subroutine aggregate_usage: called CC=5 SCAR=16.1
Pod documented
1269 11 my ( $self, $chunks ) = @_;
1270 11 ▶ return undef unless ref($chunks) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $chunks eq "ARRAY" 0 11 11
1271 11 my $usage;
1272 11 for my $c (@$chunks) {
1273 42 ▶ my $u = eval { $c->has_usage ? $c->usage : undef };
Branch: 1 branch
BranchTrueFalseTotal
$c->has_usage ? : 10 32 42
1274 42 ▶ $usage = $u if ref $u eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $u eq "HASH" 10 32 42
1275 }
1276 11 return $usage;
1277 }
1278  
1279  
1280  
1281  
1282 9484 ▶sub _process_stream_buffer {
Subroutine _process_stream_buffer: called CC=21 SCAR=30.7
1283 9484 my ($self, $buffer_ref, $format, $final, $state) = @_;
1284  
1285 9484 my @chunks;
1286  
1287 9484 ▶ if ($format eq 'sse') {
Branch: 2 branches
BranchTrueFalseTotal
if ($format eq 'sse') { } 9158 326 9484
elsif ($format eq 'ndjson') { } 326 0 326
1288 # On the final flush ($final, passed after the stream body ends) the last
1289 # event can arrive without its terminating blank line — the connection just
1290 # closed. Append one so the loop below consumes the remainder instead of
1291 # dropping it (its finish_reason / usage would be lost, and the sync
1292 # process_stream_data path — which splits the whole body at once — keeps it).
1293 # Event separators and line breaks are matched CRLF-tolerantly (\r?\n) to
1294 # match that sync path (split /\r?\n/).
1295 9158 ▶ $$buffer_ref .= "\n\n" if $final && $$buffer_ref ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $final and $$buffer_ref ne "" 18 9140 9158
Condition100%3/3
$final and $$buffer_ref ne ""
!ll&&!rl&&r
91261418
MC/DC100%2/2
$final and $$buffer_ref ne ""
$final $$buffer_ref ne ""
Truth table100%3/3
A and B
A= $finalB= $$buffer_ref ne ""
ABresult
0X0
100
111
1296 9158 ▶ while ($$buffer_ref =~ s/^(.*?)\r?\n\r?\n//s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^(.*?)\r?\n\r?\n//s) 2189 9148 11337
1297 2189 my $block = $1;
1298 2189 for my $line (split /\r?\n/, $block) {
1299 2313 ▶ next if $line eq '' || $line =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" or $line =~ /^:/ 0 2313 2313
Condition33%1/3
$line eq "" or $line =~ /^:/
l!l&&r!l&&!r
002313
MC/DC0%0/2
$line eq "" or $line =~ /^:/
$line eq "" $line =~ /^:/
Truth table33%1/3
A or B
A= $line eq ""B= $line =~ /^:/
ABresult
1X1
011
000
1300 2313 ▶ if ($line =~ /^data:\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^data:\s*(.*)$/) 2181 132 2313
1301 2181 my $json_data = $1;
1302 2181 ▶ next if $json_data eq '[DONE]' || $json_data eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $json_data eq "[DONE]" or $json_data eq "" 186 1995 2181
Condition66%2/3
$json_data eq "[DONE]" or $json_data eq ""
l!l&&r!l&&!r
18601995
MC/DC50%1/2
$json_data eq "[DONE]" or $json_data eq ""
$json_data eq "[DONE]" $json_data eq ""
Truth table66%2/3
A or B
A= $json_data eq "[DONE]"B= $json_data eq ""
ABresult
1X1
011
000
1303 1995 my $parsed = $self->json->decode($json_data);
1304 1989 my $chunk = $self->parse_stream_chunk($parsed, undef, $state);
1305 1985 ▶ push @chunks, $chunk if $chunk;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk 1904 81 1985
1306 }
1307 }
1308 }
1309 } elsif ($format eq 'ndjson') {
1310 326 ▶ $$buffer_ref .= "\n" if $final && $$buffer_ref ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $final and $$buffer_ref ne "" 2 324 326
Condition100%3/3
$final and $$buffer_ref ne ""
!ll&&!rl&&r
32222
MC/DC100%2/2
$final and $$buffer_ref ne ""
$final $$buffer_ref ne ""
Truth table100%3/3
A and B
A= $finalB= $$buffer_ref ne ""
ABresult
0X0
100
111
1311 326 ▶ while ($$buffer_ref =~ s/^(.*?)\r?\n//s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^(.*?)\r?\n//s) 10 325 335
1312 10 my $line = $1;
1313 10 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 10 10
1314 10 my $parsed = $self->json->decode($line);
1315 10 my $chunk = $self->parse_stream_chunk($parsed, undef, $state);
1316 9 ▶ push @chunks, $chunk if $chunk;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk 9 0 9
1317 }
1318 }
1319  
1320 # A final flush without a caller-owned state ends the stream on the
1321 # engine-wide fallback: close it here, so nothing left unfinished there can
1322 # reach the next stream. A caller that passes its own state (as
1323 # chat_stream_realtime_f does) closes it itself.
1324 $self->_finish_stream_state
1325 9473 ▶ if $final && !$state && $self->can('_finish_stream_state');
Branch: 1 branch
BranchTrueFalseTotal
if $final and not $state and $self->can("_finish_stream_state") 13 9460 9473
Condition100%6/6
$final and not $state and $self->can("_finish_stream_state")
!ll&&!rl&&r
94491113
$final and not $state
!ll&&!rl&&r
9440924
MC/DC100%3/3
$final and not $state and $self->can("_finish_stream_state")
$final not $state $self->can("_finish_stream_state")
Truth table100%4/4
A and not(B) and C
A= $finalB= not $stateC= $self->can("_finish_stream_state")
ABCresult
0XX0
10X0
1100
1111
1326  
1327 9473 return \@chunks;
1328 }
1329  
1330 194 with 'Langertha::Role::ThinkTag', 'Langertha::Role::Langfuse', 'Langertha::Role::AsyncHTTP';
1331  
1332  
1333 194 1;
1334  
1335 __END__
« blib/lib/Langertha/Engine/LMStudio.pm ↑ Summary blib/lib/Langertha/Role/ThinkTag.pm »