blib/lib/Langertha/Engine/Gemini.pm

filter: Statementstmt 98.7% 324 / 328 Branchbran 86.3% 202 / 234 Conditioncond 59.0% 62 / 105 MC/DCmcdc 34.4% 21 / 61 Subroutinesub 97.8% 45 / 46 Podpod 40.0% 8 / 20 totaltotal 83.3% 662 / 794 CC 166 SCAR 28.2
CC
166
Cov
88%
chat_stream_request
37.1
chat_request
30.8
chat_response
24.1
CRAP 16.8
« blib/lib/Langertha/Engine/Ollama.pm ↑ Summary blib/lib/Langertha/Reasoning.pm »
1 package Langertha::Engine::Gemini;
2 # ABSTRACT: Google Gemini API
3 64 our $VERSION = '0.505';
4 64 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 64 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 64 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 64 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 64 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 64 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 64 ▶use Langertha::CachedContent;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 64 extends 'Langertha::Engine::Remote';
13  
14 64 with map { 'Langertha::Role::'.$_ } qw(
15 Models
16 Chat
17 Temperature
18 ReasoningEffort
19 ResponseSize
20 SystemPrompt
21 ResponseFormat
22 Streaming
23 Tools
24 CachedContent
25 ImageInput
26 ToolResultImages
27 ToolResultPDF
28 Embedding
29 );
30  
31 96 ▶sub _build_reasoning_wire_format { 'gemini' }
Subroutine _build_reasoning_wire_format: called CC=1 SCAR=0.0
32  
33 # Gemini splits its reasoning knob by model generation: Gemini 2.5-* takes
34 # an integer thinking_budget (no level vocabulary), Gemini 3 and Gemini 4
35 # take a thinkingLevel (minimal|low|medium|high, clamped to the model family's
36 # subset by Langertha::Reasoning; Gemini 4: low|medium|high). Exactly one
37 # native control is honored per model. Reflect that in the capability flags so callers can ask
38 # supports('thinking_budget') vs supports('reasoning_effort') and get the
39 # truth for the configured model.
40 #
41 # The same around also gates cached_content: explicit cachedContent
42 # resources are an "on" feature for Gemini 2.5 and Gemini 3. Older
43 # generations (1.x, 2.0) don't accept the cachedContents REST endpoints,
44 # so we drop the flag there. Gemini 4 lands in the else branch too (no
45 # thinking_budget, no explicit cache); its own row in
46 # model_capability_corrections records why (karr k381).
47 #
48 # parallel_tool_use is cleared on every model (karr k241): the v1beta
49 # ToolConfig is retrievalConfig | functionCallingConfig (mode +
50 # allowedFunctionNames) | includeServerSideToolInvocations, with no parallel
51 # knob (discovery doc revision 20260924). The model emits several
52 # functionCall parts on its own; there is nothing to switch off.
53 619 ▶around engine_capabilities => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
54 619 my ( $orig, $self, @rest ) = @_;
55 619 my $caps = $self->$orig(@rest);
56 619 delete $caps->{parallel_tool_use};
57 619 ▶ my $model = $self->can('chat_model') ? ( $self->chat_model // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
$self->can('chat_model') ? : 619 0 619
Condition50%1/2
$self->chat_model // ""
l!l
6190
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
58 619 ▶ if ( $model =~ /\Agemini-2\.5/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($model =~ /\Agemini-2\.5/) { } 200 419 619
elsif ($model =~ /\Agemini-3/) { } 250 169 419
59 200 $caps->{thinking_budget} = 1;
60 200 delete $caps->{reasoning_effort};
61 200 $caps->{cached_content} = 1;
62 }
63 elsif ( $model =~ /\Agemini-3/ ) {
64 # Gemini 3 keeps the default reasoning_effort cap; thinking_budget is
65 # not advertised.
66 250 delete $caps->{thinking_budget};
67 250 $caps->{cached_content} = 1;
68 }
69 else {
70 169 delete $caps->{thinking_budget};
71 169 delete $caps->{cached_content};
72 }
73 619 return $caps;
74 64 };
75  
76 # image_input (k266, ADR 0019 k266 Update): every Gemini chat model takes
77 # inline_data image parts (llm-advisor, docs only, 2026-09-25), so the family
78 # keeps the role-derived flag. Cleared: TTS / Live / native-audio /
79 # transcription and embedding ids, the lyria/imagen/veo generators (advisor
80 # table), plus the text-only Gemini 1.0 Pro and aqa. Gemma: Gemma 3 and 4 are
81 # multimodal and keep the flag; Gemma 1/2 and the text-only gemma-3-1b clear
82 # it (decision k266: restrict the exclusion to the text-only sizes rather than
83 # the whole family).
84 #
85 # tool_result_images / tool_result_pdf (ADR 0039, k380; k344 images, k361
86 # PDFs): an image or PDF in functionResponse.parts[].inlineData is documented
87 # for Gemini 3 and later only -- default-deny, then the Gemini 3+ row grants
88 # both. Sources: the Vertex function-calling page ("For Gemini 3 and later
89 # models, you can include multimodal content (images and PDFs) in
90 # functionResponse", docs.cloud.google.com/gemini-enterprise-agent-platform/
91 # models/tools/function-calling) and the AI Studio guide (ai.google.dev/
92 # gemini-api/docs/generate-content/function-calling: "available for Gemini 3
93 # series models", MIME list "Documents: application/pdf, text/plain" beside
94 # the image types; a text/plain blob is already decoded into the result
95 # string). Fetched 2026-09-29/30 and 2026-10-19; docs-derived, not
96 # live-verified. The row matches gemini-<major> with major >= 3 (gemini-3*,
97 # gemini-4-argon, a future gemini-10), never 1.x / 2.x; (?!\d) makes it read
98 # the whole major number (ADR 0023 k196). Images and PDFs on this wire also
99 # need image_input (Gemini reads documents through its vision;
100 # ToolResult->native_needs_vision, applied by Role::Capabilities).
101 #
102 # Gemini 4 (karr k381; ai.google.dev/gemini-api/docs/generate-content/
103 # latest-model and the Vertex gemini-4-argon guide, fetched 2026-10-19,
104 # docs-derived, not live-verified): explicit caching (cachedContents) "is not
105 # supported and returns an error" -- only implicit caching remains -- so
106 # cached_content is cleared; temperature is ignored ("If provided, sampling
107 # parameters are ignored", "Remove temperature, top_p, top_k and
108 # candidate_count"), so the flag is cleared and _temperature_kwargs keeps it off
109 # the wire. thinking_budget is never claimed there (layer 2 above). (?!\d):
110 # gemini-40 is an unknown id (ADR 0023 k196).
111 64 my $GEMINI4 = qr/\Agemini-4(?!\d)/;
112  
113 619 ▶sub model_capability_corrections {
Subroutine model_capability_corrections: called CC=1 SCAR=0.0
Pod undocumented
114 return (
115 619 qr/\A/ => { tool_result_images => 0, tool_result_pdf => 0 },
116 qr/\Agemini-(?:[3-9]|[1-9]\d+)(?!\d)/ => { tool_result_images => 1, tool_result_pdf => 1 },
117 $GEMINI4 => { cached_content => 0, temperature => 0 },
118 qr/(?:-tts|-live|native-audio|transcribe|embedding)/ => { image_input => 0 },
119 qr/\A(?:lyria|imagen|veo|aqa)/ => { image_input => 0 },
120 qr/\Agemini-(?:1\.0-)?pro(?:-\d+)?\z/ => { image_input => 0 },
121 qr/\Agemma-(?:[12](?!\d)|3-1b)/ => { image_input => 0 },
122 );
123 }
124  
125  
126 648 ▶sub default_response_size { 2048 }
Subroutine default_response_size: called CC=1 SCAR=0.0
Pod undocumented
127  
128 87 ▶sub content_format { 'gemini' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod undocumented
129  
130 64 has api_key => (
131 is => 'ro',
132 lazy_build => 1,
133 );
134 3 ▶sub _build_api_key {
Subroutine _build_api_key: called CC=2 SCAR=6.9
135 3 my ( $self ) = @_;
136 return $ENV{LANGERTHA_GEMINI_API_KEY}
137 3 ▶ || croak "".(ref $self)." requires LANGERTHA_GEMINI_API_KEY or api_key set";
Condition100%2/2
$ENV{'LANGERTHA_GEMINI_API_KEY'} || croak('' . ref($self) . ' requires LANGERTHA_GEMINI_API_KEY or api_key set')
l!l
12
MC/DC100%1/1
$ENV{'LANGERTHA_GEMINI_API_KEY'} || croak('' . ref($self) . ' requires LANGERTHA_GEMINI_API_KEY or api_key set')
$ENV{'LANGERTHA_GEMINI_API_KEY'}
Truth table100%2/2
A
A= $ENV{'LANGERTHA_GEMINI_API_KEY'}
Aresult
11
00
138 }
139  
140  
141 has '+url' => (
142 lazy => 1,
143 208 ▶ default => sub { 'https://generativelanguage.googleapis.com' },
Subroutine __ANON__: called CC=1 SCAR=0.0
144 64 );
145  
146 64 has cached_content => (
147 is => 'rw',
148 isa => 'Maybe[Langertha::CachedContent]',
149 predicate => 'has_cached_content',
150 clearer => 'clear_cached_content',
151 );
152  
153  
154 31 ▶sub default_model { 'gemini-3-flash-preview' }
Subroutine default_model: called CC=1 SCAR=0.0
Pod undocumented
155  
156 # --- endpoint + auth seam -------------------------------------------------
157 #
158 # Every request URL in this engine is assembled here, and the credential is
159 # placed by gemini_auth_query alone. A second consumer of the Gemini dialect
160 # (Vertex AI express or standard, a Gemini-native gateway) differs from the
161 # Developer API exclusively in base URL, API version, model-path prefix and
162 # auth scheme — never in the request envelope — so such a shim is a subclass
163 # that overrides here rather than a copy of chat_request (ADR 0016, karr #88).
164  
165 431 ▶sub gemini_api_version { 'v1beta' }
Subroutine gemini_api_version: called CC=1 SCAR=0.0
Pod documented
166  
167 430 ▶sub gemini_auth_query {
Subroutine gemini_auth_query: called CC=3 SCAR=11.0
Pod documented
168 430 my ( $self ) = @_;
169 430 my $key = $self->api_key;
170 428 ▶ return defined $key && length $key ? ( key => $key ) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $key && length $key ? : 417 11 428
Condition66%2/3
defined $key and length $key
!ll&&!rl&&r
110417
MC/DC50%1/2
defined $key and length $key
defined $key length $key
Truth table66%2/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
171 }
172  
173 441 ▶sub gemini_endpoint {
Subroutine gemini_endpoint: called CC=1 SCAR=0.0
Pod documented
174 441 my ( $self, $path ) = @_;
175 441 return $self->url . '/' . $self->gemini_api_version . '/' . $path;
176 }
177  
178 437 ▶sub gemini_url {
Subroutine gemini_url: called CC=3 SCAR=11.0
Pod documented
179 437 my ( $self, $path, @query ) = @_;
180 437 my $url = $self->gemini_endpoint($path);
181 437 my @params = ( $self->gemini_auth_query, @query );
182 435 ▶ return $url unless @params;
Branch: 1 branch
BranchTrueFalseTotal
unless @params 14 421 435
183 # Values are interpolated verbatim, exactly as the call sites did before:
184 # the API key and the fixed switches (alt=sse) are URL-safe, and encoding
185 # them here would change bytes on the wire for no gain.
186 421 my @pairs;
187 421 ▶ while ( my ( $name, $value ) = splice @params, 0, 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@params, 0, 2)) 524 421 945
188 524 push @pairs, $name . '=' . $value;
189 }
190 421 return $url . '?' . join( '&', @pairs );
191 }
192  
193 347 ▶sub gemini_model_url {
Subroutine gemini_model_url: called CC=1 SCAR=0.0
Pod documented
194 347 my ( $self, $model, $method, @query ) = @_;
195 347 return $self->gemini_url( 'models/' . $model . ':' . $method, @query );
196 }
197  
198  
199 # The REST contract names the field `cachedContent` and takes the resource
200 # name as a plain string (https://ai.google.dev/api/generate-content). A
201 # request naming a cache may not also set systemInstruction, tools or
202 # toolConfig: the server answers 400 "CachedContent can not be used with
203 # GenerateContent request setting system_instruction, tools or tool_config.
204 # Proposed fix: move those values to CachedContent from GenerateContent
205 # request." They come from the cache, so they are left out here, with one
206 # carp per engine (k327). Both JSON spellings of each field are dropped.
207 #
208 # A model without explicit caching (Gemini 4, karr k381) cannot take the
209 # reference at all: the server answers with an error. Leaving the reference
210 # out instead would send the request without the cached contents -- and
211 # without the systemInstruction / tools the cache owns -- and answer a
212 # different question, so it croaks. $model is the model the URL names (a
213 # per-request model included).
214 328 ▶sub _cached_content_reference {
Subroutine _cached_content_reference: called CC=12 SCAR=24.9
215 328 my ( $self, $body, $extra, $model ) = @_;
216 328 ▶ return unless $self->can('cached_content') && defined $self->cached_content;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can("cached_content") and defined $self->cached_content 304 24 328
Condition66%2/3
$self->can("cached_content") and defined $self->cached_content
!ll&&!rl&&r
030424
MC/DC50%1/2
$self->can("cached_content") and defined $self->cached_content
$self->can("cached_content") defined $self->cached_content
Truth table66%2/3
A and B
A= $self->can("cached_content")B= defined $self->cached_content
ABresult
0X0
100
111
217 24 my $cc = $self->cached_content;
218 croak "Langertha::Engine::Gemini: cached_content must be a Langertha::CachedContent with a 'name'"
219 24 ▶ unless ref($cc) && eval { $cc->isa('Langertha::CachedContent') && $cc->has_name };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cc and eval { do { $cc->isa("Langertha::CachedContent") and $cc->has_name } } 1 23 24
Condition66%4/6
ref $cc and eval { do { $cc->isa("Langertha::CachedContent") and $cc->has_name } }
!ll&&!rl&&r
0123
$cc->isa('Langertha::CachedContent') && $cc->has_name
!ll&&!rl&&r
0123
MC/DC50%1/2
ref $cc and eval { do { $cc->isa("Langertha::CachedContent") and $cc->has_name } }
ref $cc eval { do { $cc->isa("Langertha::CachedContent") and $cc->has_name } }
MC/DC50%1/2
$cc->isa('Langertha::CachedContent') && $cc->has_name
$cc->isa('Langertha::CachedContent') $cc->has_name
Truth table66%2/3
A and B
A= ref $ccB= eval { do { $cc->isa("Langertha::CachedContent") and $cc->has_name } }
ABresult
0X0
100
111
Truth table66%2/3
A && B
A= $cc->isa('Langertha::CachedContent')B= $cc->has_name
ABresult
0X0
100
111
220 23 $self->_assert_explicit_cache_model( $model,
221 'cached_content ' . $cc->name . ' is bound, but' );
222 19 $body->{cachedContent} = $cc->name;
223 19 my @dropped;
224 19 for my $field (
225 [ systemInstruction => 'system_instruction' ],
226 [ tools => 'tools' ],
227 [ toolConfig => 'tool_config' ],
228 ) {
229 57 my $sent = 0;
230 57 for my $key ( @$field ) {
231 114 ▶ $sent = 1 if defined delete $body->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined delete($$body{$key}) 8 106 114
232 114 ▶ $sent = 1 if defined delete $extra->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined delete($$extra{$key}) 10 104 114
233 }
234 57 ▶ push @dropped, $field->[0] if $sent;
Branch: 1 branch
BranchTrueFalseTotal
if $sent 18 39 57
235 }
236 19 ▶ $self->_langertha_carp( "".( ref $self ).": not sending " . join( ', ', @dropped )
Branch: 1 branch
BranchTrueFalseTotal
if @dropped 8 11 19
237 . " -- cached_content " . $cc->name . " is bound, and a request naming a cache takes"
238 . " systemInstruction, tools and toolConfig from the cache", 'cached_content_overrides' )
239 if @dropped;
240 19 return;
241 }
242  
243 # Croaks when $model (a bare id or a models/... resource name) has no explicit
244 # context caching: Gemini 4 "does not support" cachedContents "and returns an
245 # error" (karr k381, docs-derived). Only the known family croaks; an unknown id
246 # goes to the server, which has the last word.
247 37 ▶sub _assert_explicit_cache_model {
Subroutine _assert_explicit_cache_model: called CC=4 SCAR=14.5
248 37 my ( $self, $model, $what ) = @_;
249 37 ▶ return unless defined $model && !ref $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and not ref $model 0 37 37
Condition33%1/3
defined $model and not ref $model
!ll&&!rl&&r
0037
MC/DC0%0/2
defined $model and not ref $model
defined $model not ref $model
Truth table33%1/3
A and not(B)
A= defined $modelB= not ref $model
ABresult
0X0
100
111
250 37 ( my $id = $model ) =~ s{\A.*models/}{};
251 37 ▶ croak "".( ref $self ).": $what model '$id' has no explicit context caching"
Branch: 1 branch
BranchTrueFalseTotal
if $id =~ /$GEMINI4/ 6 31 37
252 . " (cachedContents); it caches long prompt prefixes implicitly"
253 if $id =~ $GEMINI4;
254 31 return;
255 }
256  
257 # The create body names its own model (Langertha::CachedContent model); the
258 # role does not look at model names, the engine does.
259 14 ▶before _create_cached_content_request => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
260 14 my ( $self, @args ) = @_;
261 1 ▶ my $model = @args == 1 && eval { $args[0]->isa('Langertha::CachedContent') }
Branch: 1 branch
BranchTrueFalseTotal
@args % 2 ? : 0 13 13
262 ? $args[0]->model
263 14 ▶ : @args % 2 ? undef : {@args}->{model};
Branch: 1 branch
BranchTrueFalseTotal
@args == 1 && eval { do { $args[0]->isa('Langertha::CachedContent') } } ? : 1 13 14
Condition66%2/3
@args == 1 and eval { do { $args[0]->isa("Langertha::CachedContent") } }
!ll&&!rl&&r
1301
MC/DC50%1/2
@args == 1 and eval { do { $args[0]->isa("Langertha::CachedContent") } }
@args == 1 eval { do { $args[0]->isa("Langertha::CachedContent") } }
Truth table66%2/3
A and B
A= @args == 1B= eval { do { $args[0]->isa("Langertha::CachedContent") } }
ABresult
0X0
100
111
264 14 $self->_assert_explicit_cache_model( $model, 'cannot create a cachedContent:' );
265 64 };
266  
267 # generationConfig.temperature, control beats attribute. Gemini 4 ignores
268 # temperature (and topP / topK / candidateCount) and the docs say to remove it
269 # (karr k381), so model_capability_corrections clears the flag there; then the
270 # field stays off the wire. The same drop + carp as the wire roles' gates
271 # (ADR 0025 k214/k220/k247 Updates): a caller-set value other than 1 carps,
272 # once per engine for the attribute, every time for a per-request control; 1
273 # is dropped quietly.
274 323 ▶sub _temperature_kwargs {
Subroutine _temperature_kwargs: called CC=10 SCAR=23.1
275 323 my ( $self, $controls ) = @_;
276 my $temp = exists $controls->{temperature} ? $controls->{temperature}
277 323 ▶ : $self->has_temperature ? $self->temperature
Branch: 2 branches
BranchTrueFalseTotal
exists $$controls{'temperature'} ? : 4 319 323
$self->has_temperature ? : 17 302 319
278 : undef;
279 323 ▶ return () unless defined $temp;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $temp 302 21 323
280 21 ▶ return ( temperature => $temp ) if $self->supports('temperature');
Branch: 1 branch
BranchTrueFalseTotal
if $self->supports("temperature") 13 8 21
281 my $once = exists $controls->{temperature} ? undef
282 8 ▶ : 'temperature=' . $temp . ' model=' . ( $self->chat_model // '' );
Branch: 1 branch
BranchTrueFalseTotal
exists $$controls{'temperature'} ? : 2 6 8
Condition50%1/2
$self->chat_model // ""
l!l
60
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
283 8 ▶ $self->_langertha_carp( "".( ref $self ).": dropping temperature=$temp -- model '"
Branch: 2 branches
BranchTrueFalseTotal
if $temp != 1 6 2 8
defined $once ? : 4 2 6
Condition50%1/2
$self->chat_model // ""
l!l
60
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
284 . ( $self->chat_model // '' )
285 . "' does not take a temperature (ignored server-side); "
286 . "unset temperature to silence this",
287 defined $once ? "$once unsupported" : undef )
288 if $temp != 1;
289 8 return ();
290 }
291  
292 234 ▶sub chat_request {
Subroutine chat_request: called CC=28 SCAR=34.3
Pod undocumented
293 234 my ( $self, $messages, %extra ) = @_;
294  
295 # Canonical per-request controls (chat_f, karr #46) beat the engine
296 # attributes on a per-key basis; the rest of %extra passes straight through.
297 234 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
71163
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
298 # No parallel knob on this wire (parallel_tool_use is cleared): a value the
299 # caller set is only dropped, with the shared carp (karr k241).
300 234 $self->_parallel_tool_calls_kwarg( \%extra, $controls );
301  
302 # Translate tool_choice (canonical / OpenAI / Anthropic shapes) into
303 # Gemini's toolConfig.functionCallingConfig form.
304 234 ▶ if ( exists $extra{tool_choice} && defined $extra{tool_choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $extra{"tool_choice"} and defined $extra{"tool_choice"}) 6 228 234
Condition66%2/3
exists $extra{"tool_choice"} and defined $extra{"tool_choice"}
!ll&&!rl&&r
22806
MC/DC50%1/2
exists $extra{"tool_choice"} and defined $extra{"tool_choice"}
exists $extra{"tool_choice"} defined $extra{"tool_choice"}
Truth table66%2/3
A and B
A= exists $extra{"tool_choice"}B= defined $extra{"tool_choice"}
ABresult
0X0
100
111
305 6 my $tc = Langertha::ToolChoice->from_hash( delete $extra{tool_choice} );
306 6 ▶ if ($tc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc) 6 0 6
307 6 my $cfg = $tc->to( $self->tool_wire_format );
308 6 ▶ $extra{toolConfig} = $cfg if $cfg;
Branch: 1 branch
BranchTrueFalseTotal
if $cfg 6 0 6
309 }
310 }
311  
312 # Convert messages to Gemini format
313 234 my @gemini_contents;
314 my $system_instruction;
315  
316 234 for my $message (@{$messages}) {
317 279 ▶ if ($message->{role} eq 'system') {
Branch: 2 branches
BranchTrueFalseTotal
if ($$message{'role'} eq 'system') { } 24 255 279
elsif ($$message{'parts'}) { } 36 219 255
318 # Gemini uses systemInstruction field for system messages
319 24 ▶ $system_instruction .= "\n\n" if $system_instruction;
Branch: 1 branch
BranchTrueFalseTotal
if $system_instruction 0 24 24
320 # Array content arrives as parts (Role::Chat, karr k269); keep its text.
321 $system_instruction .= $message->{parts}
322 2 ▶ ? join( "\n", map { $_->{text} // () } @{ $message->{parts} } )
Condition33%1/3
$$_{"text"} // ()
l!l&&r!l&&!r
200
MC/DC0%0/2
$$_{"text"} // ()
$$_{"text"} ()
Truth table33%1/3
A // B
A= $$_{"text"}B= ()
ABresult
1X1
011
000
323 24 ▶ : $message->{content};
Branch: 1 branch
BranchTrueFalseTotal
$$message{'parts'} ? : 1 23 24
324 } elsif ($message->{parts}) {
325 # Already in Gemini format (e.g. from format_tool_results)
326 36 push @gemini_contents, $message;
327 } else {
328 # Convert role: 'assistant' -> 'model' for Gemini
329 219 ▶ my $role = $message->{role} eq 'assistant' ? 'model' : $message->{role};
Branch: 1 branch
BranchTrueFalseTotal
$$message{'role'} eq 'assistant' ? : 1 218 219
330 push @gemini_contents, {
331 role => $role,
332 219 parts => [{ text => $message->{content} }],
333 };
334 }
335 }
336  
337 # Build the URL with model and API key. A per-request model names the model
338 # in the path, never in the body (karr k357).
339 234 my $model_name = $self->_url_model( \%extra );
340 234 my $url = $self->gemini_model_url( $model_name, 'generateContent' );
341  
342 234 my %request_body = (
343 contents => \@gemini_contents,
344 );
345  
346 # Add system instruction if present
347 234 ▶ if ($system_instruction) {
Branch: 1 branch
BranchTrueFalseTotal
if ($system_instruction) 24 210 234
348 $request_body{systemInstruction} = {
349 24 parts => [{ text => $system_instruction }],
350 };
351 }
352  
353 # Reference an explicit cachedContent resource by name when one was bound
354 # via $engine->cached_content (karr #22, k327).
355 234 $self->_cached_content_reference( \%request_body, \%extra, $model_name );
356  
357 # Add generation config
358 231 my %generation_config;
359 231 ▶ if ( exists $controls->{max_tokens} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $$controls{'max_tokens'}) { } 1 230 231
elsif ($self->get_response_size) { } 230 0 230
360 1 $generation_config{maxOutputTokens} = $controls->{max_tokens};
361 }
362 elsif ($self->get_response_size) {
363 230 $generation_config{maxOutputTokens} = $self->get_response_size;
364 }
365 231 %generation_config = ( %generation_config, $self->_temperature_kwargs($controls) );
366  
367 # Translate response_format -> Gemini's generationConfig.responseJsonSchema /
368 # responseMimeType. Accepts the OpenAI-shape response_format hash so that
369 # callers can hand the same payload to any engine. A per-request
370 # response_format (chat_f) beats the engine attribute, and is removed from
371 # the extras either way: generateContent has no top-level response_format
372 # field and would carry it as dead weight while the schema went missing.
373 # chat_f hands us an OpenAI-shaped json_schema.schema (already JSON Schema),
374 # so it goes into responseJsonSchema — the field that accepts JSON Schema
375 # directly. The older responseSchema is deprecated and wanted Google's own
376 # Schema proto dialect, not raw JSON Schema (ai.google.dev/api/generate-content,
377 # verified 2026-09-01 — karr k140). responseMimeType stays required.
378 my $rf = exists $controls->{response_format}
379 ? delete $controls->{response_format}
380 : exists $extra{response_format}
381 ? delete $extra{response_format}
382 231 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 1 230 231
exists $extra{'response_format'} ? : 4 226 230
$self->has_response_format ? : 1 225 226
383 231 ▶ if ( defined $rf ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rf) 6 225 231
384 6 ▶ my $type = ref($rf) eq 'HASH' ? ( $rf->{type} // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $rf eq 'HASH' ? : 6 0 6
Condition50%1/2
$$rf{"type"} // ""
l!l
60
MC/DC0%0/1
$$rf{"type"} // ""
$$rf{"type"}
Truth table50%1/2
A
A= $$rf{"type"}
Aresult
11
00
385 6 ▶ if ( $type eq 'json_object' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'json_object') { } 1 5 6
elsif ($type eq 'json_schema' and ref $$rf{'json_schema'} eq 'HASH' and ref $$rf{'json_schema'}{'schema'} eq 'HASH') { } 5 0 5
386 1 $generation_config{responseMimeType} = 'application/json';
387 }
388 ▶ elsif ( $type eq 'json_schema'
Condition33%2/6
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
!ll&&!rl&&r
005
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH"
!ll&&!rl&&r
005
MC/DC0%0/3
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
$type eq "json_schema" ref $$rf{"json_schema"} eq "HASH" ref $$rf{"json_schema"}{"schema"} eq "HASH"
Truth table25%1/4
A and B and C
A= $type eq "json_schema"B= ref $$rf{"json_schema"} eq "HASH"C= ref $$rf{"json_schema"}{"schema"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
389 && ref( $rf->{json_schema} ) eq 'HASH'
390 && ref( $rf->{json_schema}{schema} ) eq 'HASH' ) {
391 5 $generation_config{responseMimeType} = 'application/json';
392 5 $generation_config{responseJsonSchema} = $rf->{json_schema}{schema};
393 }
394 }
395  
396 # Merge reasoning effort / thinking_budget ->
397 # generationConfig.thinkingConfig.thinkingLevel (Gemini 3) or
398 # thinkingConfig.thinkingBudget (Gemini 2.5). Langertha::Reasoning owns
399 # the per-model placement; a per-request control (chat_f, karr #46) beats
400 # the engine attribute on a per-key basis.
401 231 my @reasoning = $self->reasoning_kwargs_for(%$controls);
402 213 ▶ %generation_config = ( %generation_config, @reasoning ) if @reasoning;
Branch: 1 branch
BranchTrueFalseTotal
if @reasoning 69 144 213
403  
404 213 ▶ $request_body{generationConfig} = \%generation_config if %generation_config;
Branch: 1 branch
BranchTrueFalseTotal
if %generation_config 213 0 213
405  
406 return $self->generate_http_request(
407 POST => $url,
408 39 ▶ sub { $self->chat_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
409 213 %request_body,
410 %extra,
411 );
412 }
413  
414 # --- embeddings (k309) -----------------------------------------------------
415 #
416 # A string goes to models/{m}:embedContent, an ArrayRef to
417 # models/{m}:batchEmbedContents with one EmbedContentRequest per input
418 # (ai.google.dev/api/embeddings, fetched 2026-09-25). taskType / title /
419 # outputDimensionality belong in embedContentConfig; the top-level spellings
420 # are deprecated, so the snake_case extras are placed there. Everything else
421 # in %extra goes into each EmbedContentRequest verbatim (ADR 0004).
422  
423 7 ▶sub default_embedding_model { 'gemini-embedding-001' }
Subroutine default_embedding_model: called CC=1 SCAR=0.0
Pod undocumented
424  
425 64 my %EMBED_CONFIG_KEY = (
426 task_type => 'taskType',
427 output_dimensionality => 'outputDimensionality',
428 title => 'title',
429 );
430  
431 20 ▶sub embedding_request {
Subroutine embedding_request: called CC=6 SCAR=17.9
Pod documented
432 20 my ( $self, $input, %extra ) = @_;
433 20 my $model = $self->embedding_model;
434  
435 my %config = (
436 defined $self->embedding_dimensions ? ( outputDimensionality => $self->embedding_dimensions ) : (),
437 20 ▶ %{ delete $extra{embedContentConfig} // {} },
Branch: 1 branch
BranchTrueFalseTotal
defined $self->embedding_dimensions ? : 6 14 20
Condition100%2/2
delete $extra{"embedContentConfig"} // {}
l!l
218
MC/DC100%1/1
delete $extra{"embedContentConfig"} // {}
delete $extra{"embedContentConfig"}
Truth table100%2/2
A
A= delete $extra{"embedContentConfig"}
Aresult
11
00
438 );
439 20 for my $key ( sort keys %EMBED_CONFIG_KEY ) {
440 60 ▶ $config{ $EMBED_CONFIG_KEY{$key} } = delete $extra{$key} if exists $extra{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $extra{$key} 7 53 60
441 }
442 27 ▶ my $embed_request = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
443 27 my ( $text ) = @_;
444 return {
445 27 ▶ model => 'models/' . $model,
Branch: 1 branch
BranchTrueFalseTotal
%config ? : 11 16 27
446 content => { parts => [ { text => $text } ] },
447 %config ? ( embedContentConfig => {%config} ) : (),
448 %extra,
449 };
450 20 };
451  
452 20 ▶ if ( ref $input eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input eq "ARRAY") 6 14 20
453 return $self->generate_http_request(
454 POST => $self->gemini_model_url( $model, 'batchEmbedContents' ),
455 4 ▶ sub { $self->embedding_response( shift, $input ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
456 6 requests => [ map { $embed_request->($_) } @{$input} ],
457 );
458 }
459 return $self->generate_http_request(
460 POST => $self->gemini_model_url( $model, 'embedContent' ),
461 5 ▶ sub { $self->embedding_response( shift, $input ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
462 14 %{ $embed_request->($input) },
463 );
464 }
465  
466  
467 9 ▶sub embedding_response {
Subroutine embedding_response: called CC=15 SCAR=27.4
Pod documented
468 9 my ( $self, $response, $input ) = @_;
469 9 my $data = $self->parse_response($response);
470 9 my $batch = ref $input eq 'ARRAY';
471 my @embeddings = ref $data ne 'HASH' ? ()
472 4 ▶ : $batch ? ( ref $data->{embeddings} eq 'ARRAY' ? @{ $data->{embeddings} } : () )
Branch: 1 branch
BranchTrueFalseTotal
defined $$data{'embedding'} ? : 4 1 5
473 9 ▶ : ( defined $data->{embedding} ? $data->{embedding} : () );
Branch: 3 branches
BranchTrueFalseTotal
ref $data ne 'HASH' ? : 0 9 9
$batch ? : 4 5 9
ref $$data{'embeddings'} eq 'ARRAY' ? : 4 0 4
474 9 ▶ my @vectors = map { ref $_ eq 'HASH' ? $_->{values} : undef } @embeddings;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 12 0 12
475 # No vector is no result: never hand back undef as if it were one (k290).
476 9 ▶ if ( !@vectors || grep { ref $_ ne 'ARRAY' || !@{$_} } @vectors ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @vectors or grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors) 3 6 9
Condition83%5/6
not @vectors or grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
l!l&&r!l&&!r
126
ref $_ ne 'ARRAY' || !@{$_;}
l!l&&r!l&&!r
2010
MC/DC100%2/2
not @vectors or grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
not @vectors grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
MC/DC50%1/2
ref $_ ne 'ARRAY' || !@{$_;}
ref $_ ne 'ARRAY' !@{$_;}
Truth table100%3/3
not(A) or B
A= not @vectorsB= grep {ref $_ ne "ARRAY" or not @{$_;};} @vectors
ABresult
1X1
011
000
Truth table66%2/3
A || not(B)
A= ref $_ ne 'ARRAY'B= !@{$_;}
ABresult
1X1
011
000
477 my $err = ref $data eq 'HASH' && $data->{error}
478 ? ( ref $data->{error} eq 'HASH' ? $data->{error}{message} : $data->{error} )
479 3 ▶ : undef;
Branch: 2 branches
BranchTrueFalseTotal
ref $data eq 'HASH' && $$data{'error'} ? : 1 2 3
ref $$data{'error'} eq 'HASH' ? : 1 0 1
Condition66%2/3
ref $data eq "HASH" and $$data{"error"}
!ll&&!rl&&r
021
MC/DC50%1/2
ref $data eq "HASH" and $$data{"error"}
ref $data eq "HASH" $$data{"error"}
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= $$data{"error"}
ABresult
0X0
100
111
480 3 ▶ croak "".(ref $self)." embedding response contained no vector"
Branch: 1 branch
BranchTrueFalseTotal
defined $err ? : 1 2 3
481 . ( defined $err ? " (error: $err)" : '' );
482 }
483 6 ▶ return $vectors[0] unless $batch;
Branch: 1 branch
BranchTrueFalseTotal
unless $batch 3 3 6
484 croak "".(ref $self)." embedding response returned ".scalar(@vectors)
485 1 ." vectors for ".scalar(@{$input})." inputs"
486 3 ▶ unless @vectors == @{$input};
Branch: 1 branch
BranchTrueFalseTotal
unless @vectors == @{$input;} 1 2 3
487 2 return \@vectors;
488 }
489  
490  
491 387 ▶sub update_request {
Subroutine update_request: called CC=1 SCAR=0.0
Pod undocumented
492 387 my ( $self, $request ) = @_;
493 387 $request->header('content-type', 'application/json');
494 }
495  
496 93 ▶sub chat_response {
Subroutine chat_response: called CC=24 SCAR=31.8
497 93 my ( $self, $response ) = @_;
498 93 my $data = $self->parse_response($response);
499  
500 # Gemini response format: candidates[0].content.parts[].text
501 88 ▶ my $candidates = $data->{candidates} || [];
Condition100%2/2
$$data{'candidates'} || []
l!l
7414
MC/DC100%1/1
$$data{'candidates'} || []
$$data{'candidates'}
Truth table100%2/2
A
A= $$data{'candidates'}
Aresult
11
00
502 88 my $text = '';
503 88 my $finish_reason;
504 my $thinking;
505 88 ▶ if (@$candidates) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$candidates) { } 73 15 88
506 73 my $candidate = $candidates->[0];
507 73 ▶ my $content = $candidate->{content} || {};
Condition50%1/2
$$candidate{'content'} || {}
l!l
730
MC/DC0%0/1
$$candidate{'content'} || {}
$$candidate{'content'}
Truth table50%1/2
A
A= $$candidate{'content'}
Aresult
11
00
508 73 ▶ my $parts = $content->{parts} || [];
Condition50%1/2
$$content{'parts'} || []
l!l
730
MC/DC0%0/1
$$content{'parts'} || []
$$content{'parts'}
Truth table50%1/2
A
A= $$content{'parts'}
Aresult
11
00
509 73 my @text_parts;
510 my @thought_parts;
511 73 for my $part (@$parts) {
512 85 ▶ next unless exists $part->{text};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$part{"text"} 14 71 85
513 71 ▶ if ($part->{thought}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$part{'thought'}) { } 7 64 71
514 7 push @thought_parts, $part->{text};
515 } else {
516 64 push @text_parts, $part->{text};
517 }
518 }
519 73 $text = join('', @text_parts);
520 73 ▶ $thinking = join("\n", @thought_parts) if @thought_parts;
Branch: 1 branch
BranchTrueFalseTotal
if @thought_parts 7 66 73
521 73 $finish_reason = $candidate->{finishReason};
522 }
523 else {
524 # No candidate: a blocked prompt says why in promptFeedback.blockReason.
525 # A block is an answer, so it is reported as finish_reason, verbatim like
526 # a candidate's finishReason (SAFETY, PROHIBITED_CONTENT, ...). Anything
527 # else without a candidate is no answer and croaks. -- karr k301
528 15 $finish_reason = $self->_gemini_block_reason($data);
529 15 ▶ unless ( defined $finish_reason ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $finish_reason) 6 9 15
530 6 my $error = $self->_body_error_text( $data->{error} );
531 6 ▶ croak "".(ref $self)." response carried an error: $error" if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 5 1 6
532 1 croak "".(ref $self)." response contained no candidates";
533 }
534 }
535  
536 # Normalize Gemini usage metadata. cachedContentTokenCount is surfaced
537 # when present so callers can monitor cache-hit rate (karr #22, 22e).
538 # See https://ai.google.dev/api/generate-content (usageMetadata).
539 # Langertha::Usage->from_hash reads both spellings (ADR 0018 tier 1), but the
540 # rename stays: Usage's %{} overload serves this hash verbatim, so
541 # $response->usage->{prompt_tokens} / {cached_content_token_count} are
542 # public back-compat keys (Langertha::CachedContent POD, karr k197).
543 # The snake_case keys take OpenAI's meaning: thoughtsTokenCount (billed as
544 # output, not part of candidatesTokenCount) is counted in completion_tokens
545 # and shown under completion_tokens_details.reasoning_tokens; the tool-use
546 # prompt (toolUsePromptTokenCount) in prompt_tokens (k299).
547 82 my $usage;
548 82 ▶ if (my $um = $data->{usageMetadata}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $um = $$data{"usageMetadata"}) 18 64 82
549 18 my $thoughts = $um->{thoughtsTokenCount};
550 my ( $prompt, $tool_prompt, $candidates ) =
551 18 @{$um}{qw( promptTokenCount toolUsePromptTokenCount candidatesTokenCount )};
552 $usage = {
553 prompt_tokens => defined $tool_prompt ? ( $prompt // 0 ) + $tool_prompt : $prompt,
554 completion_tokens => defined $thoughts ? ( $candidates // 0 ) + $thoughts : $candidates,
555 total_tokens => $um->{totalTokenCount},
556 18 ▶ };
Branch: 2 branches
BranchTrueFalseTotal
defined $tool_prompt ? : 1 17 18
defined $thoughts ? : 2 16 18
Condition50%2/4
$prompt // 0
l!l
10
$candidates // 0
l!l
20
MC/DC0%0/1
$prompt // 0
$prompt
MC/DC0%0/1
$candidates // 0
$candidates
Truth table50%1/2
A
A= $prompt
Aresult
11
00
Truth table50%1/2
A
A= $candidates
Aresult
11
00
557 18 ▶ $usage->{completion_tokens_details} = { reasoning_tokens => $thoughts } if defined $thoughts;
Branch: 1 branch
BranchTrueFalseTotal
if defined $thoughts 2 16 18
558 18 ▶ if ( defined $um->{cachedContentTokenCount} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$um{"cachedContentTokenCount"}) 2 16 18
559 2 $usage->{cached_content_token_count} = $um->{cachedContentTokenCount};
560 }
561 }
562  
563 82 my @tcs = Langertha::ToolCall->extract( $self->tool_wire_format, $data );
564 return Langertha::Response->new(
565 content => $text,
566 raw => $data,
567 $data->{responseId} ? ( id => $data->{responseId} ) : (),
568 82 ▶ $data->{modelVersion} ? ( model => $data->{modelVersion} ) : (),
Branch: 6 branches
BranchTrueFalseTotal
$$data{'responseId'} ? : 21 61 82
$$data{'modelVersion'} ? : 37 45 82
defined $finish_reason ? : 78 4 82
$usage ? : 18 64 82
defined $thinking ? : 7 75 82
@tcs ? : 13 69 82
569 defined $finish_reason ? ( finish_reason => $finish_reason ) : (),
570 $usage ? ( usage => $usage ) : (),
571 defined $thinking ? ( thinking => $thinking ) : (),
572 @tcs ? ( tool_calls => [ @tcs ] ) : (),
573 );
574 }
575  
576 # promptFeedback.blockReason of a candidate-less answer (a blocked prompt),
577 # undef when there is none. -- karr k301, k311
578 25 ▶sub _gemini_block_reason {
Subroutine _gemini_block_reason: called CC=5 SCAR=16.2
579 25 my ( $self, $data ) = @_;
580 25 ▶ my $feedback = ref $data->{promptFeedback} eq 'HASH' ? $data->{promptFeedback} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $$data{'promptFeedback'} eq 'HASH' ? : 17 8 25
581 25 my $reason = $feedback->{blockReason};
582 25 ▶ return defined $reason && !ref $reason && length $reason ? $reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $reason && !ref($reason) && length $reason ? : 17 8 25
Condition66%4/6
defined $reason and not ref $reason and length $reason
!ll&&!rl&&r
8017
defined $reason and not ref $reason
!ll&&!rl&&r
8017
MC/DC33%1/3
defined $reason and not ref $reason and length $reason
defined $reason not ref $reason length $reason
Truth table50%2/4
A and not(B) and C
A= defined $reasonB= not ref $reasonC= length $reason
ABCresult
0XX0
10X0
1100
1111
583 }
584  
585 # The tool loops croak on a blocked prompt (Role::Tools, karr k339): the
586 # candidate-less answer chat_response reports as finish_reason.
587 30 ▶sub _tool_loop_block_reason {
Subroutine _tool_loop_block_reason: called CC=4 SCAR=14.0
588 30 my ( $self, $response ) = @_;
589 30 my $data = $response->raw;
590 30 ▶ return undef unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 30 30
591 30 ▶ return undef if ref $data->{candidates} eq 'ARRAY' && @{ $data->{candidates} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $$data{"candidates"} eq "ARRAY" and @{$$data{"candidates"};} 23 7 30
Condition66%2/3
ref $$data{"candidates"} eq "ARRAY" and @{$$data{"candidates"};}
!ll&&!rl&&r
7023
MC/DC50%1/2
ref $$data{"candidates"} eq "ARRAY" and @{$$data{"candidates"};}
ref $$data{"candidates"} eq "ARRAY" @{$$data{"candidates"};}
Truth table66%2/3
A and B
A= ref $$data{"candidates"} eq "ARRAY"B= @{$$data{"candidates"};}
ABresult
0X0
100
111
592 7 return $self->_gemini_block_reason($data);
593 }
594  
595  
596 4 ▶sub stream_format { 'sse' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod undocumented
597  
598 94 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=28 SCAR=36.1
Pod undocumented
599 94 my ( $self, $messages, %extra ) = @_;
600  
601 # Canonical per-request controls (chat_f, karr #46) beat the engine
602 # attributes on a per-key basis; the rest of %extra passes straight through.
603 94 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
6232
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
604 # No parallel knob on this wire (parallel_tool_use is cleared): a value the
605 # caller set is only dropped, with the shared carp (karr k241).
606 94 $self->_parallel_tool_calls_kwarg( \%extra, $controls );
607  
608 # Same tool_choice translation as chat_request.
609 94 ▶ if ( exists $extra{tool_choice} && defined $extra{tool_choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $extra{"tool_choice"} and defined $extra{"tool_choice"}) 5 89 94
Condition66%2/3
exists $extra{"tool_choice"} and defined $extra{"tool_choice"}
!ll&&!rl&&r
8905
MC/DC50%1/2
exists $extra{"tool_choice"} and defined $extra{"tool_choice"}
exists $extra{"tool_choice"} defined $extra{"tool_choice"}
Truth table66%2/3
A and B
A= exists $extra{"tool_choice"}B= defined $extra{"tool_choice"}
ABresult
0X0
100
111
610 5 my $tc = Langertha::ToolChoice->from_hash( delete $extra{tool_choice} );
611 5 ▶ if ($tc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc) 5 0 5
612 5 my $cfg = $tc->to( $self->tool_wire_format );
613 5 ▶ $extra{toolConfig} = $cfg if $cfg;
Branch: 1 branch
BranchTrueFalseTotal
if $cfg 5 0 5
614 }
615 }
616  
617 # Convert messages to Gemini format (same as non-streaming)
618 94 my @gemini_contents;
619 my $system_instruction;
620  
621 94 for my $message (@{$messages}) {
622 104 ▶ if ($message->{role} eq 'system') {
Branch: 2 branches
BranchTrueFalseTotal
if ($$message{'role'} eq 'system') { } 9 95 104
elsif ($$message{'parts'}) { } 7 88 95
623 9 ▶ $system_instruction .= "\n\n" if $system_instruction;
Branch: 1 branch
BranchTrueFalseTotal
if $system_instruction 0 9 9
624 # Array content arrives as parts (Role::Chat, karr k269); keep its text.
625 $system_instruction .= $message->{parts}
626 0 ▶ ? join( "\n", map { $_->{text} // () } @{ $message->{parts} } )
Condition0%0/3
$$_{"text"} // ()
l!l&&r!l&&!r
000
MC/DC0%0/2
$$_{"text"} // ()
$$_{"text"} ()
Truth table0%0/3
A // B
A= $$_{"text"}B= ()
ABresult
1X1
011
000
627 9 ▶ : $message->{content};
Branch: 1 branch
BranchTrueFalseTotal
$$message{'parts'} ? : 0 9 9
628 } elsif ($message->{parts}) {
629 # Already in Gemini format (e.g. from format_tool_results)
630 7 push @gemini_contents, $message;
631 } else {
632 88 ▶ my $role = $message->{role} eq 'assistant' ? 'model' : $message->{role};
Branch: 1 branch
BranchTrueFalseTotal
$$message{'role'} eq 'assistant' ? : 1 87 88
633 push @gemini_contents, {
634 role => $role,
635 88 parts => [{ text => $message->{content} }],
636 };
637 }
638 }
639  
640 # Build the URL for streaming endpoint (a per-request model as in chat_request)
641 94 my $model_name = $self->_url_model( \%extra );
642 94 my $url = $self->gemini_model_url( $model_name, 'streamGenerateContent', alt => 'sse' );
643  
644 94 my %request_body = (
645 contents => \@gemini_contents,
646 );
647  
648 94 ▶ if ($system_instruction) {
Branch: 1 branch
BranchTrueFalseTotal
if ($system_instruction) 9 85 94
649 $request_body{systemInstruction} = {
650 9 parts => [{ text => $system_instruction }],
651 };
652 }
653  
654 # Reference an explicit cachedContent resource by name when one was bound
655 # via $engine->cached_content (karr #22, k327). Same wire as chat_request.
656 94 $self->_cached_content_reference( \%request_body, \%extra, $model_name );
657  
658 92 my %generation_config;
659 92 ▶ if ( exists $controls->{max_tokens} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $$controls{'max_tokens'}) { } 0 92 92
elsif ($self->get_response_size) { } 92 0 92
660 0 $generation_config{maxOutputTokens} = $controls->{max_tokens};
661 }
662 elsif ($self->get_response_size) {
663 92 $generation_config{maxOutputTokens} = $self->get_response_size;
664 }
665 92 %generation_config = ( %generation_config, $self->_temperature_kwargs($controls) );
666  
667 # Translate response_format -> Gemini's generationConfig.responseJsonSchema /
668 # responseMimeType. Same wire as chat_request: a per-request
669 # response_format (chat_stream_realtime_f) beats the engine attribute,
670 # and is removed from the extras either way — generateContent has no
671 # top-level response_format field and would carry it as dead weight
672 # while the schema went missing. responseJsonSchema is the current field that
673 # accepts raw JSON Schema; the deprecated responseSchema wanted Google's Schema
674 # proto dialect instead (see chat_request — karr k140).
675 my $rf = exists $controls->{response_format}
676 ? delete $controls->{response_format}
677 : exists $extra{response_format}
678 ? delete $extra{response_format}
679 92 ▶ : $self->has_response_format ? $self->response_format : undef;
Branch: 3 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 0 92 92
exists $extra{'response_format'} ? : 3 89 92
$self->has_response_format ? : 1 88 89
680 92 ▶ if ( defined $rf ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rf) 4 88 92
681 4 ▶ my $type = ref($rf) eq 'HASH' ? ( $rf->{type} // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $rf eq 'HASH' ? : 4 0 4
Condition50%1/2
$$rf{"type"} // ""
l!l
40
MC/DC0%0/1
$$rf{"type"} // ""
$$rf{"type"}
Truth table50%1/2
A
A= $$rf{"type"}
Aresult
11
00
682 4 ▶ if ( $type eq 'json_object' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'json_object') { } 1 3 4
elsif ($type eq 'json_schema' and ref $$rf{'json_schema'} eq 'HASH' and ref $$rf{'json_schema'}{'schema'} eq 'HASH') { } 3 0 3
683 1 $generation_config{responseMimeType} = 'application/json';
684 }
685 ▶ elsif ( $type eq 'json_schema'
Condition33%2/6
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
!ll&&!rl&&r
003
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH"
!ll&&!rl&&r
003
MC/DC0%0/3
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH" and ref $$rf{"json_schema"}{"schema"} eq "HASH"
$type eq "json_schema" ref $$rf{"json_schema"} eq "HASH" ref $$rf{"json_schema"}{"schema"} eq "HASH"
Truth table25%1/4
A and B and C
A= $type eq "json_schema"B= ref $$rf{"json_schema"} eq "HASH"C= ref $$rf{"json_schema"}{"schema"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
686 && ref( $rf->{json_schema} ) eq 'HASH'
687 && ref( $rf->{json_schema}{schema} ) eq 'HASH' ) {
688 3 $generation_config{responseMimeType} = 'application/json';
689 3 $generation_config{responseJsonSchema} = $rf->{json_schema}{schema};
690 }
691 }
692  
693 92 my @reasoning = $self->reasoning_kwargs_for(%$controls);
694 77 ▶ %generation_config = ( %generation_config, @reasoning ) if @reasoning;
Branch: 1 branch
BranchTrueFalseTotal
if @reasoning 32 45 77
695  
696 77 ▶ $request_body{generationConfig} = \%generation_config if %generation_config;
Branch: 1 branch
BranchTrueFalseTotal
if %generation_config 77 0 77
697  
698 return $self->generate_http_request(
699 POST => $url,
700 0 ▶ sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
701 77 %request_body,
702 %extra,
703 );
704 }
705  
706 29 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=18 SCAR=29.0
Pod undocumented
707 29 my ( $self, $data, $event ) = @_;
708  
709 29 require Langertha::Stream::Chunk;
710  
711 # An error inside an open stream arrives as a chunk with a top-level `error`
712 # object. Skipping it ended the stream as a short, silent success; the croak
713 # fails the stream, as the OpenAI-compatible parser does. -- karr k317
714 29 ▶ if ( ref $data eq 'HASH' && defined $data->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH" and defined $$data{"error"}) 2 27 29
Condition66%2/3
ref $data eq "HASH" and defined $$data{"error"}
!ll&&!rl&&r
0272
MC/DC50%1/2
ref $data eq "HASH" and defined $$data{"error"}
ref $data eq "HASH" defined $$data{"error"}
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= defined $$data{"error"}
ABresult
0X0
100
111
715 2 croak "".(ref $self)." stream carried an error: ".$self->_body_error_text( $data->{error} );
716 }
717  
718 # Gemini streaming format is similar to non-streaming
719 27 ▶ my $candidates = $data->{candidates} || [];
Condition100%2/2
$$data{'candidates'} || []
l!l
252
MC/DC100%1/1
$$data{'candidates'} || []
$$data{'candidates'}
Truth table100%2/2
A
A= $$data{'candidates'}
Aresult
11
00
720 27 ▶ unless (@$candidates) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$candidates) 3 24 27
721 # A blocked prompt streams a chunk with promptFeedback.blockReason and no
722 # candidate. Skipping it ended the stream without a finish_reason; it is
723 # the final chunk, reported like chat_response does (k301). -- karr k311
724 3 my $block_reason = $self->_gemini_block_reason($data);
725 3 ▶ return undef unless defined $block_reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $block_reason 2 1 3
726 return Langertha::Stream::Chunk->new(
727 content => '',
728 raw => $data,
729 is_final => 1,
730 finish_reason => $block_reason,
731 1 ▶ $data->{usageMetadata} ? ( usage => $data->{usageMetadata} ) : (),
Branch: 1 branch
BranchTrueFalseTotal
$$data{'usageMetadata'} ? : 1 0 1
732 );
733 }
734  
735 24 my $candidate = $candidates->[0];
736 24 ▶ my $content = $candidate->{content} || {};
Condition50%1/2
$$candidate{'content'} || {}
l!l
240
MC/DC0%0/1
$$candidate{'content'} || {}
$$candidate{'content'}
Truth table50%1/2
A
A= $$candidate{'content'}
Aresult
11
00
737 24 ▶ my $parts = $content->{parts} || [];
Condition50%1/2
$$content{'parts'} || []
l!l
240
MC/DC0%0/1
$$content{'parts'} || []
$$content{'parts'}
Truth table50%1/2
A
A= $$content{'parts'}
Aresult
11
00
738  
739 # Same shape as chat_response: walk every part, not just parts[0]. A chunk can
740 # carry a thought part ahead of (or interleaved with) the answer part; reading
741 # only parts[0] leaked a thought summary into content and dropped the real
742 # answer that followed it. A part is a thought summary when `thought` is true;
743 # such parts feed the chunk's thinking, the rest feed content. -- karr k129
744 24 my @text_parts;
745 my @thought_parts;
746 24 for my $part (@$parts) {
747 31 ▶ next unless exists $part->{text};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$part{"text"} 2 29 31
748 29 ▶ if ($part->{thought}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$part{'thought'}) { } 10 19 29
749 10 push @thought_parts, $part->{text};
750 } else {
751 19 push @text_parts, $part->{text};
752 }
753 }
754 24 my $text = join('', @text_parts);
755 24 ▶ my $thinking = @thought_parts ? join('', @thought_parts) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@thought_parts ? : 9 15 24
756  
757 24 my $finish_reason = $candidate->{finishReason};
758 24 ▶ my $is_final = defined $finish_reason && $finish_reason ne '';
Condition66%2/3
defined $finish_reason && $finish_reason ne ''
!ll&&!rl&&r
1707
MC/DC50%1/2
defined $finish_reason && $finish_reason ne ''
defined $finish_reason $finish_reason ne ''
Truth table66%2/3
A && B
A= defined $finish_reasonB= $finish_reason ne ''
ABresult
0X0
100
111
759  
760 # A streamed functionCall part arrives whole in one chunk (it is not
761 # fragmented), so the chunk that carries it is where the call completes. Read
762 # it with the same ToolCall->extract chat_response uses. -- karr k221
763 24 my @tool_calls = Langertha::ToolCall->extract( $self->tool_wire_format, $data );
764  
765 return Langertha::Stream::Chunk->new(
766 content => $text,
767 raw => $data,
768 is_final => $is_final,
769 $finish_reason ? (finish_reason => $finish_reason) : (),
770 24 ▶ $data->{usageMetadata} ? (usage => $data->{usageMetadata}) : (),
Branch: 4 branches
BranchTrueFalseTotal
$finish_reason ? : 7 17 24
$$data{'usageMetadata'} ? : 5 19 24
defined $thinking ? : 9 15 24
@tool_calls ? : 1 23 24
771 defined $thinking ? ( thinking => $thinking ) : (),
772 @tool_calls ? ( tool_calls => \@tool_calls ) : (),
773 );
774 }
775  
776 # Dynamic model listing with token pagination
777 14 ▶sub list_models_request {
Subroutine list_models_request: called CC=2 SCAR=6.9
Pod undocumented
778 14 my ($self, %params) = @_;
779 14 my $url = $self->gemini_url('models');
780  
781 # Add pagination params if provided
782 14 ▶ if (%params) {
Branch: 1 branch
BranchTrueFalseTotal
if (%params) 2 12 14
783 2 require URI;
784 2 my $uri = URI->new($url);
785 2 my %query = $uri->query_form;
786 2 $uri->query_form(%query, %params);
787 2 $url = $uri->as_string;
788 }
789  
790 return $self->generate_http_request(
791 GET => $url,
792 3 ▶ sub { $self->list_models_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
793 14 );
794 }
795  
796 4 ▶sub list_models_response {
Subroutine list_models_response: called CC=1 SCAR=0.0
Pod undocumented
797 4 my ($self, $response) = @_;
798 4 my $data = $self->parse_response($response);
799 4 return $data;
800 }
801  
802 3 ▶sub _fetch_all_models {
Subroutine _fetch_all_models: called CC=4 SCAR=14.1
803 3 my ($self) = @_;
804 3 my @all_models;
805 my $page_token;
806  
807 3 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$page_token and do { do { my $request = $self->list_models_request($page_token ? ("pageToken", $page_token) : ()); my $response = $self->user_agent->request($request); my $data = $request->response_call->($response); push @all_models, @{$$data{"models"} or [];}; $page_token = $$data{"nextPageToken"} } } 0 3 3
808 3 ▶ my $request = $self->list_models_request(
Branch: 1 branch
BranchTrueFalseTotal
$page_token ? : 0 3 3
809 $page_token ? (pageToken => $page_token) : ()
810 );
811 3 my $response = $self->user_agent->request($request);
812 3 my $data = $request->response_call->($response);
813  
814 3 ▶ push @all_models, @{$data->{models} || []};
Condition50%1/2
$$data{'models'} || []
l!l
30
MC/DC0%0/1
$$data{'models'} || []
$$data{'models'}
Truth table50%1/2
A
A= $$data{'models'}
Aresult
11
00
815 3 $page_token = $data->{nextPageToken};
816 } while ($page_token);
817  
818 3 return \@all_models;
819 }
820  
821 3 ▶sub list_models {
Subroutine list_models: called CC=6 SCAR=19.5
Pod documented
822 3 my ($self, %opts) = @_;
823  
824 # Check cache unless force_refresh requested
825 3 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 1 2 3
826 1 my $cache = $self->_models_cache;
827 1 ▶ if ($cache->{timestamp} && time - $cache->{timestamp} < $self->models_cache_ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl) 0 1 1
Condition33%1/3
$$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl
!ll&&!rl&&r
100
MC/DC0%0/2
$$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl
$$cache{"timestamp"} time - $$cache{"timestamp"} < $self->models_cache_ttl
Truth table33%1/3
A and B
A= $$cache{"timestamp"}B= time - $$cache{"timestamp"} < $self->models_cache_ttl
ABresult
0X0
100
111
828 0 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
829 }
830 }
831  
832 # Fetch all pages from API
833 3 my $models = $self->_fetch_all_models;
834  
835 # Extract IDs and update cache
836 # Gemini uses 'name' field like "models/gemini-2.0-flash"
837 my @model_ids = map {
838 3 my $name = $_->{name};
839 3 $name =~ s{^models/}{}; # Strip "models/" prefix
840 3 $name;
841 } @$models;
842  
843 3 $self->_models_cache({
844 timestamp => time,
845 models => $models,
846 model_ids => \@model_ids,
847 });
848  
849 3 ▶ return $opts{full} ? $models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 3 3
850 }
851  
852  
853 # Tool calling support (MCP) is the tag-driven default in Langertha::Role::Tools.
854 247 ▶sub _build_tool_wire_format { 'gemini' }
Subroutine _build_tool_wire_format: called CC=1 SCAR=0.0
855  
856 64 __PACKAGE__->meta->make_immutable;
857  
858  
859 64 1;
860  
861 __END__
« blib/lib/Langertha/Engine/Ollama.pm ↑ Summary blib/lib/Langertha/Reasoning.pm »