blib/lib/Langertha/Role/Chat.pm

filter: Statementstmt 98.2% 569 / 579 Branchbran 89.5% 344 / 384 Conditioncond 74.7% 260 / 348 MC/DCmcdc 56.8% 108 / 190 Subroutinesub 98.5% 67 / 68 Podpod 100% 16 / 16 totaltotal 86.0% 1364 / 1585 CC 329 SCAR 28.0
CC
329
Cov
89%
chat_f
38.7
_normalize_content_blocks
35.7
_prefetch_inline_images_f
31.6
CRAP 16.4
« blib/lib/Langertha/CallResult.pm ↑ Summary blib/lib/Langertha/Manifest/Builder.pm »
1 package Langertha::Role::Chat;
2 # ABSTRACT: Role for APIs with normal chat functionality
3 179 our $VERSION = '0.503';
4 179 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 179 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 179 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 179 ▶use Carp qw( carp croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 179 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 179 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 179 ▶use Scalar::Util qw( blessed refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 179 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 179 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 179 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 179 ▶use Langertha::ServerTool;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 179 ▶use Langertha::Role::Capabilities;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 179 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 469 ▶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 547 ▶sub _content_inline_images_only { 0 }
Subroutine _content_inline_images_only: called CC=1 SCAR=0.0
35  
36  
37 179 with 'Langertha::Role::Capabilities';
38  
39  
40 179 has chat_model => (
41 is => 'ro',
42 isa => 'Maybe[Str]',
43 lazy_build => 1,
44 );
45 2980 ▶sub _build_chat_model {
Subroutine _build_chat_model: called CC=3 SCAR=11.4
46 2980 my ( $self ) = @_;
47 2980 ▶ croak "".(ref $self)." can't handle models!" unless $self->does('Langertha::Role::Models');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->does("Langertha::Role::Models") 0 2980 2980
48 2980 ▶ return $self->default_chat_model if $self->can('default_chat_model');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("default_chat_model") 0 2980 2980
49 2980 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 219 ▶sub _merge_timing_field {
Subroutine _merge_timing_field: called CC=3 SCAR=11.4
60 219 my ( $existing, $key, $value ) = @_;
61 219 ▶ my $t = $existing ? { %$existing } : {};
Branch: 1 branch
BranchTrueFalseTotal
$existing ? : 0 219 219
62 219 ▶ $t->{$key} = $value unless exists $t->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $t->{$key} 219 0 219
63 219 return $t;
64 }
65  
66 239 ▶sub chat {
Subroutine chat: called CC=1 SCAR=0.0
Pod documented
67 239 my ( $self, @messages ) = @_;
68 239 return $self->chat_request($self->chat_messages(@messages));
69 }
70  
71  
72 931 ▶sub chat_messages {
Subroutine chat_messages: called CC=3 SCAR=11.0
Pod documented
73 931 my ( $self, @messages ) = @_;
74 931 $self->_warn_control_message_args(@messages);
75 931 my @out = $self->_system_messages;
76 931 for my $m (@messages) {
77 997 ▶ my $msg = ref $m ? $m : { role => 'user', content => $m };
Branch: 1 branch
BranchTrueFalseTotal
ref $m ? : 293 704 997
78 997 push @out, $self->_normalize_content_blocks($msg);
79 }
80 914 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 1059 ▶sub _system_messages {
Subroutine _system_messages: called CC=4 SCAR=13.9
88 1059 my ( $self, @override ) = @_;
89 1059 ▶ my $prompt = @override ? $override[0]
Branch: 2 branches
BranchTrueFalseTotal
@override ? : 17 1042 1059
$self->has_system_prompt ? : 56 986 1042
90 : $self->has_system_prompt ? $self->system_prompt : undef;
91 1059 ▶ return defined $prompt ? ( { role => 'system', content => $prompt } ) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $prompt ? : 73 986 1059
92 }
93  
94 1125 ▶sub _normalize_content_blocks {
Subroutine _normalize_content_blocks: called CC=34 SCAR=35.7
95 1125 my ( $self, $msg ) = @_;
96 1125 my $content = $msg->{content};
97 1125 ▶ return $msg unless ref $content eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content eq "ARRAY" 1019 106 1125
98  
99 106 my $needs_convert = 0;
100 106 for my $b (@$content) {
101 185 ▶ if ( blessed($b) && $b->does('Langertha::Content') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($b) and $b->does("Langertha::Content")) 72 113 185
Condition66%2/3
builtin::blessed($b) and $b->does("Langertha::Content")
!ll&&!rl&&r
113072
MC/DC50%1/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
102 72 $needs_convert = 1;
103 72 last;
104 }
105 }
106 106 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 106 ▶ return $msg unless $needs_convert || $fmt eq 'gemini' || $fmt eq 'ollama';
Branch: 1 branch
BranchTrueFalseTotal
unless $needs_convert or $fmt eq "gemini" or $fmt eq "ollama" 12 94 106
Condition100%6/6
$needs_convert or $fmt eq "gemini" or $fmt eq "ollama"
l!l&&r!l&&!r
89512
$needs_convert or $fmt eq "gemini"
l!l&&r!l&&!r
721717
MC/DC100%3/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
111  
112 94 my $method = "to_$fmt";
113 94 ▶ my $role = $msg->{role} // 'user';
Condition50%1/2
$msg->{"role"} // "user"
l!l
940
MC/DC0%0/1
$msg->{"role"} // "user"
$msg->{"role"}
Truth table50%1/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 94 ▶ my @opt = ( $self->_content_inline_images_only
Branch: 1 branch
BranchTrueFalseTotal
$self->_content_inline_images_only && ($fmt eq 'openai' || $fmt eq 'responses') ? : 20 74 94
Condition83%5/6
$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
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"
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
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 94 ▶ if ( $fmt eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "ollama") 14 80 94
121 14 my ( @text, @images );
122 14 for my $part (@$content) {
123 26 ▶ if ( blessed($part) && $part->does('Langertha::Content') ) {
Branch: 4 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
Condition66%2/3
builtin::blessed($part) and $part->does("Langertha::Content")
!ll&&!rl&&r
1808
MC/DC50%1/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
124 8 push @images, $self->_content_block( $part, $method );
125 }
126 elsif ( !ref $part ) {
127 9 push @text, $part;
128 }
129 ▶ elsif ( ref $part eq 'HASH' && ( $part->{type} // '' ) eq 'text' && defined $part->{text} ) {
Condition62%5/8
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
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
130 6 push @text, $part->{text};
131 }
132 elsif ( my $img = $self->_image_url_part_image($part) ) {
133 1 push @images, $self->_content_block( $img, $method );
134 }
135 else {
136 2 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 9 ▶ ? ( images => [ @{ $msg->{images} // [] }, @images ] ) : () };
Branch: 1 branch
BranchTrueFalseTotal
@images || $msg->{'images'} ? : 6 3 9
Condition60%3/5
@images or $msg->{"images"}
l!l&&r!l&&!r
603
$msg->{"images"} // []
l!l
06
MC/DC50%1/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
144 }
145  
146 80 ▶ my $text_type = $fmt ne 'responses' ? 'text'
Branch: 2 branches
BranchTrueFalseTotal
$fmt ne 'responses' ? : 73 7 80
$role eq 'assistant' ? : 2 5 7
147 : $role eq 'assistant' ? 'output_text'
148 : 'input_text';
149  
150 my @blocks = map {
151 80 ▶ if ( blessed($_) && $_->does('Langertha::Content') ) {
Branch: 3 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
Condition66%2/3
builtin::blessed($_) and $_->does("Langertha::Content")
!ll&&!rl&&r
84069
MC/DC50%1/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
152 69 $self->_content_block( $_, $method, @opt );
153 }
154 elsif ( !ref $_ ) {
155 57 ▶ $fmt eq 'gemini'
Branch: 1 branch
BranchTrueFalseTotal
$fmt eq 'gemini' ? : 19 38 57
156 ? { text => $_ }
157 : { type => $text_type, text => $_ };
158 }
159 elsif ( $fmt eq 'gemini' ) {
160 27 $self->_gemini_part( $_, $method );
161 }
162 else {
163 0 $_;
164 }
165 } @$content;
166  
167 68 ▶ if ( $fmt eq 'gemini' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "gemini") 22 46 68
168 22 ▶ return { role => ( $role eq 'assistant' ? 'model' : $role ), parts => \@blocks };
Branch: 1 branch
BranchTrueFalseTotal
$role eq 'assistant' ? : 2 20 22
169 }
170 46 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=18.0
179 27 my ( $self, $part, $method ) = @_;
180 27 ▶ return $part unless ref $part eq 'HASH' && defined $part->{type};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $part eq "HASH" and defined $part->{"type"} 12 15 27
Condition66%2/3
ref $part eq "HASH" and defined $part->{"type"}
!ll&&!rl&&r
01215
MC/DC50%1/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
181 15 my $type = $part->{type};
182 15 ▶ return { text => $part->{text} } if $type eq 'text' && defined $part->{text};
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "text" and defined $part->{"text"} 5 10 15
Condition66%2/3
$type eq "text" and defined $part->{"text"}
!ll&&!rl&&r
1005
MC/DC50%1/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
183 10 ▶ if ( my $img = $self->_image_url_part_image($part) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $img = $self->_image_url_part_image($part)) 7 2 9
184 7 return $self->_content_block( $img, $method );
185 }
186 2 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=21.0
195 13 my ( $self, $part ) = @_;
196 13 ▶ return undef unless ref $part eq 'HASH' && ( $part->{type} // '' ) eq 'image_url';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $part eq "HASH" and ($part->{"type"} // "") eq "image_url" 3 10 13
Condition60%3/5
ref $part eq "HASH" and ($part->{"type"} // "") eq "image_url"
!ll&&!rl&&r
0310
$part->{"type"} // ""
l!l
130
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
197 10 ▶ 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' ? : 7 3 10
198 10 ▶ return undef unless defined $url && length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 1 9 10
Condition66%2/3
defined $url and length $url
!ll&&!rl&&r
109
MC/DC50%1/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
199 9 require Langertha::Content::Image;
200 9 ▶ return $url =~ m{\Adata:([^;,]+);base64,(.*)\z}s
Branch: 1 branch
BranchTrueFalseTotal
$url =~ /\Adata:([^;,]+);base64,(.*)\z/s ? : 7 2 9
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=23.0
209 85 my ( $self, $block, $method, @opt ) = @_;
210 85 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 85 ▶ && ( $opt{inline} || $method =~ /\Ato_(?:gemini|ollama|lmstudio)\z/ );
Condition100%12/12
$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
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/
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
216 85 my $out;
217 85 ▶ return $out if eval {
Branch: 1 branch
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
218 85 ▶ $block->ensure_base64( timeout => $self->inline_image_fetch_timeout,
Branch: 1 branch
BranchTrueFalseTotal
if $prefetch 21 64 85
219 $self->_inline_image_fetch_limits ) if $prefetch;
220 76 $out = $block->$method(@opt);
221 73 1;
222 };
223 12 my $err = $@;
224 12 ▶ croak $self->_inline_image_error($err)
Branch: 1 branch
BranchTrueFalseTotal
if $block->can("has_url") and $block->has_url and not $block->has_base64 9 3 12
Condition66%4/6
$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
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
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
225 if $block->can('has_url') && $block->has_url && !$block->has_base64;
226 3 die $err;
227 }
228  
229 19 ▶sub _inline_image_error {
Subroutine _inline_image_error: called CC=1 SCAR=0.0
230 19 my ( $self, $err ) = @_;
231 19 $err =~ s/ at \S+ line \d+.*//s;
232 19 $err =~ s/\s+\z//;
233 19 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 179 has inline_image_fetch_timeout => (
239 isa => 'Int',
240 is => 'ro',
241 default => 30,
242 );
243  
244  
245 179 has inline_image_max_bytes => (
246 isa => 'Int',
247 is => 'ro',
248 default => 20_971_520,
249 );
250  
251  
252 179 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=0.0
260 43 my ($self) = @_;
261 43 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 578 ▶async sub _prefetch_inline_images_f {
Subroutine _prefetch_inline_images_f: called CC=29 SCAR=34.5
277 578 my ( $self, @messages ) = @_;
278 578 my $fmt = $self->content_format;
279 578 ▶ 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" 480 98 578
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
7919480
$fmt eq "gemini" or $fmt eq "ollama" or $fmt eq "lmstudio"
l!l&&r!l&&!r
781499
$fmt eq "gemini" or $fmt eq "ollama"
l!l&&r!l&&!r
5721500
$self->_content_inline_images_only and $fmt eq "openai" || $fmt eq "responses"
!ll&&!rl&&r
480019
$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 98 my ( @out, @fetch, %seen, %by_url );
283 98 for my $msg (@messages) {
284 98 ▶ 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") 76 22 98
Condition100%3/3
ref $msg eq "HASH" and ref $msg->{"content"} eq "ARRAY"
!ll&&!rl&&r
571922
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 76 push @out, $msg;
286 76 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 {
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 97 ▶ return @messages unless @fetch;
Branch: 1 branch
BranchTrueFalseTotal
unless @fetch 78 19 97
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 179 }
329  
330  
331 8 ▶sub simple_chat {
Subroutine simple_chat: called CC=6 SCAR=19.9
Pod documented
332 8 my ( $self, @messages ) = @_;
333 8 ▶ $log->debugf("[%s] simple_chat with %d message(s), model=%s",
Condition50%1/2
$self->chat_model // "default"
l!l
80
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 8 my $t0 = [gettimeofday];
336 8 my $request = $self->chat(@messages);
337 8 my $response = $self->user_agent->request($request);
338 8 my $elapsed = tv_interval($t0);
339 8 my $result = $request->response_call->($response);
340 2 ▶ if (ref $result && $result->isa('Langertha::Response')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result and $result->isa("Langertha::Response")) 2 0 2
Condition33%1/3
ref $result and $result->isa("Langertha::Response")
!ll&&!rl&&r
002
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 2 $result = $result->clone_with(
342 timing => _merge_timing_field($result->timing, total_seconds => $elapsed),
343 );
344 2 ▶ 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 2 2
Condition33%1/3
$self->can("has_rate_limit") and $self->has_rate_limit
!ll&&!rl&&r
020
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 2 return $result;
349 }
350  
351  
352 28 ▶sub chat_stream {
Subroutine chat_stream: called CC=2 SCAR=7.1
Pod documented
353 28 my ( $self, @messages ) = @_;
354 28 ▶ croak "".(ref $self)." does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_stream_request") 0 28 28
355 unless $self->can('chat_stream_request');
356 28 return $self->chat_stream_request($self->chat_messages(@messages));
357 }
358  
359  
360 4 ▶sub simple_chat_stream {
Subroutine simple_chat_stream: called CC=4 SCAR=14.1
Pod documented
361 4 my ( $self, $callback, @messages ) = @_;
362 4 ▶ croak "simple_chat_stream requires a callback as first argument"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 4 4
363 unless ref $callback eq 'CODE';
364 4 $log->debugf("[%s] simple_chat_stream (%s format)", ref $self, $self->stream_format);
365 4 my $request = $self->chat_stream(@messages);
366 4 my ( $chunks, $timing ) = $self->execute_streaming_request($request, $callback);
367 $log->debugf("[%s] Stream completed: %d chunks (%.3fs)",
368 2 ▶ ref $self, scalar @$chunks, $timing->{total_seconds} // 0);
Condition50%1/2
$timing->{"total_seconds"} // 0
l!l
20
MC/DC0%0/1
$timing->{"total_seconds"} // 0
$timing->{"total_seconds"}
Truth table50%1/2
A
A= $timing->{"total_seconds"}
Aresult
11
00
369 2 my $content = join('', map { $_->content } @$chunks);
370 2 my $thinking = $self->aggregate_thinking($chunks);
371 2 ▶ return wantarray ? ( $content, $thinking ) : $content;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 0 2
372 }
373  
374  
375 0 ▶sub simple_chat_stream_iterator {
Subroutine simple_chat_stream_iterator: not called CC=2 SCAR=17.9
Pod documented
376 0 my ( $self, @messages ) = @_;
377 0 require Langertha::Stream;
378 0 my $request = $self->chat_stream(@messages);
379 0 my ( $chunks, $timing ) = $self->execute_streaming_request($request);
380 $log->debugf("[%s] Stream completed: %d chunks (%.3fs)",
381 0 ▶ ref $self, scalar @$chunks, $timing->{total_seconds} // 0);
Condition0%0/2
$timing->{"total_seconds"} // 0
l!l
00
MC/DC0%0/1
$timing->{"total_seconds"} // 0
$timing->{"total_seconds"}
Truth table0%0/2
A
A= $timing->{"total_seconds"}
Aresult
11
00
382 0 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 15 ▶async sub simple_chat_f {
Subroutine simple_chat_f: called CC=1 SCAR=0.0
Pod documented
391 15 my ( $self, @messages ) = @_;
392 15 $log->debugf("[%s] simple_chat_f with %d message(s)", ref $self, scalar @messages);
393 15 return await $self->chat_f( messages => \@messages );
394 179 }
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 179 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_budget
410 thinking_display
411 prompt_cache
412 prompt_cache_ttl
413 prompt_cache_key
414 prefix_cache_salt
415 cache_prompt
416 n_cache_reuse
417 id_slot
418 priority
419 return_cached_tokens_details
420 extra_key
421 );
422  
423 466 ▶sub _extract_controls {
Subroutine _extract_controls: called CC=3 SCAR=11.0
424 466 my ( $self, $opts ) = @_;
425 466 my %controls;
426 466 for my $key ( keys %CANONICAL_CONTROLS ) {
427 8388 ▶ $controls{$key} = delete $opts->{$key} if exists $opts->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{$key} 86 8302 8388
428 }
429 466 return \%controls;
430 }
431  
432  
433 # karr #122: simple_chat / simple_chat_f / chat funnel their positional
434 # @messages through chat_messages, which turns every non-ref scalar into a
435 # { role => 'user' } turn. A caller who mistakes those methods for chat_f and
436 # appends a control as a kwarg tail -- simple_chat($prompt, reasoning_effort =>
437 # 'high') -- silently sends the control name and its value as extra user
438 # messages, with no error and no effect (the project hit this twice in its own
439 # docs). This is a diagnostic only: warn once (never die) when a plain-scalar
440 # message exactly matches a canonical control name; behaviour is otherwise
441 # unchanged (the strings still become messages as before). A control name has
442 # no legitimate use as a whole user turn, so this has no false positives in
443 # practice. The broader unknown-constructor-arg finding (karr #101) is out of
444 # scope here.
445 931 ▶sub _warn_control_message_args {
Subroutine _warn_control_message_args: called CC=4 SCAR=13.9
446 931 my ( $self, @messages ) = @_;
447 931 my %seen;
448 my @hits =
449 15 grep { !$seen{$_}++ }
450 931 ▶ grep { defined $_ && !ref $_ && $CANONICAL_CONTROLS{$_} } @messages;
Condition83%5/6
defined $_ && !ref($_) && $CANONICAL_CONTROLS{$_}
!ll&&!rl&&r
29368915
defined $_ and not ref $_
!ll&&!rl&&r
0293704
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
451 931 ▶ return unless @hits;
Branch: 1 branch
BranchTrueFalseTotal
unless @hits 918 13 931
452 carp sprintf(
453 "%s: message argument(s) %s match a chat_f control name and are being "
454 . "sent as plain user message text. Per-request controls such as "
455 . "reasoning_effort, temperature and response_format are named "
456 . "arguments to chat_f (or engine constructor attributes), not "
457 . "simple_chat/chat message arguments.",
458 ref $self,
459 13 join( ', ', map { "'$_'" } @hits ),
460 );
461 13 return;
462 }
463  
464 # Drop warnings (karr k247, ADR 0025): a request builder that leaves a value
465 # off the wire says so, but the carp fires in a private helper several
466 # Langertha frames below the caller's chat_f / chat / simple_chat_f call, and
467 # Carp skips only one frame. For the duration of this one warning every
468 # Langertha, Moose, Class::MOP, Eval::Closure and Future package on the stack
469 # is marked Carp-internal, so the message names the first frame outside that
470 # plumbing: the user's own call site (the rule of Role::AsyncHTTP's
471 # _caller_location). croak keeps Carp's normal location. Under an event loop
472 # the stack may hold no user frame; Carp then reports what it finds, it never
473 # dies.
474 #
475 # $once is set when the dropped value comes from an engine attribute: that
476 # value is the same on every request (and every chat_with_tools_f iteration),
477 # so it warns once per engine instance per key. A per-request value warns
478 # every time. The seen-set lives on the instance, never in a global.
479 has _warned_drops => (
480 is => 'ro',
481 isa => 'HashRef',
482 init_arg => undef,
483 lazy => 1,
484 120 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
485 179 );
486  
487 179 my $LANGERTHA_INTERNAL = qr/\A(?:Langertha|Moose|Class::MOP|Eval::Closure|Future)(?:::|\z)/;
488  
489 275 ▶sub _langertha_carp {
Subroutine _langertha_carp: called CC=5 SCAR=16.1
490 275 my ( $self, $message, $once ) = @_;
491 275 ▶ return if defined $once && $self->_warned_drops->{$once}++;
Branch: 1 branch
BranchTrueFalseTotal
if defined $once and $self->_warned_drops->{$once}++ 18 257 275
Condition100%3/3
defined $once and $self->_warned_drops->{$once}++
!ll&&!rl&&r
13712018
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
492 257 my %internal;
493 257 ▶ for ( my $level = 0; my ($package) = caller $level; $level++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($package) = caller $level) 1754 257 2011
494 1754 ▶ $internal{$package} = 1 if $package =~ $LANGERTHA_INTERNAL;
Branch: 1 branch
BranchTrueFalseTotal
if $package =~ /$LANGERTHA_INTERNAL/ 666 1088 1754
495 }
496 257 local @Carp::Internal{ keys %internal } = (1) x keys %internal;
497 257 carp $message;
498 257 return;
499 }
500  
501 # karr #148 / #184: a couple of OpenAI-compatible serving stacks reject a
502 # request that combines tools and a structured-output response_format with an
503 # opaque HTTP 400 and no body. No boolean capability flag can express a mutual
504 # exclusion between two capabilities in one request (ADR 0021). The constraint
505 # is a property of the serving STACK, not of the model: Groq and Cerebras
506 # enforce it across every model they serve, while AKI serves gpt-oss-120b with
507 # tools + a json_schema response_format at HTTP 200 (live 2026-09-19) — so each
508 # affected engine declares its own all-models rule and there is no shared base
509 # rule to over-fire on the unaffected stacks.
510 #
511 # The seam mirrors ADR 0019's model_capability_corrections: an ORDERED list of
512 # ( $matcher => $rule ) pairs keyed on chat_model. $matcher is an exact
513 # model-id string (matched with eq) or a qr// regex (matched against
514 # chat_model). $rule is a CODEREF — the concrete seam, deliberately NOT a
515 # declarative constraint DSL (karr #148) — invoked as $self->$rule(%request)
516 # with has_tools / tool_choice_forced / response_format / streaming; it croaks
517 # when the request hits the combination the stack rejects. The default is an
518 # empty list, so engines that constrain nothing pay nothing; an engine whose
519 # serving stack rejects the combination declares an all-models rule by
520 # overriding model_capability_exclusions (Groq, Cerebras, SGLang).
521 435 ▶sub model_capability_exclusions { return () }
Subroutine model_capability_exclusions: called CC=1 SCAR=0.0
Pod documented
522  
523 # Consulted by chat_f (streaming => 0) and chat_stream_realtime_f
524 # (streaming => 1) after the effective post-rewrite request is built (ADR 0021),
525 # so an ADR 0005 rewrite that already collapsed the body to a single path
526 # pre-empts it. Walks the per-model exclusion table for the selected chat_model
527 # and lets each matching rule convert a known provider 400 into a clear local
528 # croak. A no-op when the table is empty or no matcher hits.
529 493 ▶sub _check_capability_exclusions {
Subroutine _check_capability_exclusions: called CC=2 SCAR=6.9
530 493 my ( $self, %request ) = @_;
531 493 $self->$_(%request) for $self->_matched_capability_exclusions;
532 465 return;
533 }
534  
535 # The rules of model_capability_exclusions whose matcher hits chat_model, in
536 # table order. Shared by _check_capability_exclusions and the per-request model
537 # override warning (karr k352), which compares the matched set for two models.
538 511 ▶sub _matched_capability_exclusions {
Subroutine _matched_capability_exclusions: called CC=7 SCAR=19.5
539 511 my ( $self ) = @_;
540 511 my @rules = $self->model_capability_exclusions;
541 511 ▶ return unless @rules;
Branch: 1 branch
BranchTrueFalseTotal
unless @rules 435 76 511
542 # chat_model is the model that actually carries tools / response_format on the
543 # wire; guard for the rare consumer that has no model surface at all.
544 # An empty or undef chat_model is matched as '', the same as
545 # model_capability_corrections (karr k223), so an all-models qr// rule
546 # (Groq, Cerebras) still holds for model => ''.
547 76 ▶ return unless $self->can('chat_model');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_model") 0 76 76
548 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
549 76 my @matched;
550 76 ▶ while ( @rules >= 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rules >= 2) 76 76 152
551 76 my ( $matcher, $rule ) = splice @rules, 0, 2;
552 76 ▶ my $hit = ref $matcher eq 'Regexp' ? ( $model =~ $matcher )
Branch: 1 branch
BranchTrueFalseTotal
ref $matcher eq 'Regexp' ? : 72 4 76
553 : ( $model eq $matcher );
554 76 ▶ push @matched, $rule if $hit;
Branch: 1 branch
BranchTrueFalseTotal
if $hit 75 1 76
555 }
556 76 return @matched;
557 }
558  
559  
560 # True when the request asks for tools — either a tools array or a
561 # forced named tool_choice. Used to feed the capability-exclusion hook.
562 493 ▶sub _chat_tools_requested {
Subroutine _chat_tools_requested: called CC=6 SCAR=18.2
563 493 my ( $self, $opts ) = @_;
564 # An empty tools => [] sends zero tools on the wire, so it must NOT trip the
565 # capability-exclusion guard (which would croak on Cerebras/Groq for a request
566 # that combines tools with a structured-output response_format). Only a
567 # non-empty tools array counts as "tools requested" here.
568 493 ▶ return 1 if ref $opts->{tools} eq 'ARRAY' && @{ $opts->{tools} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};} 277 216 493
Condition100%3/3
ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};}
!ll&&!rl&&r
2133277
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
569 216 ▶ return 0 unless exists $opts->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"tool_choice"} 214 2 216
570 2 my $tc = Langertha::ToolChoice->from_hash( $opts->{tool_choice} );
571 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
572 }
573  
574 # True when the request forces a tool call: tool_choice any (wire 'required')
575 # or a named tool (karr k245). Read from the caller's tool_choice before any
576 # tool_choice gate runs, so an exclusion rule sees what was asked; after the
577 # ADR 0005 rewrite (which deletes tool_choice) it is 0. Feeds the
578 # capability-exclusion hook as tool_choice_forced.
579 493 ▶sub _chat_tool_choice_forced {
Subroutine _chat_tool_choice_forced: called CC=5 SCAR=16.1
580 493 my ( $self, $opts ) = @_;
581 493 ▶ return 0 unless defined $opts->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $opts->{"tool_choice"} 458 35 493
582 35 my $tc = Langertha::ToolChoice->from_hash( $opts->{tool_choice} );
583 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
584 }
585  
586 # The response_format the request builders will put on the wire (karr k249):
587 # the per-request value when the caller passed the key, else the engine
588 # attribute (Role::ResponseFormat) -- the same precedence as
589 # OpenAICompatible's chat_request / chat_stream_request, AnthropicCompatible's
590 # _take_response_format and ResponsesCompatible. Feeds the capability-exclusion
591 # hook, so a rule also fires for an engine-level response_format. Always a
592 # scalar (undef when neither is set): it is called in a hash-list position.
593 561 ▶sub _chat_effective_response_format {
Subroutine _chat_effective_response_format: called CC=4 SCAR=13.9
594 561 my ( $self, $opts ) = @_;
595 my $rf = exists $opts->{response_format} ? $opts->{response_format}
596 561 ▶ : ( $self->can('has_response_format') && $self->has_response_format ) ? $self->response_format
Branch: 2 branches
BranchTrueFalseTotal
exists $opts->{'response_format'} ? : 87 474 561
$self->can('has_response_format') && $self->has_response_format ? : 12 462 474
Condition100%3/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
445812
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
597 : undef;
598 561 return $rf;
599 }
600  
601 # The ADR 0005 forced-tool rewrite sets a per-request response_format, which
602 # replaces any other one (karr k250). A structured response_format the caller
603 # passed in the same request is a conflicting intent: croak. One that only
604 # comes from the engine attribute yields to the request's forced tool: carp.
605 # A `text` response_format asks for no structure, so it is no conflict.
606 31 ▶sub _chat_rewrite_replaces_response_format {
Subroutine _chat_rewrite_replaces_response_format: called CC=7 SCAR=19.9
607 31 my ( $self, $opts, $name ) = @_;
608 31 my $rf = $self->_chat_effective_response_format($opts);
609 31 ▶ return unless defined $rf;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rf 12 19 31
610 19 ▶ my $type = ref $rf eq 'HASH' ? $rf->{type} : $rf;
Branch: 1 branch
BranchTrueFalseTotal
ref $rf eq 'HASH' ? : 19 0 19
611 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
612 croak "".(ref $self).": chat_f got both a forced tool_choice '$name' and a "
613 . "response_format; this engine carries a forced tool as a response_format "
614 . "(no native named tool_choice), so the two conflict -- pick one"
615 13 ▶ if exists $opts->{response_format};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"response_format"} 9 4 13
616 4 $self->_langertha_carp( "".(ref $self).": the forced tool_choice '$name' is sent as a "
617 . "response_format (no native named tool_choice); the engine's "
618 . "response_format is replaced for this request",
619 "response_format replaced by tool_choice $name" );
620 4 return;
621 }
622  
623 # karr k352 (split from k238): a `model` passed to chat_f or
624 # chat_stream_realtime_f is no canonical control; it rides %extra into the
625 # request builder and replaces the body's model field. Every model-scoped wire
626 # decision still reads chat_model: the layer-3 capability corrections and the
627 # learned facts (ADR 0019 / 0032, and a model-aware layer 2 such as Gemini's),
628 # the exclusion rules (ADR 0024), the reasoning profile (ADR 0023), the
629 # reasoning temperature gate (ADR 0025), the per-model tool_wire_format (ADR
630 # 0033) and the per-model body shape (completion-length key, response-size
631 # default, native structured output). Langertha does not re-scope a request to
632 # its override (that is a second engine); it warns when the override would get
633 # a different decision, naming which.
634 #
635 # Quiet unless something flips: an override equal to chat_model costs nothing,
636 # and only the decisions THIS request consults are compared. A capability flag
637 # named here is compared only when one of its request features is in play;
638 # image_input never (it reports what the model sees and gates nothing, ADR
639 # 0019 k266 Update); any other flag always, so a new model-scoped flag errs
640 # toward a warning, not toward silence.
641 179 my %CAP_CONSULTED_BY = (
642 tools_native => ['tools'],
643 tools_hermes => ['tools'],
644 server_tools => ['tools'],
645 tool_choice_auto => ['tool_choice'],
646 tool_choice_any => ['tool_choice'],
647 tool_choice_none => ['tool_choice'],
648 tool_choice_named => ['tool_choice'],
649 response_format_json_object => ['response_format'],
650 # the ADR 0005 forced-tool rewrite consults it too
651 response_format_json_schema => [ 'response_format', 'tool_choice' ],
652 temperature => ['temperature'],
653 reasoning_effort => ['reasoning'],
654 thinking_budget => ['reasoning'],
655 parallel_tool_use => ['parallel_tool_use'],
656 streaming => ['streaming'],
657 # Gemini's per-generation flag: consulted only with a bound cachedContent
658 cached_content => ['cached_content'],
659 image_input => [],
660 );
661  
662 # The request features that decide which model-scoped decisions a request
663 # consults: from the per-request options, else the engine attribute.
664 37 ▶sub _chat_request_features {
Subroutine _chat_request_features: called CC=14 SCAR=26.5
665 37 my ( $self, $opts, $streaming ) = @_;
666 216 ▶ my $attr_set = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
667 216 my $predicate = 'has_' . $_[0];
668 216 ▶ return $self->can($predicate) && $self->$predicate;
Condition100%3/3
$self->can($predicate) && $self->$predicate
!ll&&!rl&&r
341793
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
669 37 };
670 37 my %features;
671 37 ▶ $features{tools} = 1 if ref $opts->{tools} eq 'ARRAY' && @{ $opts->{tools} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};} 9 28 37
Condition66%2/3
ref $opts->{"tools"} eq "ARRAY" and @{$opts->{"tools"};}
!ll&&!rl&&r
2809
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
672 37 ▶ $features{tool_choice} = 1 if defined $opts->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"tool_choice"} 1 36 37
673 37 ▶ $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 37 37
674 37 ▶ $features{temperature} = 1 if exists $opts->{temperature} || $attr_set->('temperature');
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"temperature"} or &$attr_set("temperature") 4 33 37
Condition100%3/3
exists $opts->{"temperature"} or &$attr_set("temperature")
l!l&&r!l&&!r
3133
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
675 $features{reasoning} = 1
676 37 ▶ if grep { exists $opts->{$_} || $attr_set->($_) } qw( reasoning_effort thinking_budget thinking_display );
Branch: 1 branch
BranchTrueFalseTotal
if grep {exists $opts->{$_} or &$attr_set($_);} "reasoning_effort", "thinking_budget", "thinking_display" 4 33 37
Condition100%3/3
exists $opts->{$_} || &$attr_set($_)
l!l&&r!l&&!r
31107
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
677 37 ▶ $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 37 37
Condition33%1/3
exists $opts->{"parallel_tool_use"} or &$attr_set("parallel_tool_use")
l!l&&r!l&&!r
0037
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
678 37 ▶ $features{max_tokens} = 1 if exists $opts->{max_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"max_tokens"} 5 32 37
679 37 ▶ $features{streaming} = 1 if $streaming;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming 2 35 37
680 37 ▶ $features{cached_content} = 1 if $attr_set->('cached_content');
Branch: 1 branch
BranchTrueFalseTotal
if &$attr_set("cached_content") 1 36 37
681 37 return \%features;
682 }
683  
684 # The model-scoped decisions this engine takes for a request with $features,
685 # as label => value. Read-only: no warning, no request. An engine with a
686 # model-scoped decision of its own adds it with an `around` (NousResearch's
687 # reasoning prompt).
688 74 ▶sub _model_scoped_wire_decisions {
Subroutine _model_scoped_wire_decisions: called CC=23 SCAR=31.9
689 74 my ( $self, $features, $opts ) = @_;
690 74 my %decision;
691 74 my $caps = $self->engine_capabilities;
692 74 for my $cap ( grep { $caps->{$_} } keys %$caps ) {
693 1123 my $by = $CAP_CONSULTED_BY{$cap};
694 1123 ▶ next if $by && !grep { $features->{$_} } @$by;
Branch: 1 branch
BranchTrueFalseTotal
if $by and not grep({$features->{$_};} @$by) 724 399 1123
Condition100%3/3
$by and not grep({$features->{$_};} @$by)
!ll&&!rl&&r
35544724
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
695 399 $decision{"supports('$cap')"} = 1;
696 }
697 74 ▶ my $tools = $features->{tools} || $features->{tool_choice};
Condition66%2/3
$features->{'tools'} || $features->{'tool_choice'}
l!l&&r!l&&!r
18056
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
698 74 ▶ $decision{tool_wire_format} = $self->tool_wire_format
Branch: 1 branch
BranchTrueFalseTotal
if $tools and $self->can("tool_wire_format") 18 56 74
Condition66%2/3
$tools and $self->can("tool_wire_format")
!ll&&!rl&&r
56018
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
699 if $tools && $self->can('tool_wire_format');
700 1 $decision{model_capability_exclusions} = join ',', map { refaddr $_ } $self->_matched_capability_exclusions
701 74 ▶ if $tools || $features->{response_format};
Branch: 1 branch
BranchTrueFalseTotal
if $tools or $features->{"response_format"} 18 56 74
Condition66%2/3
$tools or $features->{"response_format"}
l!l&&r!l&&!r
18056
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
702 74 ▶ if ( $features->{reasoning} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($features->{"reasoning"}) 8 66 74
703 8 require Langertha::Reasoning::Profile;
704 8 $decision{'reasoning profile'} =
705 refaddr( Langertha::Reasoning::Profile->for_model( $self->_capability_model ) );
706 }
707 $decision{'temperature gate'} = $self->_temperature_rejected_by_reasoning($opts) ? 1 : 0
708 74 ▶ if $features->{temperature} && $self->can('_temperature_rejected_by_reasoning');
Branch: 2 branches
BranchTrueFalseTotal
if $features->{"temperature"} and $self->can("_temperature_rejected_by_reasoning") 2 72 74
$self->_temperature_rejected_by_reasoning($opts) ? : 1 1 2
Condition100%3/3
$features->{"temperature"} and $self->can("_temperature_rejected_by_reasoning")
!ll&&!rl&&r
6662
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
709 74 ▶ my $size = $self->can('get_response_size') ? $self->get_response_size : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->can('get_response_size') ? : 74 0 74
710 $decision{'response_size default'} = $size // ''
711 74 ▶ if !$features->{max_tokens} && $self->can('get_response_size');
Branch: 1 branch
BranchTrueFalseTotal
if not $features->{"max_tokens"} and $self->can("get_response_size") 64 10 74
Condition80%4/5
not $features->{"max_tokens"} and $self->can("get_response_size")
!ll&&!rl&&r
10064
$size // ""
l!l
2242
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
712 $decision{'completion-length key'} = $self->_max_tokens_key
713 74 ▶ 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 58 74
Condition100%6/6
$features->{"max_tokens"} || $size and $self->can("_max_tokens_key")
!ll&&!rl&&r
421616
$features->{"max_tokens"} or $size
l!l&&r!l&&!r
102242
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
714 $decision{'native structured output'} = $self->_native_structured_output_for_model ? 1 : 0
715 73 ▶ 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 73 73
$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
7300
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
716 73 return %decision;
717 }
718  
719 # Warns when the request's model override flips a decision (see above). The
720 # decisions for the override are read off an in-memory clone whose chat_model
721 # is the override, as Manifest::Builder probes a model (a builder-made
722 # tool_wire_format is resolved again, a constructor one kept, karr k251). A
723 # per-request value, so it warns on every request (karr k247). Diagnostic
724 # only: if the decisions cannot be computed, the request goes on unwarned and
725 # its own path reports the error.
726 518 ▶sub _warn_model_override {
Subroutine _warn_model_override: called CC=12 SCAR=24.9
727 518 my ( $self, $method, $opts, $streaming ) = @_;
728 518 my $override = $opts->{model};
729 518 ▶ return unless defined $override && !ref $override && length $override;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $override and not ref $override and length $override 478 40 518
Condition83%5/6
defined $override and not ref $override and length $override
!ll&&!rl&&r
477140
defined $override and not ref $override
!ll&&!rl&&r
477041
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
730 40 ▶ return unless $self->can('chat_model');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_model") 0 40 40
731 40 ▶ my $configured = $self->_capability_model // '';
Condition50%1/2
$self->_capability_model // ""
l!l
400
MC/DC0%0/1
$self->_capability_model // ""
$self->_capability_model
Truth table50%1/2
A
A= $self->_capability_model
Aresult
11
00
732 40 ▶ return if $override eq $configured;
Branch: 1 branch
BranchTrueFalseTotal
if $override eq $configured 3 37 40
733 37 my @flipped;
734 {
735 37 local $@;
736 37 ▶ 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 36 1 37
737 37 my $features = $self->_chat_request_features( $opts, $streaming );
738 37 my $probe = $self->meta->clone_object( $self, chat_model => $override );
739 37 ▶ $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") 37 0 37
740 37 my %mine = $self->_model_scoped_wire_decisions( $features, $opts );
741 37 my %theirs = $probe->_model_scoped_wire_decisions( $features, $opts );
742 36 my %labels = ( %mine, %theirs );
743 36 ▶ @flipped = grep { ( $mine{$_} // '' ) ne ( $theirs{$_} // '' ) } sort keys %labels;
Condition100%4/4
$mine{$_} // ""
l!l
2635
$theirs{$_} // ""
l!l
25810
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
744 36 1;
745 } or return;
746 }
747 36 ▶ return unless @flipped;
Branch: 1 branch
BranchTrueFalseTotal
unless @flipped 13 23 36
748 23 $self->_langertha_carp( "".(ref $self).": $method got a per-request model '$override' "
749 . "that differs from chat_model '$configured'; model-scoped wire decisions follow "
750 . "chat_model, and these differ for '$override': " . join( ', ', @flipped )
751 . " -- use an engine whose chat_model is '$override'" );
752 23 return;
753 }
754  
755 # The model a request goes to on a wire that names it in the URL (Gemini's
756 # models/{model}:generateContent, AKI native's /api/call/{model}): the
757 # per-request override when there is one (the same test as
758 # _warn_model_override), else chat_model. The `model` key is taken out of
759 # %extra either way: there it would only ride the body as an unknown field
760 # while the URL still named chat_model (karr k357).
761 300 ▶sub _url_model {
Subroutine _url_model: called CC=4 SCAR=13.9
762 300 my ( $self, $extra ) = @_;
763 300 my $override = delete $extra->{model};
764 300 ▶ return $override if defined $override && !ref $override && length $override;
Branch: 1 branch
BranchTrueFalseTotal
if defined $override and not ref $override and length $override 7 293 300
Condition83%5/6
defined $override and not ref $override and length $override
!ll&&!rl&&r
29127
defined $override and not ref $override
!ll&&!rl&&r
29109
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
765 293 return $self->chat_model;
766 }
767  
768 298 ▶async sub chat_f {
Subroutine chat_f: called CC=36 SCAR=36.6
Pod documented
769 298 my ( $self, %opts ) = @_;
770  
771 298 ▶ my $messages = delete $opts{messages} // [];
Condition100%2/2
delete $opts{"messages"} // []
l!l
2962
MC/DC100%1/1
delete $opts{"messages"} // []
delete $opts{"messages"}
Truth table100%2/2
A
A= delete $opts{"messages"}
Aresult
11
00
772 298 ▶ my @messages = ref $messages eq 'ARRAY' ? @$messages : ($messages);
Branch: 1 branch
BranchTrueFalseTotal
ref $messages eq 'ARRAY' ? : 298 0 298
773  
774 # Before any decision is taken for chat_model (karr k352).
775 298 $self->_warn_model_override( 'chat_f', \%opts, 0 );
776  
777 # A Langertha::ServerTool needs a wire that takes server-side tools (k206).
778 298 Langertha::ServerTool->check_engine( $self, $opts{tools} );
779  
780 # Auto-fallback: forced named tool on an engine that cannot do
781 # native named-tool-forcing but supports json_schema response_format.
782 # Rewrite tools+tool_choice into a response_format and remember the
783 # tool name so we can synthesize a tool_calls entry afterwards.
784 292 my $synth_tool_name;
785 292 ▶ 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 251 292
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
250141
exists $opts{"tool_choice"} and exists $opts{"tools"} and not $self->supports("tool_choice_named")
!ll&&!rl&&r
2302042
exists $opts{"tool_choice"} and exists $opts{"tools"}
!ll&&!rl&&r
228262
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
786 && exists $opts{tools}
787 && !$self->supports('tool_choice_named')
788 && $self->supports('response_format_json_schema')
789 ) {
790 41 my $tc = Langertha::ToolChoice->from_hash( $opts{tool_choice} );
791 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
792 32 my $name = $tc->name;
793 my ($tool) =
794 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
795 33 map { Langertha::Tool->from_hash($_) }
796 32 @{ $opts{tools} };
797 32 ▶ if ($tool) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tool) 31 1 32
798 31 $self->_chat_rewrite_replaces_response_format( \%opts, $name );
799 22 delete $opts{tools};
800 22 delete $opts{tool_choice};
801 $opts{response_format} = {
802 type => 'json_schema',
803 json_schema => {
804 22 %{ $tool->to_json_schema },
805 strict => JSON->true,
806 },
807 };
808 22 $synth_tool_name = $name;
809 22 $log->debugf("[%s] forced-tool fallback: tool '%s' rerouted via response_format",
810 ref $self, $name);
811 }
812 }
813 }
814  
815 # Provider mutual-exclusion guard (karr #148). Consulted after the
816 # forced-tool fallback (which may have set response_format) so it sees the
817 # effective request; walks the per-model exclusion table for the selected
818 # chat_model and croaks on a combination the model rejects with an opaque 400.
819 $self->_check_capability_exclusions(
820 283 has_tools => $self->_chat_tools_requested(\%opts),
821 tool_choice_forced => $self->_chat_tool_choice_forced(\%opts),
822 response_format => $self->_chat_effective_response_format(\%opts),
823 streaming => 0,
824 );
825  
826 # Extract the canonical controls (after the forced-tool fallback, which may
827 # have set response_format) and hand them to chat_request under `controls`.
828 260 my $controls = $self->_extract_controls(\%opts);
829  
830 260 @messages = await $self->_prefetch_inline_images_f(@messages);
831 249 my ( $conversation, $hermes_prompted ) =
832 $self->_hermes_prompt_tools( \%opts, $self->chat_messages(@messages) );
833 248 ▶ $opts{tools} = $self->_wire_tools( $opts{tools} ) if ref $opts{tools} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts{"tools"} eq "ARRAY" 90 158 248
834  
835 248 $conversation = $self->_hermes_prompt_schema( $controls, $conversation );
836  
837 248 my $t0 = [gettimeofday];
838 248 ▶ my $request = $self->chat_request( $conversation,
Branch: 1 branch
BranchTrueFalseTotal
%$controls ? : 67 181 248
839 ( %$controls ? ( controls => $controls ) : () ),
840 %opts );
841  
842 248 my $response = await $self->_async_do_request_f( request => $request );
843  
844 # A failed response records its rate limit before the die (a success does it
845 # in parse_response), so a caller can back off from a 429 (karr k300).
846 245 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 21 224 245
847 21 ▶ $self->_update_rate_limit($response) if $self->can('_update_rate_limit');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_update_rate_limit") 21 0 21
848 # The sync croak's text, body included (karr k312).
849 21 die $self->_request_failed_message( $response, 'request' );
850 }
851  
852 224 my $elapsed = tv_interval($t0);
853 224 my $result = $request->response_call->($response);
854  
855 217 ▶ if ( blessed($result) && $result->isa('Langertha::Response') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->isa("Langertha::Response")) 217 0 217
Condition33%1/3
builtin::blessed($result) and $result->isa("Langertha::Response")
!ll&&!rl&&r
00217
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
856 217 $result = $result->clone_with(
857 timing => _merge_timing_field( $result->timing, total_seconds => $elapsed ),
858 );
859 }
860  
861 # One chat_with_tools_f turn on hermes (k231): the <tool_call> blocks the
862 # model wrote go onto Response.tool_calls (ADR 0003), out of content. An
863 # engine whose chat_response already lifted them (AKI native) is left alone.
864 217 ▶ 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 186 217
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
185131
$hermes_prompted and builtin::blessed($result) and $result->isa("Langertha::Response")
!ll&&!rl&&r
185032
$hermes_prompted and builtin::blessed($result)
!ll&&!rl&&r
185032
$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
865 1 && !( $result->has_tool_calls && @{ $result->tool_calls } ) ) {
866 31 my ( $clean, $calls ) = $self->_hermes_split_text( $result->content );
867 31 ▶ if (@$calls) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$calls) 14 17 31
868 # The reply ended to call tools: report that over the wire's stop, as the
869 # OpenAI dialect does for native calls (k248); ->raw keeps the wire value.
870 14 my $reason = $result->finish_reason;
871 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
872 ( !length( $reason // '' ) || $reason eq 'stop' ) ? ( finish_reason => 'tool_calls' ) : () );
873 }
874 }
875  
876 217 ▶ 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 195 217
Condition66%4/6
$synth_tool_name and builtin::blessed($result) and $result->isa("Langertha::Response")
!ll&&!rl&&r
195022
$synth_tool_name and builtin::blessed($result)
!ll&&!rl&&r
195022
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
877 22 my $args = $self->decode_loose_json( $result->content );
878 # A tool's arguments are a JSON object. Only synthesize the ToolCall when the
879 # model actually returned one — a non-object result (e.g. a bare JSON array)
880 # would otherwise be coerced to empty {} in Response BUILDARGS and the
881 # synthetic call would falsely claim success with no arguments. Leaving
882 # tool_calls unset lets the caller see the gap (the raw content is still on
883 # Response.content) instead of a hollow success.
884 22 ▶ if ( ref $args eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args eq 'HASH') { } 19 3 22
885 19 $result = $result->clone_with(
886 tool_calls => [{
887 name => $synth_tool_name,
888 arguments => $args,
889 synthetic => 1,
890 }],
891 );
892 }
893 else {
894 3 $log->debugf(
895 "[%s] forced-tool fallback: '%s' response was not a JSON object; no synthetic tool_call attached",
896 ref $self, $synth_tool_name);
897 }
898 }
899  
900 217 ▶ 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 211 217
Condition66%6/9
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result and $result->isa("Langertha::Response")
!ll&&!rl&&r
21106
$self->can("has_rate_limit") and $self->has_rate_limit and ref $result
!ll&&!rl&&r
21106
$self->can("has_rate_limit") and $self->has_rate_limit
!ll&&!rl&&r
02116
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
901 && ref $result && $result->isa('Langertha::Response') ) {
902 6 $result = $result->clone_with( rate_limit => $self->rate_limit );
903 }
904 217 return $result;
905 179 }
906  
907  
908  
909 1 ▶sub simple_chat_stream_f {
Subroutine simple_chat_stream_f: called CC=1 SCAR=0.0
Pod documented
910 1 my ($self, @messages) = @_;
911 1 return $self->simple_chat_stream_realtime_f(undef, @messages);
912 }
913  
914  
915 4 ▶async sub simple_chat_stream_realtime_f {
Subroutine simple_chat_stream_realtime_f: called CC=1 SCAR=0.0
Pod documented
916 4 my ($self, $chunk_callback, @messages) = @_;
917  
918 4 return await $self->chat_stream_realtime_f(
919 messages => \@messages,
920 chunk_callback => $chunk_callback,
921 );
922 179 }
923  
924 211 ▶async sub chat_stream_realtime_f {
Subroutine chat_stream_realtime_f: called CC=16 SCAR=27.9
Pod documented
925 211 my ( $self, %opts ) = @_;
926  
927 211 my $chunk_callback = delete $opts{chunk_callback};
928 211 ▶ my $messages = delete $opts{messages} // [];
Condition50%1/2
delete $opts{"messages"} // []
l!l
2110
MC/DC0%0/1
delete $opts{"messages"} // []
delete $opts{"messages"}
Truth table50%1/2
A
A= delete $opts{"messages"}
Aresult
11
00
929 211 ▶ my @messages = ref $messages eq 'ARRAY' ? @$messages : ($messages);
Branch: 1 branch
BranchTrueFalseTotal
ref $messages eq 'ARRAY' ? : 211 0 211
930  
931 211 ▶ croak "".(ref $self)." does not support streaming"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("chat_stream_request") 1 210 211
932 unless $self->can('chat_stream_request');
933  
934 # Before any decision is taken for chat_model (karr k352).
935 210 $self->_warn_model_override( 'chat_stream_realtime_f', \%opts, 1 );
936  
937 # A Langertha::ServerTool needs a wire that takes server-side tools (k206).
938 210 Langertha::ServerTool->check_engine( $self, $opts{tools} );
939  
940 # Provider mutual-exclusion guard (karr #148) — streaming path. Same per-model
941 # seam as chat_f; the streaming flag lets a rule refuse a combination that is
942 # rejected only when streaming (e.g. Groq structured outputs, which do not
943 # support streaming at all).
944 210 $self->_check_capability_exclusions(
945 has_tools => $self->_chat_tools_requested(\%opts),
946 tool_choice_forced => $self->_chat_tool_choice_forced(\%opts),
947 response_format => $self->_chat_effective_response_format(\%opts),
948 streaming => 1,
949 );
950  
951 # Same canonical-control extraction as chat_f (karr #46).
952 205 my $controls = $self->_extract_controls(\%opts);
953  
954 205 @messages = await $self->_prefetch_inline_images_f(@messages);
955 205 my ( $conversation, $hermes_prompted ) =
956 $self->_hermes_prompt_tools( \%opts, $self->chat_messages(@messages) );
957 205 $conversation = $self->_hermes_prompt_schema( $controls, $conversation );
958 205 ▶ $opts{tools} = $self->_wire_tools( $opts{tools} ) if ref $opts{tools} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $opts{"tools"} eq "ARRAY" 7 198 205
959  
960 205 ▶ my $request = $self->chat_stream_request( $conversation,
Branch: 1 branch
BranchTrueFalseTotal
%$controls ? : 3 202 205
961 ( %$controls ? ( controls => $controls ) : () ),
962 %opts );
963 199 my @all_chunks;
964 199 my $buffer = '';
965 199 my %stream_state; # this stream's parse state (tool-call fragments, karr k221)
966 199 my $format = $self->stream_format;
967 199 my $response_status;
968 my $error_content; # the body of a non-2xx response
969 199 my $t0 = [gettimeofday];
970 199 my $ttft_seconds;
971  
972 # Every parsed chunk goes out through here. When the tools rode the hermes
973 # prompt, the <tool_call> blocks are withheld from the text and their calls
974 # land on the final chunk, as chat_f lifts them from its reply (karr k253).
975 my %hermes_state;
976 # $flush (no chunk) asks the lift for what a stream without a final chunk
977 # still owes.
978 1822 ▶ my $deliver = sub {
Subroutine __ANON__: called CC=7 SCAR=19.6
979 1822 my ( $chunk, $flush ) = @_;
980 1822 ▶ $ttft_seconds = tv_interval($t0) unless defined $ttft_seconds || $flush;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ttft_seconds or $flush 184 1638 1822
Condition66%2/3
defined $ttft_seconds or $flush
l!l&&r!l&&!r
16380184
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
981 1822 ▶ if ($hermes_prompted) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hermes_prompted) 1649 173 1822
982 1649 $chunk = $self->_hermes_stream_chunk( \%hermes_state, $chunk, $flush );
983 1649 ▶ return unless $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless $chunk 1154 495 1649
984 }
985 668 ▶ $ttft_seconds //= tv_interval($t0);
Condition33%1/3
$ttft_seconds //= tv_interval($t0)
l!l&&r!l&&!r
66800
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
986 668 push @all_chunks, $chunk;
987 668 ▶ $chunk_callback->($chunk) if $chunk_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk_callback 538 130 668
988 199 };
989  
990 # A die in the chunk-sub (a malformed stream line, or the caller's
991 # chunk_callback) must fail this request's future on every backend, and must
992 # not unwind into the backend: Net::Async::HTTP runs the chunk-sub inside
993 # the loop's read handler, where a die escapes the loop and leaves this
994 # request pending (karr k194, ADR 0027).
995 199 my ( $request_f, $stream_error );
996 $request_f = $self->_async_do_request_f(
997 request => $request,
998 196 ▶ on_header => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
999 196 my ($response) = @_;
1000 196 $response_status = $response;
1001  
1002 # A non-2xx body is the provider's error, not a stream: keep it for the
1003 # error text (the sync croak shows it, karr k312) instead of parsing it.
1004 # Net::Async::HTTP hands the header response without the body.
1005 196 ▶ unless ( $response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 8 188 196
1006 8 $error_content = '';
1007 8 ▶ return sub { $error_content .= $_[0] if defined $_[0] };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[0] 8 8 16
1008 }
1009  
1010 # Return a callback that handles each body chunk
1011 2085 ▶ return sub {
Subroutine __ANON__: called CC=10 SCAR=23.0
1012 2085 my ($data) = @_;
1013 2085 ▶ return if $stream_error; # already failed; drop the rest
Branch: 1 branch
BranchTrueFalseTotal
if $stream_error 15 2070 2085
1014 2070 ▶ return unless defined $data; # undef signals end of body
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 167 1903 2070
1015  
1016 1903 my $ok = eval {
1017 1903 $buffer .= $data;
1018 1903 my $chunks = $self->_process_stream_buffer(\$buffer, $format, 0, \%stream_state);
1019 1895 $deliver->($_) for @$chunks;
1020 1885 1;
1021 };
1022 1903 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 1885 18 1903
1023 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
1024  
1025 # A synchronous backend (Langertha::Request::SyncHTTP) runs the
1026 # chunk-sub before do_request returns: die again so it stops reading
1027 # and fails its own future with the original exception.
1028 18 ▶ die $stream_error->[0] unless $request_f;
Branch: 1 branch
BranchTrueFalseTotal
unless $request_f 5 13 18
1029  
1030 # An event-loop backend must not be stopped from in here. Cancelling
1031 # a Net::Async::HTTP request closes its connection, and doing that
1032 # inside its read handler leaves the rest of an already-read burst
1033 # in the buffer of a connection with no request left, which
1034 # Net::Async::HTTP then dies on ("Spurious on_read"). Cancel on the
1035 # next loop iteration instead, once this read is fully processed; if
1036 # the response completes within this read there is nothing to cancel.
1037 # A future without an IO::Async-style loop (an injected client with
1038 # no loop, or one from another event system) is drained.
1039 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
1040 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
1041 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
1042 13 return;
1043 188 };
1044 },
1045 199 );
1046  
1047 # Wait for the transfer to end however it ends: done, failed, or cancelled
1048 # above. A cancel from our own caller still stops the transfer.
1049 199 my $transfer_f = $request_f->new;
1050 199 ▶ $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 199 0 199
1051 199 ▶ $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
1052 199 await $transfer_f;
1053 # The headers arrived, so their rate limit is this response's, whatever
1054 # happens to the body or the status next (karr k300). Taken here, not in
1055 # on_header, which may run inside the event loop's read handler.
1056 196 ▶ $self->_update_rate_limit($response_status)
Branch: 1 branch
BranchTrueFalseTotal
if $response_status and $self->can("_update_rate_limit") 194 2 196
Condition66%2/3
$response_status and $self->can("_update_rate_limit")
!ll&&!rl&&r
20194
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
1057 if $response_status && $self->can('_update_rate_limit');
1058 # The exception that stopped the stream wins over any transport failure
1059 # seen afterwards (from the cancel, a drain, or the connection itself).
1060 196 ▶ await Future->fail(@$stream_error) if $stream_error;
Branch: 1 branch
BranchTrueFalseTotal
if $stream_error 18 178 196
1061 178 ▶ await $request_f if $request_f->is_failed;
Branch: 1 branch
BranchTrueFalseTotal
if $request_f->is_failed 2 176 178
1062  
1063 176 ▶ unless ($response_status->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response_status->is_success) 8 167 175
1064 8 my $failed = $response_status->clone;
1065 8 ▶ $failed->content($error_content) if defined $error_content;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error_content 8 0 8
1066 8 die $self->_request_failed_message( $failed, 'streaming request' );
1067 }
1068  
1069 # Process remaining buffer
1070 167 ▶ if ($buffer ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffer ne "") 0 167 167
1071 0 my $chunks = $self->_process_stream_buffer(\$buffer, $format, 1, \%stream_state);
1072 0 $deliver->($_) for @$chunks;
1073 }
1074 # A hermes stream that ended without a final chunk still owes its held text
1075 # (a partial or unclosed tag is text) and the calls of its closed blocks.
1076 167 ▶ $deliver->( undef, 1 ) if $hermes_prompted;
Branch: 1 branch
BranchTrueFalseTotal
if $hermes_prompted 119 48 167
1077 # The stream ended: let the dialect report what it could not finish (a
1078 # tool call that never saw its finish_reason, karr k221).
1079 167 ▶ $self->_finish_stream_state(\%stream_state) if $self->can('_finish_stream_state');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("_finish_stream_state") 165 2 167
1080  
1081 167 my $content = join('', map { $_->content } @all_chunks);
1082 167 my $thinking = $self->aggregate_thinking(\@all_chunks);
1083 167 my $total_seconds = tv_interval($t0);
1084 167 return ($content, \@all_chunks, {
1085 ttft_seconds => $ttft_seconds,
1086 total_seconds => $total_seconds,
1087 }, $thinking);
1088 179 }
1089  
1090 # Decides a caller's tool_choice against supports('tool_choice_*'), in place,
1091 # for every request builder whose wire field may be missing (karr k239, the
1092 # k233 Responses rule generalized; ADR 0002: field emission follows the
1093 # claimed capability). Returns the Langertha::ToolChoice to serialize when the
1094 # engine supports its kind; the builder calls ->to($fmt) itself, since only it
1095 # knows its envelope. Otherwise the field is deleted: undef or 'auto' (the
1096 # wire default) silently; 'none' withholds the request's tools too, so "call
1097 # no tool" holds without the field, with a carp when there were tools to
1098 # withhold (none without tools is silent, as on the hermes wire, k246); a
1099 # forced choice (any /
1100 # named) with a carp, the model then decides. chat_f's ADR 0005 rewrite runs
1101 # first and has already taken a forced named tool it could reroute. A value
1102 # ToolChoice cannot read (a provider-native choice) stays as given where the
1103 # wire has a tool_choice field at all, and is dropped with a carp where not.
1104 2219 ▶sub _gate_tool_choice {
Subroutine _gate_tool_choice: called CC=14 SCAR=26.4
1105 2219 my ( $self, $extra ) = @_;
1106 2219 ▶ return unless exists $extra->{tool_choice};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $extra->{"tool_choice"} 2112 107 2219
1107 107 my $has_field = grep { $self->supports("tool_choice_$_") } qw( auto any none named );
1108 107 ▶ unless ( defined $extra->{tool_choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $extra->{"tool_choice"}) 4 103 107
1109 4 ▶ delete $extra->{tool_choice} unless $has_field;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_field 4 0 4
1110 4 return;
1111 }
1112 103 my $tc = Langertha::ToolChoice->from_hash( $extra->{tool_choice} );
1113 103 ▶ unless ($tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tc) 5 98 103
1114 5 ▶ return if $has_field;
Branch: 1 branch
BranchTrueFalseTotal
if $has_field 3 2 5
1115 2 delete $extra->{tool_choice};
1116 2 $self->_langertha_carp( "".( ref $self ).": dropping tool_choice -- this engine has no tool_choice "
1117 . "field and the value is not one Langertha can read; the model decides whether to call a tool" );
1118 2 return;
1119 }
1120 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
1121 98 ▶ return $tc if $self->supports($cap);
Branch: 1 branch
BranchTrueFalseTotal
if $self->supports($cap) 36 62 98
1122 62 delete $extra->{tool_choice};
1123 62 ▶ if ( $tc->type eq 'none' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc->type eq "none") 24 38 62
1124 24 my $tools = delete $extra->{tools};
1125 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
1126 . "support('tool_choice_none'); the request's tools are withheld instead" )
1127 if ref $tools eq 'ARRAY' && @$tools;
1128 24 return;
1129 }
1130 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
1131 . ( $tc->type eq 'tool' ? 'tool ' . ( $tc->name // '' ) : $tc->type )
1132 . "' -- this engine does not support('$cap'); the model decides whether to call a tool" )
1133 unless $tc->type eq 'auto';
1134 38 return;
1135 }
1136  
1137 # parallel_tool_use -> parallel_tool_calls, in place, for the Chat Completions
1138 # and Responses builders alike (streaming too, karr k240); Ollama native and
1139 # Gemini call it only for the drop carp (flag cleared, k241). Only when tools are
1140 # present. A per-request control beats the engine attribute; an explicit
1141 # parallel_tool_calls kwarg is the caller's wire intent and wins over both.
1142 # Emitted only where the engine supports('parallel_tool_use') (karr k241, ADR
1143 # 0002); a value the caller set that the gate drops carps (ADR 0025
1144 # drop+carp), nothing set stays silent.
1145 2480 ▶sub _parallel_tool_calls_kwarg {
Subroutine _parallel_tool_calls_kwarg: called CC=10 SCAR=23.0
1146 2480 my ( $self, $extra, $controls ) = @_;
1147 2480 ▶ 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"} 2051 429 2480
Condition100%3/3
exists $extra->{"tools"} and not exists $extra->{"parallel_tool_calls"}
!ll&&!rl&&r
203912429
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
1148 429 my ( $ptu, $from_attr );
1149 429 ▶ if ( exists $controls->{parallel_tool_use} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $controls->{'parallel_tool_use'}) { } 41 388 429
elsif ($self->can('has_parallel_tool_use') and $self->has_parallel_tool_use) { } 24 364 388
1150 41 $ptu = $controls->{parallel_tool_use};
1151 }
1152 ▶ 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
036424
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
1153 24 $ptu = $self->parallel_tool_use;
1154 24 $from_attr = 1;
1155 }
1156 429 ▶ return unless defined $ptu;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ptu 364 65 429
1157 65 ▶ unless ( $self->supports('parallel_tool_use') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->supports("parallel_tool_use")) 45 20 65
1158 45 ▶ $self->_langertha_carp( "".( ref $self ).": dropping parallel_tool_use -- this engine does not "
Branch: 1 branch
BranchTrueFalseTotal
$from_attr ? : 20 25 45
1159 . "support('parallel_tool_use'); the provider decides how many tool calls a turn has",
1160 $from_attr ? "parallel_tool_use=$ptu" : undef );
1161 45 return;
1162 }
1163 20 ▶ $extra->{parallel_tool_calls} = $ptu ? JSON->true : JSON->false;
Branch: 1 branch
BranchTrueFalseTotal
$ptu ? : 9 11 20
1164 20 return;
1165 }
1166  
1167 # The one path that puts a caller's tools list on the wire, for chat_f and
1168 # chat_stream_realtime_f alike (karr k221, k227; ADR 0001). A tools list is
1169 # often built by hand: Langertha::Tool / ServerTool objects next to hashes of
1170 # any shape. The JSON encoder would put an object on the wire in its canonical
1171 # to_hash shape, which only the Anthropic wire reads, so the value objects
1172 # shape the list for this engine's tool_wire_format, item by item and in the
1173 # caller's order (Langertha::Tool->request_list): objects serialize, hashes
1174 # already in the wire's shape pass through verbatim (extras and built-ins
1175 # included), other function-tool hashes convert. Order is caller intent, and
1176 # an Anthropic cache_control breakpoint caches the prefix of the list.
1177 # Left alone: an engine without Role::Tools, and the Responses envelope,
1178 # which already decides per item itself and needs the ServerTool objects for
1179 # its engine hook and default-tool dedup (_responses_tools_kwarg, k210/k206).
1180 # The hermes wire never gets here: _hermes_prompt_tools took the list off.
1181 99 ▶sub _wire_tools {
Subroutine _wire_tools: called CC=3 SCAR=11.0
1182 99 my ( $self, $tools ) = @_;
1183 99 ▶ return $tools unless $self->can('tool_wire_format');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("tool_wire_format") 0 99 99
1184 99 my $fmt = $self->tool_wire_format;
1185 99 ▶ return $tools if $fmt eq 'responses';
Branch: 1 branch
BranchTrueFalseTotal
if $fmt eq "responses" 8 91 99
1186 91 return Langertha::Tool->request_list( $fmt, $tools );
1187 }
1188  
1189 # The hermes wire has no tools or tool_choice body key: the tools ride the
1190 # system prompt (Role::HermesTools). A chat_f / chat_stream_realtime_f turn is
1191 # built as one chat_with_tools_f turn (karr k231, ADR 0001): the list goes
1192 # through the same format_tools and prompt builder, and neither key reaches
1193 # the body. tool_choice none withholds the tools (no prompt, so no reply
1194 # lift either; the Responses rule of k233). The prompt cannot force a tool,
1195 # so any other choice but auto (or undef, no choice) is ignored with a carp.
1196 # Returns the conversation to send and whether the tool prompt was put in
1197 # front of it.
1198 454 ▶sub _hermes_prompt_tools {
Subroutine _hermes_prompt_tools: called CC=12 SCAR=24.9
1199 454 my ( $self, $opts, $conversation ) = @_;
1200 454 ▶ return ( $conversation, 0 )
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("tool_wire_format") and $self->tool_wire_format eq "hermes" 276 178 454
Condition100%3/3
$self->can("tool_wire_format") and $self->tool_wire_format eq "hermes"
!ll&&!rl&&r
1275178
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
1201 unless $self->can('tool_wire_format') && $self->tool_wire_format eq 'hermes';
1202 178 my $tools = delete $opts->{tools};
1203 178 my $given = delete $opts->{tool_choice};
1204 178 ▶ my $choice = defined $given ? Langertha::ToolChoice->from_hash($given) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $given ? : 8 170 178
1205 178 ▶ my $type = $choice ? $choice->type : '';
Branch: 1 branch
BranchTrueFalseTotal
$choice ? : 8 170 178
1206 178 ▶ if ( $type eq 'none' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "none") 3 175 178
1207 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
1208 . "the tools were withheld from the system prompt" )
1209 if ref $tools eq 'ARRAY' && @$tools;
1210 3 return ( $conversation, 0 );
1211 }
1212 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
1213 . "(tools ride the system prompt, which cannot force a tool)" )
1214 if defined $given && $type ne 'auto';
1215 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
1216 155 return ( $self->_hermes_tool_messages( $conversation, $self->format_tools($tools) ), 1 );
1217 }
1218  
1219 # On the hermes wire a json_schema response_format -- the caller's, the
1220 # engine's, or the ADR 0005 rewrite's -- also rides a leading system message
1221 # (karr k234), so a backend that ignores response_format still sees the
1222 # schema. Only on an engine whose wire takes response_format (NousResearch).
1223 453 ▶sub _hermes_prompt_schema {
Subroutine _hermes_prompt_schema: called CC=7 SCAR=19.5
1224 453 my ( $self, $controls, $conversation ) = @_;
1225 453 ▶ 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") 279 174 453
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
2763174
$self->can("tool_wire_format") and $self->tool_wire_format eq "hermes"
!ll&&!rl&&r
1275177
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
1226 unless $self->can('tool_wire_format') && $self->tool_wire_format eq 'hermes'
1227 && $self->supports('response_format_json_schema');
1228 my $format = exists $controls->{response_format} ? $controls->{response_format}
1229 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
1230 : undef;
1231 174 return $self->_hermes_schema_messages( $conversation, $format );
1232 }
1233  
1234 142 ▶sub aggregate_tool_calls {
Subroutine aggregate_tool_calls: called CC=4 SCAR=13.9
Pod documented
1235 142 my ( $self, $chunks ) = @_;
1236 142 ▶ return [] unless ref($chunks) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $chunks eq "ARRAY" 0 142 142
1237 142 my @tcs;
1238 142 for my $c (@$chunks) {
1239 578 ▶ next unless eval { $c->has_tool_calls };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $c->has_tool_calls } } 442 136 578
1240 136 push @tcs, @{ $c->tool_calls };
1241 }
1242 142 return \@tcs;
1243 }
1244  
1245  
1246 182 ▶sub aggregate_thinking {
Subroutine aggregate_thinking: called CC=6 SCAR=17.9
Pod documented
1247 182 my ( $self, $chunks ) = @_;
1248 182 ▶ return undef unless ref($chunks) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $chunks eq "ARRAY" 1 181 182
1249 181 my $thinking = '';
1250 181 my $seen = 0;
1251 181 for my $c (@$chunks) {
1252 696 ▶ my $t = eval { $c->has_thinking ? $c->thinking : undef };
Branch: 1 branch
BranchTrueFalseTotal
$c->has_thinking ? : 25 671 696
1253 696 ▶ next unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 671 25 696
1254 25 $thinking .= $t;
1255 25 $seen = 1;
1256 }
1257 181 ▶ return $seen ? $thinking : undef;
Branch: 1 branch
BranchTrueFalseTotal
$seen ? : 12 169 181
1258 }
1259  
1260  
1261 # Every dialect reports cumulative usage, but not always on the final chunk:
1262 # the OpenAI include_usage frame arrives after it (karr k298). The last chunk
1263 # that carries usage has the stream's totals.
1264 5 ▶sub aggregate_usage {
Subroutine aggregate_usage: called CC=5 SCAR=16.1
Pod documented
1265 5 my ( $self, $chunks ) = @_;
1266 5 ▶ return undef unless ref($chunks) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $chunks eq "ARRAY" 0 5 5
1267 5 my $usage;
1268 5 for my $c (@$chunks) {
1269 16 ▶ my $u = eval { $c->has_usage ? $c->usage : undef };
Branch: 1 branch
BranchTrueFalseTotal
$c->has_usage ? : 6 10 16
1270 16 ▶ $usage = $u if ref $u eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $u eq "HASH" 6 10 16
1271 }
1272 5 return $usage;
1273 }
1274  
1275  
1276  
1277  
1278 9464 ▶sub _process_stream_buffer {
Subroutine _process_stream_buffer: called CC=21 SCAR=30.7
1279 9464 my ($self, $buffer_ref, $format, $final, $state) = @_;
1280  
1281 9464 my @chunks;
1282  
1283 9464 ▶ if ($format eq 'sse') {
Branch: 2 branches
BranchTrueFalseTotal
if ($format eq 'sse') { } 9139 325 9464
elsif ($format eq 'ndjson') { } 325 0 325
1284 # On the final flush ($final, passed after the stream body ends) the last
1285 # event can arrive without its terminating blank line — the connection just
1286 # closed. Append one so the loop below consumes the remainder instead of
1287 # dropping it (its finish_reason / usage would be lost, and the sync
1288 # process_stream_data path — which splits the whole body at once — keeps it).
1289 # Event separators and line breaks are matched CRLF-tolerantly (\r?\n) to
1290 # match that sync path (split /\r?\n/).
1291 9139 ▶ $$buffer_ref .= "\n\n" if $final && $$buffer_ref ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $final and $$buffer_ref ne "" 16 9123 9139
Condition100%3/3
$final and $$buffer_ref ne ""
!ll&&!rl&&r
91091416
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
1292 9139 ▶ while ($$buffer_ref =~ s/^(.*?)\r?\n\r?\n//s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^(.*?)\r?\n\r?\n//s) 2080 9131 11211
1293 2080 my $block = $1;
1294 2080 for my $line (split /\r?\n/, $block) {
1295 2198 ▶ next if $line eq '' || $line =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" or $line =~ /^:/ 0 2198 2198
Condition33%1/3
$line eq "" or $line =~ /^:/
l!l&&r!l&&!r
002198
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
1296 2198 ▶ if ($line =~ /^data:\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^data:\s*(.*)$/) 2072 126 2198
1297 2072 my $json_data = $1;
1298 2072 ▶ next if $json_data eq '[DONE]' || $json_data eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $json_data eq "[DONE]" or $json_data eq "" 172 1900 2072
Condition66%2/3
$json_data eq "[DONE]" or $json_data eq ""
l!l&&r!l&&!r
17201900
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
1299 1900 my $parsed = $self->json->decode($json_data);
1300 1894 my $chunk = $self->parse_stream_chunk($parsed, undef, $state);
1301 1892 ▶ push @chunks, $chunk if $chunk;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk 1813 79 1892
1302 }
1303 }
1304 }
1305 } elsif ($format eq 'ndjson') {
1306 325 ▶ $$buffer_ref .= "\n" if $final && $$buffer_ref ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $final and $$buffer_ref ne "" 1 324 325
Condition100%3/3
$final and $$buffer_ref ne ""
!ll&&!rl&&r
32221
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
1307 325 ▶ while ($$buffer_ref =~ s/^(.*?)\r?\n//s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^(.*?)\r?\n//s) 8 325 333
1308 8 my $line = $1;
1309 8 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 8 8
1310 8 my $parsed = $self->json->decode($line);
1311 8 my $chunk = $self->parse_stream_chunk($parsed, undef, $state);
1312 8 ▶ push @chunks, $chunk if $chunk;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk 8 0 8
1313 }
1314 }
1315  
1316 # A final flush without a caller-owned state ends the stream on the
1317 # engine-wide fallback: close it here, so nothing left unfinished there can
1318 # reach the next stream. A caller that passes its own state (as
1319 # chat_stream_realtime_f does) closes it itself.
1320 $self->_finish_stream_state
1321 9456 ▶ if $final && !$state && $self->can('_finish_stream_state');
Branch: 1 branch
BranchTrueFalseTotal
if $final and not $state and $self->can("_finish_stream_state") 13 9443 9456
Condition100%6/6
$final and not $state and $self->can("_finish_stream_state")
!ll&&!rl&&r
94321113
$final and not $state
!ll&&!rl&&r
9423924
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
1322  
1323 9456 return \@chunks;
1324 }
1325  
1326 179 with 'Langertha::Role::ThinkTag', 'Langertha::Role::Langfuse', 'Langertha::Role::AsyncHTTP';
1327  
1328  
1329 179 1;
1330  
1331 __END__
1332  
1333 =pod
1334  
1335 =encoding UTF-8
1336  
1337 =head1 NAME
1338  
1339 Langertha::Role::Chat - Role for APIs with normal chat functionality
1340  
1341 =head1 VERSION
1342  
1343 version 0.503
1344  
1345 =head1 SYNOPSIS
1346  
1347 # Synchronous chat
1348 my $response = $engine->simple_chat('Hello, how are you?');
1349  
1350 # Streaming with callback
1351 $engine->simple_chat_stream(sub {
1352 my ($chunk) = @_;
1353 print $chunk->content;
1354 }, 'Tell me a story');
1355  
1356 # Streaming with iterator
1357 my $stream = $engine->simple_chat_stream_iterator('Tell me a story');
1358 while (my $chunk = $stream->next) {
1359 print $chunk->content;
1360 }
1361  
1362 # Async with Future (traditional style)
1363 my $future = $engine->simple_chat_f('Hello');
1364 my $response = $future->get;
1365  
1366 # Async with Future::AsyncAwait (recommended)
1367 use Future::AsyncAwait;
1368  
1369 async sub chat_example {
1370 my ($engine) = @_;
1371 my $response = await $engine->simple_chat_f('Hello');
1372 say $response;
1373 }
1374  
1375 # Async streaming with real-time callback
1376 async sub stream_example {
1377 my ($engine) = @_;
1378 my ($content, $chunks) = await $engine->simple_chat_stream_realtime_f(
1379 sub { print shift->content },
1380 'Tell me a story'
1381 );
1382 say "\nTotal chunks: ", scalar @$chunks;
1383 }
1384  
1385 =head1 DESCRIPTION
1386  
1387 This role provides chat functionality for LLM engines. It includes both
1388 synchronous and asynchronous (L<Future>-based) methods for chat and streaming.
1389  
1390 The Future-based C<_f> methods are implemented using L<Future::AsyncAwait>. The
1391 HTTP backend is selected by L<Langertha::Role::AsyncHTTP>: an injected
1392 C<_async_http> client wins, else L<Net::Async::HTTP> if it can be loaded, else a
1393 synchronous L<LWP::UserAgent> fallback (L<Langertha::Request::SyncHTTP>). These
1394 async modules are loaded lazily only on the async path, so synchronous-only
1395 usage — and the sync fallback — does not require them.
1396  
1397 When the sync fallback is used the C<_f> methods still return a L<Future> and
1398 keep working, but they run B<synchronously and sequentially> (blocking, no
1399 concurrency): the future is already complete when returned, so several C<_f>
1400 calls awaited "in parallel" run one after another. Install L<Net::Async::HTTP>
1401 + L<IO::Async> (or inject your own C<_async_http> client) for real concurrency.
1402  
1403 =head2 chat_model
1404  
1405 The model name used for chat requests. Lazily defaults to C<default_chat_model>
1406 if the engine provides it, otherwise falls back to the general C<model>
1407 attribute from L<Langertha::Role::Models>.
1408  
1409 =head2 chat
1410  
1411 my $request = $engine->chat(@messages);
1412  
1413 Builds and returns a chat HTTP request object. Messages may be plain strings
1414 (treated as C<user> role) or HashRefs with C<role> and C<content> keys. A
1415 system prompt from L<Langertha::Role::SystemPrompt> is prepended automatically.
1416  
1417 =head2 inline_image_fetch_timeout
1418  
1419 Seconds each URL image fetch may take on an engine that has to inline images
1420 (see L</content_format>) before the call fails with the engine-named
1421 inline-image error. Defaults to C<30>.
1422  
1423 On the C<_f> paths it is enforced on the event loop of the async backend
1424 (L<Langertha::Role::AsyncHTTP/async_loop>; the error says C<timed out after
1425 30s>), and C<0> disables it; on the synchronous LWP fallback, or with an
1426 injected client without a C<loop>, the client's own timeout applies instead
1427 (for the fallback, the C<user_agent>'s). When the synchronous methods build the
1428 request, it is the LWP timeout of L<Langertha::Content::Image/ensure_base64>
1429 (the error then carries LWP's C<read timeout> status), and C<0> leaves LWP's
1430 own default of 180 seconds, because LWP cannot run without a timeout.
1431  
1432 =head2 inline_image_max_bytes
1433  
1434 The most bytes a URL image fetch may download on an engine that has to inline
1435 images (see L</content_format>). Defaults to C<20971520> (20 MiB), about the
1436 largest inline image providers take; C<0> removes the cap. Enforced on every
1437 backend: a C<Content-Length> over the cap stops the fetch before the body, and
1438 a body that grows past it stops the download (L<Net::Async::HTTP> closes the
1439 connection, LWP stops reading). The call then fails with the engine-named
1440 inline-image error carrying
1441  
1442 Langertha::Content::Image image at <url> exceeds inline_image_max_bytes (<n>)
1443  
1444 on the synchronous and the C<_f> paths alike.
1445 See L<Langertha::Content::Image/ensure_base64>.
1446  
1447 =head2 inline_image_url_filter
1448  
1449 inline_image_url_filter => Langertha::Content::Image->deny_private_hosts,
1450 inline_image_url_filter => sub { my ($uri) = @_; $uri->host eq 'img.example.com' },
1451  
1452 Optional code reference that decides which image URLs an engine that has to
1453 inline images may fetch, against server-side request forgery when image URLs
1454 come from untrusted input (a gateway forwarding its clients' messages). It gets
1455 a L<URI> object and returns true to allow the fetch. It runs on the image URL
1456 before any request and on every redirect hop before that hop is requested; a
1457 refusal fails the call with the engine-named inline-image error. Unset by
1458 default: every C<http> and C<https> URL is fetched.
1459 L<Langertha::Content::Image/deny_private_hosts> returns a filter that refuses
1460 loopback, link-local, private, carrier-grade NAT and cloud metadata addresses;
1461 read its DNS-rebinding caveat. Only the fetches Langertha makes are filtered:
1462 engines that pass an image URL through to the provider (OpenAI, Anthropic)
1463 leave the fetch to the provider.
1464  
1465 =head2 chat_messages
1466  
1467 my $messages = $engine->chat_messages(@messages);
1468  
1469 Normalises C<@messages> into the canonical ArrayRef-of-HashRef format expected
1470 by C<chat_request>. Plain strings become C<{ role =E<gt> 'user', content =E<gt>
1471 $string }>. If the engine has a C<system_prompt> set it is prepended as a
1472 C<system> message.
1473  
1474 =head2 simple_chat
1475  
1476 my $response = $engine->simple_chat(@messages);
1477 my $response = $engine->simple_chat('Hello, how are you?');
1478  
1479 Sends a synchronous chat request and returns the response text. Blocks until
1480 the request completes.
1481  
1482 =head2 chat_stream
1483  
1484 my $request = $engine->chat_stream(@messages);
1485  
1486 Builds and returns a streaming chat HTTP request object. Croaks if the engine
1487 does not implement C<chat_stream_request>. Use L</simple_chat_stream> or
1488 L</simple_chat_stream_iterator> to execute the request.
1489  
1490 =head2 simple_chat_stream
1491  
1492 my $content = $engine->simple_chat_stream($callback, @messages);
1493  
1494 $engine->simple_chat_stream(sub {
1495 my ($chunk) = @_;
1496 print $chunk->content;
1497 }, 'Tell me a story');
1498  
1499 Sends a synchronous streaming chat request. Calls C<$callback> with each
1500 L<Langertha::Stream::Chunk> as it arrives (each chunk may carry incremental
1501 C<thinking>, see L<Langertha::Stream::Chunk/thinking>). In scalar context
1502 returns the complete concatenated content string; in list context returns
1503 C<($content, $thinking)> where C<$thinking> is the aggregated chain-of-thought
1504 (C<undef> when the engine surfaced none), as L</aggregate_thinking> assembles
1505 it. Blocks until the stream completes. C<total_seconds> is logged; for a full
1506 breakdown read L</execute_streaming_request>.
1507  
1508 =head2 simple_chat_stream_iterator
1509  
1510 my $stream = $engine->simple_chat_stream_iterator(@messages);
1511 while (my $chunk = $stream->next) {
1512 print $chunk->content;
1513 }
1514  
1515 Returns a L<Langertha::Stream> iterator. The full response is fetched
1516 synchronously and buffered; iteration yields each L<Langertha::Stream::Chunk>
1517 in order.
1518  
1519 =head2 _extract_controls
1520  
1521 my $controls = $engine->_extract_controls(\%opts);
1522  
1523 Removes the canonical per-request controls (karr #46) from C<%opts> and returns
1524 them as a HashRef. The engine's C<chat_request> receives the hash under the
1525 C<controls> key and places each control on its wire; unknown keys stay in
1526 C<%opts> and pass straight through as before.
1527  
1528 =head2 model_capability_exclusions
1529  
1530 sub model_capability_exclusions {
1531 return (
1532 qr/some-family/ => \&_exclude_some_combination, # a model family (regex)
1533 'exact-model-id' => \&_exclude_some_combination, # an exact model id
1534 );
1535 }
1536  
1537 The per-model capability-exclusion seam (karr #148), consulted at the
1538 C<chat_f> / C<chat_stream_realtime_f> layer above the boolean registry. A
1539 boolean capability flag asserts I<the wire accepts field X>; this seam
1540 expresses a I<mutual exclusion between two fields in one request> — combining
1541 C<tools> with a structured-output C<response_format> — which a flag cannot spell
1542 (L<ADR 0021|docs/adr/0021-pairwise-capability-exclusions-as-per-engine-guard.md>).
1543  
1544 Returns an B<ordered> list of C<< ( $matcher => $rule ) >> pairs, keyed on
1545 C<chat_model> exactly as L<Langertha::Role::Capabilities/model_capability_corrections>
1546 is. C<$matcher> is an exact model-id string (matched with C<eq>) or a C<qr//>
1547 regex (matched against C<chat_model>) — model ids come in families and, through
1548 aggregators, carry a C<provider/> prefix, so a regex catches the routed backend
1549 id too. C<$rule> is a B<coderef> (the concrete seam — deliberately not a
1550 constraint DSL) invoked as C<< $self->$rule(%request) >> with C<has_tools>,
1551 C<tool_choice_forced> (true for a C<tool_choice> of C<any>/C<required> or a
1552 named tool, as the caller passed it), C<response_format> (the one that goes on
1553 the wire: the per-request value, else the engine's C<response_format>
1554 attribute) and C<streaming>; it C<croak>s when the request hits the combination
1555 the model rejects.
1556  
1557 Where the rule lives depends on what the constraint belongs to. Groq and
1558 Cerebras reject C<tools> alongside a structured-output C<response_format> across
1559 every model they serve — a property of the serving stack — so each declares an
1560 all-models (C<qr//>) rule by overriding this method. SGLang does the same for a
1561 forced C<tool_choice> combined with a C<response_format>. A constraint that belonged
1562 to one model would instead be keyed on that model id or family regex, leaving a
1563 sibling model on the same engine unaffected. The default is an empty list, so an
1564 engine that constrains nothing pays nothing.
1565  
1566 =head2 simple_chat_f
1567  
1568 # Traditional Future style
1569 my $response = $engine->simple_chat_f(@messages)->get;
1570  
1571 # With async/await (recommended)
1572 use Future::AsyncAwait;
1573 async sub my_chat {
1574 my $response = await $engine->simple_chat_f(@messages);
1575 return $response;
1576 }
1577  
1578 Async version of L</simple_chat>. Returns a L<Future> that resolves to the
1579 response text. The HTTP backend comes from L<Langertha::Role::AsyncHTTP>:
1580 L<Net::Async::HTTP> when installed (loaded lazily on first call), otherwise a
1581 synchronous L<LWP::UserAgent> fallback under which the call blocks and several
1582 C<_f> calls run one after another rather than concurrently.
1583  
1584 For requests that need named arguments (tools, tool_choice,
1585 response_format, etc.) use L</chat_f>; C<simple_chat_f> delegates to it.
1586  
1587 =head2 chat_f
1588  
1589 my $response = await $engine->chat_f(
1590 messages => [ ... ],
1591 tools => [ $tool, ... ],
1592 tool_choice => { type => 'tool', name => 'extract' },
1593 response_format => { ... },
1594 temperature => 0.7,
1595 max_tokens => 512,
1596 # any other engine-specific extras pass straight through
1597 );
1598  
1599 Async I<single-turn> chat with named arguments. Returns a L<Future>
1600 resolving to a L<Langertha::Response>. The caller is responsible for
1601 acting on any C<tool_calls> the engine emits — C<chat_f> does not
1602 loop. For the multi-turn MCP tool-calling loop use
1603 L<Langertha::Role::Tools/chat_with_tools_f> instead.
1604  
1605 C<tools> in C<chat_f> can mix L<Langertha::Tool> objects,
1606 L<Langertha::ServerTool> objects and HashRefs of any provider shape (OpenAI,
1607 Anthropic, MCP, Gemini, provider built-ins). Before the request is built,
1608 each item is put into the engine's C<tool_wire_format> in place, keeping
1609 the caller's order (L<Langertha::Tool/request_list>, the same path
1610 L</chat_stream_realtime_f> takes): an object goes through its C<to>; a
1611 hash already in the wire's shape goes out verbatim, extras such as
1612 C<function.strict> and C<cache_control> included; a function-tool hash in
1613 another shape (for example an MCP tool with C<inputSchema>) is converted;
1614 built-ins and unknown typed items go out verbatim for the provider to
1615 judge. On Gemini all function declarations share one
1616 C<functionDeclarations> entry. The Responses envelope decides per item
1617 itself (L<Langertha::Role::ResponsesCompatible>). A
1618 C<Langertha::ServerTool> croaks on an engine that does not
1619 C<supports('server_tools')>.
1620  
1621 On a C<hermes> engine (L<Langertha::Role::HermesTools>) a C<chat_f> call is
1622 one turn of L<Langertha::Role::Tools/chat_with_tools_f>: the tools go into a
1623 leading system message built from C<hermes_tool_prompt>, in MCP shape, and
1624 the body carries no C<tools> key. Only function tools can go into the
1625 prompt: a built-in or other non-function item croaks there instead of going
1626 out verbatim. C<tool_choice> is never sent there: C<none> withholds the
1627 tools (no tool prompt; a warning says so), and any value other than
1628 C<auto> is ignored with a warning, as the prompt cannot force a tool
1629 (on L<Langertha::Engine::NousResearch> a forced named tool takes the
1630 C<json_schema> rewrite described below instead). On NousResearch, tools
1631 together with a C<json_schema> C<response_format> send both the schema prompt
1632 and the tool prompt.
1633 C<E<lt>tool_callE<gt>> blocks in the reply land on
1634 L<Langertha::Response/tool_calls> and are removed from C<content>; a block
1635 that carries no call (no valid JSON object with a C<name>) stays in
1636 C<content> as the model wrote it. When calls were lifted and the reply's
1637 C<finish_reason> was C<stop> or absent, it reads C<tool_calls>
1638 (L<Langertha::Response/raw> keeps the provider's value); any other value, such
1639 as C<length>, stays.
1640  
1641 A C<tool_choice> goes on the wire only as the engine's C<tool_choice_*>
1642 capabilities allow. Where the engine does not
1643 C<supports('tool_choice_E<lt>kindE<gt>')> for the choice's kind, C<auto> is
1644 dropped silently, C<none> withholds the request's tools instead (with a
1645 warning when there were tools to withhold), and a forced choice is dropped
1646 with a warning, the model then decides; a forced
1647 named tool that the C<json_schema> rewrite below can take is rewritten
1648 instead. Likewise C<parallel_tool_use> reaches the wire only where the engine
1649 C<supports('parallel_tool_use')>; a value you set elsewhere is dropped with a
1650 warning.
1651  
1652 These drop warnings (and the C<temperature> drops of
1653 L<Langertha::Role::Temperature>) name the line of your own call to C<chat_f>,
1654 C<simple_chat_f>, C<chat_request> and the like, not a line inside Langertha;
1655 code running inside an event-loop callback gets whatever location Carp finds.
1656 A value that comes from an engine attribute is the same on every request, so
1657 its drop warns once per engine instance; a value passed with the request warns
1658 on every request.
1659  
1660 A C<model> passed to C<chat_f> is no control: it replaces the model field of
1661 the request body, or, on engines that carry the model in the URL
1662 (L<Langertha::Engine::Gemini>, L<Langertha::Engine::AKI>), the model named in
1663 the URL, but every model-scoped decision is still taken for the engine's C<chat_model> — the
1664 capability picture L<Langertha::Role::Capabilities/supports> answers, the
1665 C<model_capability_exclusions> rules, the reasoning profile, the temperature
1666 gate for reasoning models, a per-model C<tool_wire_format> and reasoning
1667 prompt (L<Langertha::Engine::NousResearch>) and per-model body details such as the
1668 completion-length key and the default response size. When the override
1669 differs from C<chat_model> and one of those decisions that the request uses
1670 would come out differently for it, C<chat_f> warns and names the decisions;
1671 the request is sent unchanged. For a different model, use an engine whose
1672 C<chat_model> is that model.
1673  
1674 The canonical per-request controls (karr #46) are normalized like
1675 C<messages>/C<tools> instead of being spread as raw target-wire kwargs:
1676 C<temperature>, C<max_tokens>, C<response_format>, C<seed>,
1677 C<parallel_tool_use>, C<reasoning_effort>, C<thinking_budget>,
1678 C<prompt_cache>, C<prompt_cache_ttl> and C<prompt_cache_key>. Each engine's
1679 C<chat_request> places them on its own wire (Ollama C<options>, Gemini
1680 C<generationConfig>, Anthropic C<output_config>+C<thinking>, ...) via the same
1681 value objects the engine attributes use, so the same call is correct across
1682 engine families. A per-request control beats the configured engine attribute
1683 on a per-key basis. Any other key still passes straight through to the wire as
1684 before.
1685  
1686 When the caller asks for a forced named tool on an engine that cannot
1687 do native named-tool-forcing but supports C<json_schema>
1688 response_format (for example L<Langertha::Engine::Perplexity> and
1689 L<Langertha::Engine::NousResearch>), the
1690 request is automatically rewritten to use the JSON Schema path and the
1691 response is loose-parsed; the resulting L<Langertha::Response> exposes
1692 the parsed arguments via L<Langertha::Response/tool_call_args> with
1693 C<synthetic =E<gt> 1> on the synthesized tool_call entry.
1694  
1695 The rewrite takes the request's C<response_format>. Passing a forced named
1696 tool and a C<response_format> other than C<text> in the same C<chat_f> call
1697 therefore croaks: the two ask for different output, so pick one. When the
1698 C<response_format> only comes from the engine attribute, the forced tool wins
1699 for that request and a warning says so. A C<text> response_format is replaced
1700 silently.
1701  
1702 On a C<hermes> engine that takes C<response_format>
1703 (L<Langertha::Engine::NousResearch>), every C<json_schema> response format
1704 (the rewritten one, one passed to C<chat_f> or
1705 L</chat_stream_realtime_f>, or the engine's own) also goes into a leading
1706 system message built from L<Langertha::Role::HermesTools/hermes_schema_prompt>,
1707 for a backend that ignores C<response_format>.
1708  
1709 =head2 simple_chat_stream_f
1710  
1711 my ($content, $chunks) = $engine->simple_chat_stream_f(@messages)->get;
1712  
1713 Async streaming without a real-time callback. Convenience wrapper around
1714 L</simple_chat_stream_realtime_f> with C<undef> as the callback. Returns a
1715 L<Future> that resolves to C<($content, \@chunks, \%timing, $thinking)> — the
1716 same tuple as L</chat_stream_realtime_f>; the trailing elements are additive.
1717  
1718 =head2 aggregate_tool_calls
1719  
1720 my $tool_calls = $engine->aggregate_tool_calls( $chunks );
1721  
1722 Walks an ArrayRef of L<Langertha::Stream::Chunk> objects and returns
1723 the flat list of L<Langertha::ToolCall> objects collected from any
1724 chunks that carry C<tool_calls>, in stream order. Returns an empty ArrayRef if
1725 none of the chunks emitted tool calls.
1726  
1727 This is the streaming counterpart to L<Langertha::Response/tool_calls>: for a
1728 streamed response it returns the same calls, as equal L<Langertha::ToolCall>
1729 objects, that the non-streaming reply of that response carries. Each dialect's
1730 C<parse_stream_chunk> assembles its fragments (Chat-Completions
1731 C<delta.tool_calls> per C<index>, Anthropic C<input_json_delta> per content
1732 block) in per-stream state and puts every finished call on exactly one chunk,
1733 so this helper only collects and never sees a call twice. See
1734 L<Langertha::Stream::Chunk/tool_calls> for the chunk each dialect uses.
1735  
1736 =head2 aggregate_thinking
1737  
1738 my $thinking = $engine->aggregate_thinking( $chunks );
1739  
1740 Walks an ArrayRef of L<Langertha::Stream::Chunk> objects and concatenates the
1741 C<thinking> text of every chunk that carries one, in stream order — the way
1742 L</chat_stream_realtime_f> concatenates C<content>. Returns C<undef> when no
1743 chunk carried thinking, so the streamed result mirrors
1744 L<Langertha::Response/thinking> (also C<undef> when the engine surfaced none).
1745  
1746 This is the streaming counterpart to the native C<thinking> that
1747 L<Langertha::Response> exposes on the non-streaming path. Each dialect stream
1748 parser fills C<Stream::Chunk-E<gt>thinking> from its own delta spelling (see
1749 L<Langertha::Stream::Chunk/thinking>); this helper just reassembles the
1750 fragments.
1751  
1752 =head2 aggregate_usage
1753  
1754 my $usage = $engine->aggregate_usage( $chunks );
1755 my $counts = Langertha::Usage->from_hash($usage) if $usage;
1756  
1757 Walks an ArrayRef of L<Langertha::Stream::Chunk> objects and returns the
1758 C<usage> HashRef of the last chunk that carries one, or C<undef> when none
1759 did. Streamed usage is cumulative, so that is the whole stream's usage. Use it
1760 rather than reading the C<is_final> chunk: an OpenAI-compatible stream
1761 requested with C<stream_options =E<gt> { include_usage =E<gt> 1 }> reports
1762 its usage on a content-less chunk after the final one.
1763  
1764 =head2 simple_chat_stream_realtime_f
1765  
1766 # With async/await (recommended)
1767 use Future::AsyncAwait;
1768 async sub my_stream {
1769 my ($content, $chunks) = await $engine->simple_chat_stream_realtime_f(
1770 sub { print shift->content },
1771 @messages
1772 );
1773 return $content;
1774 }
1775  
1776 # Traditional Future style
1777 my $future = $engine->simple_chat_stream_realtime_f($callback, @messages);
1778 my ($content, $chunks) = $future->get;
1779  
1780 Async streaming with real-time callback. C<$callback> is called with each
1781 L<Langertha::Stream::Chunk> as it arrives from the server (each chunk may carry
1782 incremental C<thinking>). Returns a L<Future> that resolves to
1783 C<($content, \@chunks, \%timing, $thinking)>, the same tuple as
1784 L</chat_stream_realtime_f>; the trailing elements are additive, so callers
1785 destructuring only C<($content, \@chunks)> keep working.
1786  
1787 This is the recommended method for real-time streaming in async applications.
1788 Pass C<undef> as the callback (or use L</simple_chat_stream_f>) if you only
1789 need the final result.
1790  
1791 This is a thin wrapper around L</chat_stream_realtime_f>; existing callers
1792 keep working unchanged. For requests that need named arguments (tools,
1793 tool_choice, response_format, temperature, max_tokens, etc.) use
1794 L</chat_stream_realtime_f> directly.
1795  
1796 =head2 chat_stream_realtime_f
1797  
1798 my ($content, $chunks) = await $engine->chat_stream_realtime_f(
1799 messages => [ ... ],
1800 chunk_callback => sub { print shift->content },
1801 temperature => 0.7,
1802 max_tokens => 512,
1803 # any other engine-specific extras pass straight through
1804 );
1805  
1806 Async I<single-turn> streaming chat with named arguments. C<messages> is
1807 required (ArrayRef or a single message); C<chunk_callback> is called with each
1808 L<Langertha::Stream::Chunk> as it arrives from the server. The canonical
1809 per-request controls (karr #46) — C<temperature>, C<max_tokens>,
1810 C<response_format>, C<seed>, C<parallel_tool_use>, C<reasoning_effort>,
1811 C<thinking_budget>, C<prompt_cache>, C<prompt_cache_ttl>, C<prompt_cache_key> —
1812 are extracted and handed to L</chat_stream_request> under C<controls>, exactly
1813 as in L</chat_f>. C<tools> is shaped for the engine's C<tool_wire_format> item
1814 by item, exactly as in L</chat_f> (L<Langertha::Tool/request_list>):
1815 L<Langertha::Tool> objects are serialized, hashes already in the wire's shape
1816 (built-ins and extras included) pass through verbatim, other function-tool
1817 hashes (MCP C<inputSchema>, canonical C<input_schema>) are converted, and on
1818 Gemini all declarations are merged into one C<functionDeclarations> entry.
1819 C<tool_choice> is decided against the C<tool_choice_*> capabilities as in
1820 L</chat_f> (without the C<json_schema> rewrite); any engine-specific extras
1821 pass through. Tool calls the
1822 model streams are collected with L</aggregate_tool_calls>. On a C<hermes>
1823 engine the tools ride the system prompt and C<tool_choice> is handled as in
1824 L</chat_f>. The text inside the C<E<lt>tool_callE<gt>> blocks the model writes
1825 (L<Langertha::Role::HermesTools/hermes_call_tag>) is not streamed, even when a
1826 tag is split across chunks, and chunks that carried only such text are not
1827 delivered; the calls land as L<Langertha::ToolCall> objects on the final chunk,
1828 as L</chat_f> puts them on L<Langertha::Response/tool_calls>, and that chunk's
1829 C<finish_reason> reads C<tool_calls> where L</chat_f>'s would (over C<stop> or
1830 none). A block that carries no call is streamed as text where it stood, as
1831 L</chat_f> keeps it in C<content>, and a call tag inside C<E<lt>thinkE<gt>>
1832 text is no call. Markup that is unclosed when the stream ends is streamed as
1833 text and gives no call. A stream that ends without a final chunk gets a
1834 closing chunk for the text still held back and any calls. A per-request
1835 C<model> warns as in L</chat_f> when it would flip a model-scoped decision.
1836  
1837 Returns a L<Future> that resolves to C<($content, \@chunks, \%timing,
1838 $thinking)> where C<$content> is the full concatenated text, C<\@chunks> the
1839 collected L<Langertha::Stream::Chunk> objects, C<\%timing> carries
1840 C<ttft_seconds> and C<total_seconds>, and C<$thinking> is the aggregated
1841 chain-of-thought (C<undef> when the engine surfaced none), assembled from the
1842 per-chunk C<thinking> deltas by L</aggregate_thinking> so it matches the native
1843 L<Langertha::Response/thinking> of the non-streaming L</chat_f> on the same
1844 engine and prompt. The trailing element is additive: callers destructuring only
1845 the first three keep working.
1846  
1847 If C<chunk_callback> dies, or a stream line cannot be parsed, the returned
1848 future B<fails> with that exception on every HTTP backend, and no further
1849 chunk reaches C<chunk_callback>. How the rest of the transfer ends depends on
1850 the backend (L<Langertha::Role::AsyncHTTP>):
1851  
1852 =over
1853  
1854 =item * L<Net::Async::HTTP>: the exception never escapes the event loop. The
1855 request is cancelled on the next loop iteration (unless the response already
1856 ended within the same read), and the engine goes on serving requests. Like any
1857 cancelled L<Net::Async::HTTP> request this closes its connection; the client
1858 Langertha builds does not pipeline, so requests queued behind it on the same
1859 engine wait for a connection of their own and are unaffected.
1860  
1861 =item * the synchronous L<Langertha::Request::SyncHTTP> fallback: LWP stops
1862 reading at once.
1863  
1864 =item * an injected client whose futures have no C<loop> (or one without
1865 C<later>, from another event system): the rest of the body is read and
1866 discarded, and the future fails when the response ends. If the transfer then
1867 fails at the transport level, the future still fails with the original
1868 exception.
1869  
1870 =back
1871  
1872 Cancelling the returned future cancels the HTTP request.
1873  
1874 This is the streaming counterpart to L</chat_f>. Unlike L</chat_f> it does
1875 not apply the forced-tool fallback (rewriting a named C<tool_choice> into a
1876 C<response_format> on engines without C<tool_choice_named>); synthesizing a
1877 C<tool_calls> entry from the accumulated stream text is a separate follow-up
1878 concern.
1879  
1880 C<response_format> is honored on the streaming path only where the engine
1881 has a native wire form (Gemini C<responseJsonSchema>, Ollama C<format>,
1882 OpenAI-compatible C<response_format>). Anthropic-family engines have no
1883 native form and their synthesized-tool rewrite has no streaming lift, so
1884 they consume the key and croak — use L</chat_f> for structured output there.
1885  
1886 =head2 content_format
1887  
1888 my $fmt = $engine->content_format;
1889 # 'openai' | 'anthropic' | 'gemini' | 'responses' | 'ollama' | 'lmstudio'
1890  
1891 Wire format for multimodal content blocks. Controls how
1892 L<Langertha::Content> objects embedded in a message's C<content> arrayref
1893 are serialized during L</chat_messages>. Defaults to C<'openai'>; overridden
1894 by L<Langertha::Engine::AnthropicBase>, L<Langertha::Engine::Gemini>,
1895 L<Langertha::Role::ResponsesCompatible> (C<responses>: C<input_text> /
1896 C<input_image> parts, C<output_text> on assistant turns),
1897 L<Langertha::Engine::Ollama> (C<ollama>: text joined into a string content,
1898 images lifted into the message C<images> array) and
1899 L<Langertha::Engine::LMStudio> (C<lmstudio>).
1900  
1901 A message whose content is a plain string is passed through unchanged on
1902 every format; so is an arrayref without any L<Langertha::Content> object,
1903 except on C<gemini> (always turned into parts) and C<ollama> (text parts
1904 always joined into a string, C<image_url> parts lifted into C<images>).
1905  
1906 =head2 engine_capabilities
1907  
1908 my $caps = $engine->engine_capabilities;
1909 if ( $caps->{tool_choice_named} ) { ... }
1910  
1911 Returns a HashRef of capability flags so callers can avoid passing
1912 parameters the engine cannot honour.
1913  
1914 The base implementation reports only what L<Langertha::Role::Chat>
1915 itself provides (C<chat>). Every other capability-bearing role
1916 (L<Langertha::Role::Tools>, L<Langertha::Role::ResponseFormat>,
1917 L<Langertha::Role::Streaming>, L<Langertha::Role::Embedding>,
1918 L<Langertha::Role::Transcription>, L<Langertha::Role::ImageGeneration>,
1919 L<Langertha::Role::HermesTools>, L<Langertha::Role::Temperature>,
1920 L<Langertha::Role::Seed>, L<Langertha::Role::ContextSize>,
1921 L<Langertha::Role::ResponseSize>, L<Langertha::Role::SystemPrompt>,
1922 L<Langertha::Role::ParallelToolUse>) hangs its own contribution into
1923 this method via C<around engine_capabilities>. Engines override (also
1924 via C<around>) when the wire reality differs from the role inventory
1925 — for example to clear C<tool_choice_named> on providers that only
1926 accept string forms.
1927  
1928 Common keys produced by the bundled roles:
1929  
1930 =over
1931  
1932 =item * C<chat> — C<simple_chat>/C<simple_chat_f> work
1933  
1934 =item * C<streaming> — C<chat_stream_request> is wired up
1935  
1936 =item * C<tools_native> — engine accepts a C<tools> array on the wire
1937  
1938 =item * C<tools_hermes> — tools are injected via Hermes-style XML
1939 prompt rather than (or in addition to) the native API
1940  
1941 =item * C<tool_choice_auto> / C<tool_choice_any> / C<tool_choice_none> —
1942 which string-form C<tool_choice> values are accepted
1943  
1944 =item * C<tool_choice_named> — C<{type =E<gt> 'tool', name =E<gt> '...'}>
1945 forcing works (possibly translated internally — Gemini routes named
1946 tools through C<allowed_function_names>, for example)
1947  
1948 =item * C<response_format_json_object> — C<{type =E<gt> 'json_object'}>
1949  
1950 =item * C<response_format_json_schema> — JSON Schema structured output
1951  
1952 =item * C<embedding>, C<transcription>, C<image_generation> — auxiliary
1953 capabilities matching the corresponding roles
1954  
1955 =item * C<temperature>, C<seed>, C<context_size>, C<response_size>,
1956 C<system_prompt>, C<parallel_tool_use> — generation-parameter knobs
1957 the engine will honour
1958  
1959 =back
1960  
1961 Callers should treat the hash as advisory — a missing key means
1962 "unknown / unsupported", a true value means "the engine claims it
1963 will honour this".
1964  
1965 =head1 SEE ALSO
1966  
1967 =over
1968  
1969 =item * L<Langertha::Role::Langfuse> - Observability integration (composed by this role)
1970  
1971 =item * L<Langertha::Role::SystemPrompt> - System prompt injection
1972  
1973 =item * L<Langertha::Role::Streaming> - Stream parsing (SSE / NDJSON)
1974  
1975 =item * L<Langertha::Role::Tools> - Tool calling on top of chat
1976  
1977 =item * L<Langertha::Role::Models> - Model selection
1978  
1979 =item * L<Langertha::Stream> - Stream iterator
1980  
1981 =item * L<Langertha::Stream::Chunk> - Individual stream chunk
1982  
1983 =back
1984  
1985 =head1 SUPPORT
1986  
1987 =head2 Issues
1988  
1989 Please report bugs and feature requests on GitHub at
1990 L<https://github.com/Getty/langertha/issues>.
1991  
1992 =head2 IRC
1993  
1994 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
1995  
1996 =head1 CONTRIBUTING
1997  
1998 Contributions are welcome! Please fork the repository and submit a pull request.
1999  
2000 =head1 AUTHOR
2001  
2002 Torsten Raudssus <getty@cpan.org>
2003  
2004 =head1 COPYRIGHT AND LICENSE
2005  
2006 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
2007  
2008 This is free software; you can redistribute it and/or modify it under
2009 the same terms as the Perl 5 programming language system itself.
2010  
2011 =cut
« blib/lib/Langertha/CallResult.pm ↑ Summary blib/lib/Langertha/Manifest/Builder.pm »