@memberjunction/ai-gemini 6.2.0-edge.4 → 6.2.0-edge.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,23 +9,12 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  };
10
10
  var GeminiLLM_1;
11
11
  // Google Gemini Import
12
- import { GoogleGenAI, FunctionCallingConfigMode } from "@google/genai";
12
+ import { GoogleGenAI, ApiError, FunctionCallingConfigMode } from "@google/genai";
13
13
  // MJ stuff
14
14
  import { BaseLLM, ChatResult, ModelUsage, ErrorAnalyzer, CHAT_FINISH_REASON_TOOL_CALLS, CHAT_FINISH_REASON_MALFORMED_TOOL_CALL } from "@memberjunction/ai";
15
15
  import { RegisterClass, ToJSONSafe } from "@memberjunction/global";
16
- /**
17
- * True when `error` represents a client-initiated cancellation rather than a genuine provider or
18
- * network failure. Node's fetch (which @google/genai uses under the hood) rejects with a
19
- * `DOMException` named `AbortError` when the supplied `AbortSignal` fires, and with `TimeoutError`
20
- * when the signal came from `AbortSignal.timeout()`.
21
- */
22
- function isGeminiCancellationError(error) {
23
- if (!error || typeof error !== 'object') {
24
- return false;
25
- }
26
- const name = error.name;
27
- return name === 'AbortError' || name === 'TimeoutError';
28
- }
16
+ import { AcceptsCustomSampling } from "./geminiSampling.js";
17
+ import { GeminiThinkingFallback, ResolveGeminiThinkingConfig } from "./geminiThinking.js";
29
18
  /**
30
19
  * Gemini 3 requires a `thoughtSignature` on every replayed `functionCall` part. Calls the model made
31
20
  * carry their own (kept on `ChatToolCall.providerMetadata`); calls constructed outside the model —
@@ -52,7 +41,8 @@ const THOUGHT_SIGNATURE_ORIGIN_KEY = 'thoughtSignatureOrigin';
52
41
  * so the model reads it as the opening request rather than as noise.
53
42
  */
54
43
  export const GEMINI_LEADING_USER_TURN_TEXT = 'Proceed with the task described in the system instructions.';
55
- let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
44
+ let GeminiLLM = class GeminiLLM extends BaseLLM {
45
+ static { GeminiLLM_1 = this; }
56
46
  constructor(apiKey) {
57
47
  super(apiKey);
58
48
  this._gemini = null;
@@ -67,10 +57,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
67
57
  // Diagnostic context for the in-flight streaming request, used only by the GEMINI_CACHE_DEBUG
68
58
  // logging path so the final chunk's usage can be reported alongside the request's prefix info.
69
59
  this._cacheDiagContext = null;
70
- // Cancellation token for the in-flight STREAMING request. The base class's streaming loop
71
- // swallows mid-stream iteration errors, so finalizeStreamingResponse() consults this to detect
72
- // that the stream ended because the caller aborted (rather than because the model finished).
73
- this._streamingCancellationToken = null;
74
60
  // Note: We don't initialize the client here to allow subclasses to set up first
75
61
  // Initialization happens lazily on first use via ensureGeminiClient()
76
62
  }
@@ -124,70 +110,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
124
110
  }
125
111
  return this._gemini;
126
112
  }
127
- /**
128
- * Convert MJ effort level (1-100) to Gemini thinkingBudget (0-24576)
129
- *
130
- * Mapping strategy:
131
- * - 1 (minimal): 0 (disabled) on Flash; clamped to ~1024 on Pro
132
- * - 2-33 (low): 1024-4096 tokens
133
- * - 34-66 (medium): 4097-12288 tokens
134
- * - 67-100 (high): 12289-24576 tokens
135
- * - undefined: No thinkingConfig (Gemini default ~8192)
136
- *
137
- * Model-specific behavior:
138
- * - Gemini 2.5 Flash/Flash-Lite: Can disable thinking with budget=0
139
- * - Gemini 2.5 Pro: Cannot disable thinking, minimum ~1024
140
- * - Gemini 3 models: Use thinkingLevel instead (future consideration)
141
- *
142
- * @param effortLevel - MJ normalized effort level (1-100) as string or number
143
- * @param modelName - The Gemini model name to check capabilities
144
- * @returns thinkingBudget value or undefined for default behavior
145
- */
146
- getThinkingBudget(effortLevel, modelName) {
147
- if (effortLevel === undefined || effortLevel === null || effortLevel === '') {
148
- return undefined; // Use Gemini's default behavior (auto, up to ~8192)
149
- }
150
- // Parse string to number if needed
151
- const numericLevel = typeof effortLevel === 'string' ? parseInt(effortLevel, 10) : effortLevel;
152
- if (isNaN(numericLevel)) {
153
- return undefined; // Invalid effort level, use default
154
- }
155
- // Clamp to valid range
156
- const level = Math.max(1, Math.min(100, numericLevel));
157
- // Check model capabilities for thinking
158
- const lowerModel = modelName.toLowerCase();
159
- const isFlashModel = lowerModel.includes('flash');
160
- const isProModel = lowerModel.includes('pro') && !isFlashModel;
161
- // Minimal effort (1) - disable thinking on Flash models
162
- if (level === 1 && isFlashModel) {
163
- return 0; // Disable thinking (only works on Flash/Flash-Lite)
164
- }
165
- // For Pro models, minimum effective budget is ~1024
166
- // For Flash models with effort >= 2, use normal scaling
167
- if (level <= 33) {
168
- // Low (2-33): linear scale from 1024 to 4096
169
- return Math.round(1024 + ((level - 2) / 31) * (4096 - 1024));
170
- }
171
- else if (level <= 66) {
172
- // Medium: linear scale from 4097 to 12288
173
- return Math.round(4097 + ((level - 34) / 32) * (12288 - 4097));
174
- }
175
- else {
176
- // High: linear scale from 12289 to 24576
177
- return Math.round(12289 + ((level - 67) / 33) * (24576 - 12289));
178
- }
179
- }
180
- /**
181
- * Check if a model supports thinking configuration
182
- * Thinking is supported on Gemini 2.5+ models
183
- */
184
- supportsThinking(modelName) {
185
- const lowerModel = modelName.toLowerCase();
186
- // Gemini 2.5 and later support thinking
187
- return lowerModel.includes('2.5') ||
188
- lowerModel.includes('gemini-3') ||
189
- lowerModel.includes('gemini-exp');
190
- }
191
113
  /**
192
114
  * Gemini supports streaming
193
115
  */
@@ -241,8 +163,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
241
163
  async nonStreamingChatCompletion(params) {
242
164
  const startTime = new Date();
243
165
  try {
244
- // Fail fast if the caller already cancelled before we opened a socket.
245
- this.throwIfCancelled(params.cancellationToken);
246
166
  // For text-only input, use the gemini-pro model
247
167
  const modelName = params.model || "gemini-pro";
248
168
  // Filter out system messages and extract system instruction content
@@ -269,49 +189,8 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
269
189
  if (finalMessageParts.length === 0) {
270
190
  finalMessageParts = [{ text: '' }];
271
191
  }
272
- // Create the model and then chat
273
- const modelOptions = {
274
- temperature: params.temperature || 0.5,
275
- };
276
- switch (params.responseFormat) {
277
- case 'JSON':
278
- modelOptions.responseMimeType = 'application/json';
279
- break;
280
- case 'ModelSpecific':
281
- if (params.modelSpecificResponseFormat) {
282
- Object.assign(modelOptions, params.modelSpecificResponseFormat);
283
- }
284
- break;
285
- }
286
- // Add supported parameters
287
- if (params.topP != null) {
288
- modelOptions.top_p = params.topP;
289
- }
290
- if (params.topK != null) {
291
- modelOptions.top_k = params.topK;
292
- }
293
- if (params.stopSequences != null && params.stopSequences.length > 0) {
294
- modelOptions.stopSequences = params.stopSequences;
295
- }
296
- if (params.seed != null) {
297
- modelOptions.seed = params.seed;
298
- }
299
- // Gemini doesn't support these parameters - warn if provided
300
- if (params.frequencyPenalty != null) {
301
- console.warn('Gemini provider does not support frequencyPenalty parameter, ignoring');
302
- }
303
- if (params.presencePenalty != null) {
304
- console.warn('Gemini provider does not support presencePenalty parameter, ignoring');
305
- }
306
- if (params.minP != null) {
307
- console.warn('Gemini provider does not support minP parameter, ignoring');
308
- }
309
- // Build thinking configuration based on effort level and model capabilities
310
- const thinkingBudget = this.getThinkingBudget(params.effortLevel, modelName);
311
- const useThinking = this.supportsThinking(modelName) && thinkingBudget !== undefined;
312
- // Create chat config - only include thinkingConfig if model supports it and effortLevel is specified
313
- const chatConfig = {};
314
- this.setThinkingConfig(chatConfig, useThinking, params.effortLevel, modelName, thinkingBudget);
192
+ // Sampling + response-format options, shaped for the model's version (see buildGenerationOptions)
193
+ const modelOptions = this.buildGenerationOptions(params, modelName);
315
194
  // Ensure Gemini client is initialized
316
195
  const client = await this.ensureGeminiClient();
317
196
  // Pass the system prompt as systemInstruction (a plain string — a string[] is invalid and
@@ -319,24 +198,15 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
319
198
  // cacheable prefix so Gemini's implicit cache can engage across turns.
320
199
  // NOTE: @google/genai's sendMessage `config` REPLACES (not merges) the session config, so
321
200
  // systemInstruction must ride in the per-request config (modelOptions) — that's the one
322
- // that applies. We intentionally do NOT fold chatConfig (thinkingConfig) in here: that
323
- // preserves the prior thinking behavior exactly (it stays on the session config) and avoids
324
- // sending a thinking level some models reject.
201
+ // that applies, and the session config is never sent. The same holds for thinkingConfig.
325
202
  const requestConfig = { ...modelOptions };
326
203
  if (systemInstructionText) {
327
204
  requestConfig.systemInstruction = systemInstructionText;
328
205
  }
329
206
  this.applyToolParams(requestConfig, params);
207
+ this.applyThinkingConfig(requestConfig, modelName, params.effortLevel);
330
208
  this.applyCancellationToken(requestConfig, params.cancellationToken);
331
- const chat = client.chats.create({
332
- config: Object.keys(chatConfig).length > 0 ? chatConfig : undefined,
333
- model: modelName,
334
- history: history
335
- });
336
- const result = await chat.sendMessage({
337
- message: finalMessageParts,
338
- config: requestConfig
339
- });
209
+ const result = await this.sendWithThinkingFallback(modelName, requestConfig, params.cancellationToken, config => client.chats.create({ model: modelName, history }).sendMessage({ message: finalMessageParts, config }));
340
210
  // Check for blocked response or empty candidates
341
211
  if (!result.candidates || result.candidates.length === 0) {
342
212
  // Response was blocked or failed - check promptFeedback for details
@@ -373,7 +243,7 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
373
243
  throw new Error(`Content blocked by model: ${finishReason}${blockedCategories ? ` - ${blockedCategories}` : ''}`);
374
244
  }
375
245
  const rawContent = candidate.content?.parts?.find(part => part.text && !part.thought)?.text || '';
376
- const thinking = candidate.content?.parts?.find(part => part.thought)?.text || '';
246
+ const thinking = (candidate.content?.parts ?? []).filter(part => part.thought && part.text).map(part => part.text).join('');
377
247
  const toolCalls = this.extractToolCalls(candidate.content?.parts, this.thoughtSignatureOrigin(modelName));
378
248
  // Check if we got empty content despite no blocking. A native tool call IS output, and a
379
249
  // forced/clean tool-call turn legitimately carries no text at all — so tool calls
@@ -399,15 +269,8 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
399
269
  thinkingContent = thinking;
400
270
  }
401
271
  const endTime = new Date();
402
- // Gemini's cache convention: `promptTokenCount` INCLUDES cached tokens, reported
403
- // separately as `cachedContentTokenCount`. Normalize to the uniform ModelUsage contract:
404
- // promptTokens must be UNCACHED/net-new only, so subtract the cache-read count (clamped at
405
- // 0) and record it disjointly. Gemini does not report a separate cache-write charge, so
406
- // cacheWriteTokens stays 0. Full native prompt count = usage.totalInputTokens.
407
- const geminiCachedTokens = result.usageMetadata?.cachedContentTokenCount ?? 0;
408
- const geminiNetPromptTokens = Math.max(0, (result.usageMetadata?.promptTokenCount || 0) - geminiCachedTokens);
409
- const geminiUsage = new ModelUsage(geminiNetPromptTokens, result.usageMetadata?.candidatesTokenCount || 0);
410
- geminiUsage.cacheReadTokens = geminiCachedTokens;
272
+ const geminiUsage = GeminiLLM_1.usageFromMetadata(result.usageMetadata);
273
+ const geminiCachedTokens = geminiUsage.cacheReadTokens ?? 0;
411
274
  this.logCacheDiagnostics('non-streaming', this.buildCacheDiagContext(modelName, systemInstructionText, history.length), result.usageMetadata);
412
275
  return {
413
276
  success: true,
@@ -448,8 +311,9 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
448
311
  };
449
312
  }
450
313
  catch (e) {
451
- if (this.isCancelled(e, params.cancellationToken)) {
452
- return this.buildCancelledResult(startTime, e, params.cancellationToken);
314
+ // Node's fetch, which @google/genai uses, rejects with an AbortError when the signal fires.
315
+ if (this.IsCancellationError(e, params.cancellationToken)) {
316
+ return this.BuildCancelledChatResult(startTime, { error: e, signal: params.cancellationToken });
453
317
  }
454
318
  return {
455
319
  success: false,
@@ -467,11 +331,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
467
331
  };
468
332
  }
469
333
  }
470
- /**
471
- * Attach the caller's cancellation token to a Gemini per-request config. @google/genai reads
472
- * `GenerateContentConfig.abortSignal` and forwards it to the underlying `fetch` call, so an
473
- * abort tears down the HTTP socket instead of merely abandoning the promise.
474
- */
475
334
  /**
476
335
  * Maps the neutral {@link ChatParams.tools} onto Gemini's `tools` / `toolConfig` request fields.
477
336
  *
@@ -562,101 +421,169 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
562
421
  }
563
422
  return calls.length > 0 ? calls : undefined;
564
423
  }
424
+ /**
425
+ * Attach the caller's cancellation token to a Gemini per-request config. @google/genai reads
426
+ * `GenerateContentConfig.abortSignal` and forwards it to the underlying `fetch` call, so an
427
+ * abort tears down the HTTP socket instead of merely abandoning the promise.
428
+ */
565
429
  applyCancellationToken(requestConfig, token) {
566
430
  if (token) {
567
431
  requestConfig.abortSignal = token;
568
432
  }
569
433
  }
570
- /** Throw immediately (before any socket is opened) when the caller has already cancelled. */
571
- throwIfCancelled(token) {
572
- if (token?.aborted) {
573
- throw this.createCancellationError(token);
434
+ /**
435
+ * Model + field pairs already warned about, so a prompt that sets `temperature` on every call
436
+ * logs once per process instead of once per request.
437
+ */
438
+ static { this._warnedUnsupportedSampling = new Set(); }
439
+ /**
440
+ * Builds the per-request generation options: sampling, stop sequences, seed, response format.
441
+ *
442
+ * Sampling fields depend on the model's version. Models before Gemini 3.6 keep the original
443
+ * shape (`temperature` defaulting to 0.5, `topP`, `topK`) because they still honor it. Every
444
+ * other model gets none of the three: Google ignores them since Gemini 3.6 Flash and upcoming
445
+ * models reject them with a 400, so a caller-supplied value is dropped with a one-time warning.
446
+ *
447
+ * A `ModelSpecific` response format is merged in after this gate, so it can still set these
448
+ * fields explicitly; that is the caller's deliberate override.
449
+ */
450
+ buildGenerationOptions(params, modelName) {
451
+ const modelOptions = {};
452
+ if (AcceptsCustomSampling(modelName)) {
453
+ modelOptions.temperature = params.temperature ?? 0.5;
454
+ if (params.topP != null) {
455
+ modelOptions.topP = params.topP;
456
+ }
457
+ if (params.topK != null) {
458
+ modelOptions.topK = params.topK;
459
+ }
460
+ }
461
+ else {
462
+ this.warnUnsupportedSampling(modelName, 'temperature', params.temperature);
463
+ this.warnUnsupportedSampling(modelName, 'topP', params.topP);
464
+ this.warnUnsupportedSampling(modelName, 'topK', params.topK);
574
465
  }
466
+ switch (params.responseFormat) {
467
+ case 'JSON':
468
+ modelOptions.responseMimeType = 'application/json';
469
+ break;
470
+ case 'ModelSpecific':
471
+ if (params.modelSpecificResponseFormat) {
472
+ Object.assign(modelOptions, params.modelSpecificResponseFormat);
473
+ }
474
+ break;
475
+ }
476
+ if (params.stopSequences != null && params.stopSequences.length > 0) {
477
+ modelOptions.stopSequences = params.stopSequences;
478
+ }
479
+ if (params.seed != null) {
480
+ modelOptions.seed = params.seed;
481
+ }
482
+ // Gemini doesn't support these parameters - warn if provided
483
+ if (params.frequencyPenalty != null) {
484
+ console.warn('Gemini provider does not support frequencyPenalty parameter, ignoring');
485
+ }
486
+ if (params.presencePenalty != null) {
487
+ console.warn('Gemini provider does not support presencePenalty parameter, ignoring');
488
+ }
489
+ if (params.minP != null) {
490
+ console.warn('Gemini provider does not support minP parameter, ignoring');
491
+ }
492
+ return modelOptions;
575
493
  }
576
- /** The canonical abort error we raise for a pre-aborted request, shaped like fetch's own. */
577
- createCancellationError(token) {
578
- const error = new Error(this.describeCancellation(token));
579
- error.name = 'AbortError';
580
- return error;
494
+ warnUnsupportedSampling(modelName, field, value) {
495
+ if (value == null) {
496
+ return;
497
+ }
498
+ const key = `${modelName}:${field}`;
499
+ if (GeminiLLM_1._warnedUnsupportedSampling.has(key)) {
500
+ return;
501
+ }
502
+ GeminiLLM_1._warnedUnsupportedSampling.add(key);
503
+ console.warn(`Gemini model ${modelName} does not accept a custom ${field}; omitting it so the model uses its default sampling.`);
581
504
  }
582
- /** True when this failure is the caller's cancellation rather than a provider/network fault. */
583
- isCancelled(error, token) {
584
- return token?.aborted === true || isGeminiCancellationError(error);
505
+ /**
506
+ * Thinking settings a model rejected in this process, mapped to what was sent instead (`null`
507
+ * for no setting). Keyed by driver, model and setting, so a rejected `MINIMAL` does not stop
508
+ * `HIGH` being sent, and a rejection through one driver does not affect another.
509
+ */
510
+ static { this._thinkingReplacements = new Map(); }
511
+ /** Thinking warnings already logged, so each is logged once per process. */
512
+ static { this._warnedThinking = new Set(); }
513
+ thinkingReplacementKey(modelName, config) {
514
+ return `${this.constructor.name}|${modelName}|${JSON.stringify(config)}`;
585
515
  }
586
- /** Human-readable reason for a cancellation, preferring the signal's own reason when present. */
587
- describeCancellation(token) {
588
- const reason = token?.reason;
589
- if (reason instanceof Error && reason.message) {
590
- return `Gemini request cancelled: ${reason.message}`;
516
+ /**
517
+ * Puts the `thinkingConfig` for `effortLevel` on the request (see {@link ResolveGeminiThinkingConfig}),
518
+ * or what replaced it after the model rejected it earlier in this process. Nothing is added when
519
+ * no effort is set; an effort that cannot be used is reported once.
520
+ */
521
+ applyThinkingConfig(requestConfig, modelName, effortLevel) {
522
+ const resolution = ResolveGeminiThinkingConfig(modelName, effortLevel);
523
+ if (resolution.Ignored) {
524
+ this.warnThinkingOnce(`${modelName}:${resolution.Ignored}`, `Gemini: ${resolution.Ignored}; sending no thinking setting, so the model thinks at its default.`);
525
+ }
526
+ if (!resolution.Config) {
527
+ return;
591
528
  }
592
- if (typeof reason === 'string' && reason.length > 0) {
593
- return `Gemini request cancelled: ${reason}`;
529
+ const key = this.thinkingReplacementKey(modelName, resolution.Config);
530
+ const config = GeminiLLM_1._thinkingReplacements.has(key) ? GeminiLLM_1._thinkingReplacements.get(key) : resolution.Config;
531
+ if (config) {
532
+ requestConfig.thinkingConfig = config;
594
533
  }
595
- return 'Gemini request cancelled by caller';
596
534
  }
597
535
  /**
598
- * Build the typed ChatResult for a cancelled request. Reported as a normal failed ChatResult —
599
- * same shape as every other Gemini error path — never as an unhandled rejection.
536
+ * Sends a request, and when it carried a thinking setting and Google answered 400, sends it once
537
+ * more with the setting's fallback (see {@link GeminiThinkingFallback}: `LOW` for a rejected
538
+ * `MINIMAL`, otherwise none). Which levels a model accepts varies (Gemini 3.8 Flash rejects
539
+ * `MINIMAL`), so an unsupported level must not fail the request. When the retry succeeds, the
540
+ * rejected setting is replaced for this driver and model for the rest of the process; when it also
541
+ * fails, the 400 had another cause, so the original error is thrown and nothing is remembered.
600
542
  */
601
- buildCancelledResult(startTime, error, token) {
602
- const endTime = new Date();
603
- const result = new ChatResult(false, startTime, endTime);
604
- result.statusText = 'Cancelled';
605
- result.errorMessage = this.describeCancellation(token ?? undefined);
606
- result.exception = error;
607
- result.errorInfo = ErrorAnalyzer.analyzeError(error, 'Gemini');
608
- result.data = {
609
- choices: [],
610
- usage: new ModelUsage(0, 0)
611
- };
612
- return result;
613
- }
614
- setThinkingConfig(chatConfig, useThinking, effortLevel, modelName, thinkingBudget) {
615
- // this is a hack, need a cleaner way of doing this
616
- const gemini3AndAbove = modelName?.toLowerCase().includes("-3") ||
617
- modelName?.toLowerCase().includes("-4") ||
618
- modelName?.toLowerCase().includes("-5") ||
619
- modelName?.toLowerCase().includes("-6") ||
620
- modelName?.toLowerCase().includes("-7");
621
- if (useThinking) {
622
- if (gemini3AndAbove) {
623
- // no budget used, we map the effortLevel to 4 buckets
624
- let geminiLevel = undefined;
625
- // Parse string to number if needed
626
- let numericLevel = typeof effortLevel === 'string' ? parseInt(effortLevel, 10) : effortLevel;
627
- if (isNaN(numericLevel)) {
628
- numericLevel = 0;
629
- }
630
- if (numericLevel === 1) {
631
- geminiLevel = "MINIMAL"; // effort 1 is the minimum valid value and maps to minimal thinking on Gemini 3+ models
632
- }
633
- else if (numericLevel >= 2 && numericLevel <= 33) {
634
- geminiLevel = "LOW";
635
- }
636
- else if (numericLevel <= 66) {
637
- geminiLevel = "MEDIUM";
638
- }
639
- else {
640
- geminiLevel = "HIGH";
641
- }
642
- chatConfig.thinkingConfig = {
643
- thinkingLevel: geminiLevel
644
- };
543
+ async sendWithThinkingFallback(modelName, requestConfig, cancellationToken, send) {
544
+ try {
545
+ return await send(requestConfig);
546
+ }
547
+ catch (error) {
548
+ const { thinkingConfig, ...withoutThinking } = requestConfig;
549
+ if (!thinkingConfig || !(error instanceof ApiError) || error.status !== 400 || cancellationToken?.aborted) {
550
+ throw error;
645
551
  }
646
- else {
647
- chatConfig.thinkingConfig = {
648
- includeThoughts: true,
649
- thinkingBudget: thinkingBudget
650
- };
552
+ const fallback = GeminiThinkingFallback(thinkingConfig);
553
+ let result;
554
+ try {
555
+ result = await send(fallback ? { ...withoutThinking, thinkingConfig: fallback } : withoutThinking);
651
556
  }
652
- }
653
- else {
654
- if (gemini3AndAbove) {
655
- chatConfig.thinkingConfig = {
656
- thinkingLevel: "MINIMAL" // if we don't have thinking setup and we're dealing with Gemini 3 series models, set thinking level to minimal
657
- };
557
+ catch {
558
+ throw error;
658
559
  }
560
+ GeminiLLM_1._thinkingReplacements.set(this.thinkingReplacementKey(modelName, thinkingConfig), fallback ?? null);
561
+ this.warnThinkingOnce(this.thinkingReplacementKey(modelName, thinkingConfig), `Gemini model ${modelName} rejected thinking setting ${JSON.stringify(thinkingConfig)} (${error.message}); ` +
562
+ `sending ${fallback ? JSON.stringify(fallback) : 'no thinking setting'} instead for the rest of the process.`);
563
+ return result;
564
+ }
565
+ }
566
+ warnThinkingOnce(key, message) {
567
+ if (GeminiLLM_1._warnedThinking.has(key)) {
568
+ return;
659
569
  }
570
+ GeminiLLM_1._warnedThinking.add(key);
571
+ console.warn(message);
572
+ }
573
+ /**
574
+ * Normalizes Gemini usage to the {@link ModelUsage} contract.
575
+ *
576
+ * - `promptTokenCount` includes cached tokens, reported separately as `cachedContentTokenCount`,
577
+ * so the cached count is subtracted (clamped at 0) and recorded as `cacheReadTokens`. Gemini
578
+ * reports no separate cache-write charge.
579
+ * - `candidatesTokenCount` leaves out thinking, which Google counts in `thoughtsTokenCount` and
580
+ * bills as output, so completion tokens are the sum of the two.
581
+ */
582
+ static usageFromMetadata(metadata) {
583
+ const cached = metadata?.cachedContentTokenCount ?? 0;
584
+ const usage = new ModelUsage(Math.max(0, (metadata?.promptTokenCount ?? 0) - cached), (metadata?.candidatesTokenCount ?? 0) + (metadata?.thoughtsTokenCount ?? 0));
585
+ usage.cacheReadTokens = cached;
586
+ return usage;
660
587
  }
661
588
  /**
662
589
  * Reset streaming state for a new request
@@ -668,7 +595,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
668
595
  pendingContent: '',
669
596
  thinkingComplete: false
670
597
  };
671
- this._streamingCancellationToken = null;
672
598
  }
673
599
  /**
674
600
  * Create a streaming request for Gemini
@@ -676,8 +602,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
676
602
  async createStreamingRequest(params) {
677
603
  // Reset streaming state for new request
678
604
  this.resetStreamingState();
679
- this.throwIfCancelled(params.cancellationToken);
680
- this._streamingCancellationToken = params.cancellationToken ?? null;
681
605
  const modelName = params.model || "gemini-pro";
682
606
  // Filter out system messages and extract system instruction content
683
607
  const noSystemMessages = params.messages.filter(m => m.role !== 'system');
@@ -708,70 +632,22 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
708
632
  if (finalMessageParts.length === 0) {
709
633
  finalMessageParts = [{ text: '' }];
710
634
  }
711
- // Create the model and then chat
712
- const modelOptions = {
713
- temperature: params.temperature || 0.5,
714
- };
715
- switch (params.responseFormat) {
716
- case 'JSON':
717
- modelOptions.responseMimeType = 'application/json';
718
- break;
719
- case 'ModelSpecific':
720
- if (params.modelSpecificResponseFormat) {
721
- Object.assign(modelOptions, params.modelSpecificResponseFormat);
722
- }
723
- break;
724
- }
725
- // Add supported parameters
726
- if (params.topP != null) {
727
- modelOptions.top_p = params.topP;
728
- }
729
- if (params.topK != null) {
730
- modelOptions.top_k = params.topK;
731
- }
732
- if (params.stopSequences != null && params.stopSequences.length > 0) {
733
- modelOptions.stopSequences = params.stopSequences;
734
- }
735
- if (params.seed != null) {
736
- modelOptions.seed = params.seed;
737
- }
738
- // Gemini doesn't support these parameters - warn if provided
739
- if (params.frequencyPenalty != null) {
740
- console.warn('Gemini provider does not support frequencyPenalty parameter, ignoring');
741
- }
742
- if (params.presencePenalty != null) {
743
- console.warn('Gemini provider does not support presencePenalty parameter, ignoring');
744
- }
745
- if (params.minP != null) {
746
- console.warn('Gemini provider does not support minP parameter, ignoring');
747
- }
748
- // Build thinking configuration based on effort level and model capabilities
749
- const thinkingBudget = this.getThinkingBudget(params.effortLevel, modelName);
750
- const useThinking = this.supportsThinking(modelName) && thinkingBudget !== undefined;
751
- // Create chat config - only include thinkingConfig if model supports it and effortLevel is specified
752
- const chatConfig = {};
753
- this.setThinkingConfig(chatConfig, useThinking, params.effortLevel, modelName, thinkingBudget);
635
+ // Sampling + response-format options, shaped for the model's version (see buildGenerationOptions)
636
+ const modelOptions = this.buildGenerationOptions(params, modelName);
754
637
  // Ensure Gemini client is initialized
755
638
  const client = await this.ensureGeminiClient();
756
639
  // systemInstruction (a plain string) is the stable, cacheable prefix. It must ride in the
757
- // per-request config since @google/genai's sendMessage config REPLACES the session config.
758
- // We do NOT fold chatConfig (thinkingConfig) in — that preserves prior thinking behavior and
759
- // avoids sending a thinking level some models reject (see nonStreamingChatCompletion).
640
+ // per-request config since @google/genai's sendMessage config REPLACES the session config;
641
+ // so must thinkingConfig.
760
642
  const requestConfig = { ...modelOptions };
761
643
  if (systemInstructionText) {
762
644
  requestConfig.systemInstruction = systemInstructionText;
763
645
  }
646
+ this.applyThinkingConfig(requestConfig, modelName, params.effortLevel);
764
647
  this.applyCancellationToken(requestConfig, params.cancellationToken);
765
- const chat = client.chats.create({
766
- config: Object.keys(chatConfig).length > 0 ? chatConfig : undefined,
767
- model: modelName,
768
- history: history
769
- });
770
- // Send the latest user message (streaming); system prompt rides in requestConfig.
771
- const streamResult = await chat.sendMessageStream({
772
- message: finalMessageParts,
773
- config: requestConfig
774
- });
648
+ // Send the latest user message (streaming); system prompt rides in requestConfig. A rejected
649
+ // request throws here, before any chunk, so the thinking fallback works as it does above.
650
+ const streamResult = await this.sendWithThinkingFallback(modelName, requestConfig, params.cancellationToken, config => client.chats.create({ model: modelName, history }).sendMessageStream({ message: finalMessageParts, config }));
775
651
  // Return the stream for the for-await loop to work
776
652
  return streamResult;
777
653
  }
@@ -811,16 +687,10 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
811
687
  if (chunk?.candidates?.[0]?.finishReason) {
812
688
  finishReason = chunk.candidates[0].finishReason;
813
689
  }
814
- // Extract usage from chunk if available (appears on final chunk). Normalize to the uniform
815
- // ModelUsage contract: promptTokenCount INCLUDES cached, so subtract cachedContentTokenCount
816
- // (clamped at 0) to get UNCACHED/net-new promptTokens; cacheReadTokens holds the disjoint
817
- // cache-read subset.
690
+ // Extract usage from chunk if available (appears on final chunk).
818
691
  let usage = null;
819
692
  if (chunk.usageMetadata) {
820
- const chunkCachedTokens = chunk.usageMetadata.cachedContentTokenCount ?? 0;
821
- const chunkNetPromptTokens = Math.max(0, (chunk.usageMetadata.promptTokenCount || 0) - chunkCachedTokens);
822
- usage = new ModelUsage(chunkNetPromptTokens, chunk.usageMetadata.candidatesTokenCount || 0);
823
- usage.cacheReadTokens = chunkCachedTokens;
693
+ usage = GeminiLLM_1.usageFromMetadata(chunk.usageMetadata);
824
694
  // Usage only appears on the final chunk — log the cache diagnostic once here.
825
695
  this.logCacheDiagnostics('streaming', this._cacheDiagContext, chunk.usageMetadata);
826
696
  }
@@ -965,14 +835,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
965
835
  * Create the final response from streaming results for Gemini
966
836
  */
967
837
  finalizeStreamingResponse(accumulatedContent, lastChunk, usage) {
968
- // A mid-stream abort surfaces as an iteration error that the base class swallows, so the
969
- // ONLY reliable signal here is the token itself. Report cancellation as a clean failure
970
- // rather than passing off a truncated stream as a successful completion.
971
- const cancellationToken = this._streamingCancellationToken;
972
- if (cancellationToken?.aborted) {
973
- const now = new Date();
974
- return this.buildCancelledResult(now, this.createCancellationError(cancellationToken), cancellationToken);
975
- }
976
838
  // Extract finish reason from last chunk if available
977
839
  let finishReason = 'stop';
978
840
  if (lastChunk?.candidates && lastChunk.candidates.length > 0 && lastChunk.candidates[0].finishReason) {