@memberjunction/ai-gemini 6.2.0-edge.4 → 6.2.0-edge.6
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/geminiEmbedding.d.ts +11 -0
- package/dist/geminiEmbedding.d.ts.map +1 -1
- package/dist/geminiEmbedding.js +34 -12
- package/dist/geminiEmbedding.js.map +1 -1
- package/dist/geminiImage.d.ts +10 -3
- package/dist/geminiImage.d.ts.map +1 -1
- package/dist/geminiImage.js +84 -14
- package/dist/geminiImage.js.map +1 -1
- package/dist/geminiLiveSetup.d.ts +1 -1
- package/dist/geminiLiveSetup.js +4 -4
- package/dist/geminiLiveSetup.js.map +1 -1
- package/dist/geminiRealtime.d.ts +20 -2
- package/dist/geminiRealtime.d.ts.map +1 -1
- package/dist/geminiRealtime.js +50 -10
- package/dist/geminiRealtime.js.map +1 -1
- package/dist/geminiSampling.d.ts +30 -0
- package/dist/geminiSampling.d.ts.map +1 -0
- package/dist/geminiSampling.js +44 -0
- package/dist/geminiSampling.js.map +1 -0
- package/dist/geminiThinking.d.ts +54 -0
- package/dist/geminiThinking.d.ts.map +1 -0
- package/dist/geminiThinking.js +107 -0
- package/dist/geminiThinking.js.map +1 -0
- package/dist/index.d.ts +84 -43
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +254 -322
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
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
|
-
import { BaseLLM, ChatResult, ModelUsage, ErrorAnalyzer, CHAT_FINISH_REASON_TOOL_CALLS, CHAT_FINISH_REASON_MALFORMED_TOOL_CALL } from "@memberjunction/ai";
|
|
14
|
+
import { BaseLLM, ChatResult, ModelUsage, ErrorAnalyzer, CHAT_FINISH_REASON_TOOL_CALLS, CHAT_FINISH_REASON_MALFORMED_TOOL_CALL, CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL } from "@memberjunction/ai";
|
|
15
15
|
import { RegisterClass, ToJSONSafe } from "@memberjunction/global";
|
|
16
|
-
|
|
17
|
-
|
|
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 —
|
|
@@ -40,6 +29,8 @@ const GEMINI_INJECTED_CALL_THOUGHT_SIGNATURE = 'skip_thought_signature_validator
|
|
|
40
29
|
* on capture, compared on replay, and a foreign signature is replaced with the placeholder.
|
|
41
30
|
*/
|
|
42
31
|
const THOUGHT_SIGNATURE_ORIGIN_KEY = 'thoughtSignatureOrigin';
|
|
32
|
+
/** The `provider` this driver (and Vertex, which extends it) stamps on its {@link ChatReasoningBlock}s. */
|
|
33
|
+
const GEMINI_REASONING_PROVIDER = 'gemini';
|
|
43
34
|
/**
|
|
44
35
|
* The user turn Gemini is given when a conversation would otherwise open with a model turn.
|
|
45
36
|
*
|
|
@@ -52,7 +43,8 @@ const THOUGHT_SIGNATURE_ORIGIN_KEY = 'thoughtSignatureOrigin';
|
|
|
52
43
|
* so the model reads it as the opening request rather than as noise.
|
|
53
44
|
*/
|
|
54
45
|
export const GEMINI_LEADING_USER_TURN_TEXT = 'Proceed with the task described in the system instructions.';
|
|
55
|
-
let GeminiLLM =
|
|
46
|
+
let GeminiLLM = class GeminiLLM extends BaseLLM {
|
|
47
|
+
static { GeminiLLM_1 = this; }
|
|
56
48
|
constructor(apiKey) {
|
|
57
49
|
super(apiKey);
|
|
58
50
|
this._gemini = null;
|
|
@@ -67,10 +59,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
67
59
|
// Diagnostic context for the in-flight streaming request, used only by the GEMINI_CACHE_DEBUG
|
|
68
60
|
// logging path so the final chunk's usage can be reported alongside the request's prefix info.
|
|
69
61
|
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
62
|
// Note: We don't initialize the client here to allow subclasses to set up first
|
|
75
63
|
// Initialization happens lazily on first use via ensureGeminiClient()
|
|
76
64
|
}
|
|
@@ -124,70 +112,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
124
112
|
}
|
|
125
113
|
return this._gemini;
|
|
126
114
|
}
|
|
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
115
|
/**
|
|
192
116
|
* Gemini supports streaming
|
|
193
117
|
*/
|
|
@@ -241,8 +165,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
241
165
|
async nonStreamingChatCompletion(params) {
|
|
242
166
|
const startTime = new Date();
|
|
243
167
|
try {
|
|
244
|
-
// Fail fast if the caller already cancelled before we opened a socket.
|
|
245
|
-
this.throwIfCancelled(params.cancellationToken);
|
|
246
168
|
// For text-only input, use the gemini-pro model
|
|
247
169
|
const modelName = params.model || "gemini-pro";
|
|
248
170
|
// Filter out system messages and extract system instruction content
|
|
@@ -269,49 +191,8 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
269
191
|
if (finalMessageParts.length === 0) {
|
|
270
192
|
finalMessageParts = [{ text: '' }];
|
|
271
193
|
}
|
|
272
|
-
//
|
|
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);
|
|
194
|
+
// Sampling + response-format options, shaped for the model's version (see buildGenerationOptions)
|
|
195
|
+
const modelOptions = this.buildGenerationOptions(params, modelName);
|
|
315
196
|
// Ensure Gemini client is initialized
|
|
316
197
|
const client = await this.ensureGeminiClient();
|
|
317
198
|
// Pass the system prompt as systemInstruction (a plain string — a string[] is invalid and
|
|
@@ -319,24 +200,15 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
319
200
|
// cacheable prefix so Gemini's implicit cache can engage across turns.
|
|
320
201
|
// NOTE: @google/genai's sendMessage `config` REPLACES (not merges) the session config, so
|
|
321
202
|
// systemInstruction must ride in the per-request config (modelOptions) — that's the one
|
|
322
|
-
// that applies
|
|
323
|
-
// preserves the prior thinking behavior exactly (it stays on the session config) and avoids
|
|
324
|
-
// sending a thinking level some models reject.
|
|
203
|
+
// that applies, and the session config is never sent. The same holds for thinkingConfig.
|
|
325
204
|
const requestConfig = { ...modelOptions };
|
|
326
205
|
if (systemInstructionText) {
|
|
327
206
|
requestConfig.systemInstruction = systemInstructionText;
|
|
328
207
|
}
|
|
329
208
|
this.applyToolParams(requestConfig, params);
|
|
209
|
+
this.applyThinkingConfig(requestConfig, modelName, params.effortLevel);
|
|
330
210
|
this.applyCancellationToken(requestConfig, params.cancellationToken);
|
|
331
|
-
const
|
|
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
|
-
});
|
|
211
|
+
const result = await this.sendWithThinkingFallback(modelName, requestConfig, params.cancellationToken, config => client.chats.create({ model: modelName, history }).sendMessage({ message: finalMessageParts, config }));
|
|
340
212
|
// Check for blocked response or empty candidates
|
|
341
213
|
if (!result.candidates || result.candidates.length === 0) {
|
|
342
214
|
// Response was blocked or failed - check promptFeedback for details
|
|
@@ -372,13 +244,19 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
372
244
|
.join(', ');
|
|
373
245
|
throw new Error(`Content blocked by model: ${finishReason}${blockedCategories ? ` - ${blockedCategories}` : ''}`);
|
|
374
246
|
}
|
|
375
|
-
|
|
376
|
-
const
|
|
247
|
+
// Every visible text part, not only the first: a turn can split its answer across parts.
|
|
248
|
+
const rawContent = (candidate.content?.parts ?? []).filter(part => part.text && !part.thought).map(part => part.text).join('');
|
|
249
|
+
const thinking = (candidate.content?.parts ?? []).filter(part => part.thought && part.text).map(part => part.text).join('');
|
|
377
250
|
const toolCalls = this.extractToolCalls(candidate.content?.parts, this.thoughtSignatureOrigin(modelName));
|
|
251
|
+
const reasoning = GeminiLLM_1.extractReasoning(candidate.content?.parts, this.thoughtSignatureOrigin(modelName));
|
|
378
252
|
// Check if we got empty content despite no blocking. A native tool call IS output, and a
|
|
379
253
|
// forced/clean tool-call turn legitimately carries no text at all — so tool calls
|
|
380
254
|
// satisfy this check just as text does.
|
|
381
|
-
|
|
255
|
+
// A rejected tool call is an answer the tool loop must correct, not missing output — but
|
|
256
|
+
// only for a request that declared tools. Without any, no tool loop can correct it, and
|
|
257
|
+
// the empty turn stays the error it always was, so failover can try another model.
|
|
258
|
+
const rejectedCall = params.tools?.length ? GeminiLLM_1.rejectedToolCallReason(finishReason) : undefined;
|
|
259
|
+
if (!rawContent && !thinking && !toolCalls && !rejectedCall) {
|
|
382
260
|
const usage = result.usageMetadata;
|
|
383
261
|
throw new Error(`No output received from model (finishReason: ${finishReason || 'none'}, ` +
|
|
384
262
|
`promptTokens: ${usage?.promptTokenCount || 0}, ` +
|
|
@@ -399,15 +277,8 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
399
277
|
thinkingContent = thinking;
|
|
400
278
|
}
|
|
401
279
|
const endTime = new Date();
|
|
402
|
-
|
|
403
|
-
|
|
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;
|
|
280
|
+
const geminiUsage = GeminiLLM_1.usageFromMetadata(result.usageMetadata);
|
|
281
|
+
const geminiCachedTokens = geminiUsage.cacheReadTokens ?? 0;
|
|
411
282
|
this.logCacheDiagnostics('non-streaming', this.buildCacheDiagContext(modelName, systemInstructionText, history.length), result.usageMetadata);
|
|
412
283
|
return {
|
|
413
284
|
success: true,
|
|
@@ -425,14 +296,14 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
425
296
|
role: 'assistant',
|
|
426
297
|
content: content,
|
|
427
298
|
thinking: thinkingContent || undefined,
|
|
428
|
-
toolCalls: toolCalls
|
|
299
|
+
toolCalls: toolCalls,
|
|
300
|
+
...(reasoning ? { reasoning } : {})
|
|
429
301
|
},
|
|
430
302
|
// Normalize the tool-call case and Gemini's "tried to call a tool but the call was
|
|
431
303
|
// unreadable" case; every other reason keeps Gemini's own value.
|
|
432
|
-
finish_reason: toolCalls ? CHAT_FINISH_REASON_TOOL_CALLS
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
index: 0
|
|
304
|
+
finish_reason: toolCalls ? CHAT_FINISH_REASON_TOOL_CALLS : (rejectedCall ?? (finishReason || "completed")),
|
|
305
|
+
index: 0,
|
|
306
|
+
...(rejectedCall && candidate.finishMessage ? { finishMessage: candidate.finishMessage } : {})
|
|
436
307
|
}],
|
|
437
308
|
usage: geminiUsage
|
|
438
309
|
},
|
|
@@ -448,8 +319,9 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
448
319
|
};
|
|
449
320
|
}
|
|
450
321
|
catch (e) {
|
|
451
|
-
|
|
452
|
-
|
|
322
|
+
// Node's fetch, which @google/genai uses, rejects with an AbortError when the signal fires.
|
|
323
|
+
if (this.IsCancellationError(e, params.cancellationToken)) {
|
|
324
|
+
return this.BuildCancelledChatResult(startTime, { error: e, signal: params.cancellationToken });
|
|
453
325
|
}
|
|
454
326
|
return {
|
|
455
327
|
success: false,
|
|
@@ -467,11 +339,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
467
339
|
};
|
|
468
340
|
}
|
|
469
341
|
}
|
|
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
342
|
/**
|
|
476
343
|
* Maps the neutral {@link ChatParams.tools} onto Gemini's `tools` / `toolConfig` request fields.
|
|
477
344
|
*
|
|
@@ -498,8 +365,9 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
498
365
|
const toolConfig = { functionCallingConfig: this.mapToolChoice(params.toolChoice) };
|
|
499
366
|
requestConfig.toolConfig = toolConfig;
|
|
500
367
|
}
|
|
501
|
-
|
|
502
|
-
|
|
368
|
+
// Gemini always allows parallel calls, so only a request to turn them off goes unmet.
|
|
369
|
+
if (params.parallelToolCalls === false) {
|
|
370
|
+
console.warn('Gemini provider does not support turning parallel tool calls off, ignoring parallelToolCalls=false');
|
|
503
371
|
}
|
|
504
372
|
}
|
|
505
373
|
/**
|
|
@@ -531,6 +399,18 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
531
399
|
thoughtSignatureOrigin(modelName) {
|
|
532
400
|
return `${this.ThoughtSignatureEndpoint}:${modelName}`;
|
|
533
401
|
}
|
|
402
|
+
/**
|
|
403
|
+
* The normalized finish reason for a tool call Gemini rejected — `MALFORMED_FUNCTION_CALL` (the
|
|
404
|
+
* call could not be read) or `UNEXPECTED_TOOL_CALL` (a call to a tool the request did not offer)
|
|
405
|
+
* — or undefined for any other finish reason.
|
|
406
|
+
*/
|
|
407
|
+
static rejectedToolCallReason(finishReason) {
|
|
408
|
+
switch (finishReason) {
|
|
409
|
+
case 'MALFORMED_FUNCTION_CALL': return CHAT_FINISH_REASON_MALFORMED_TOOL_CALL;
|
|
410
|
+
case 'UNEXPECTED_TOOL_CALL': return CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL;
|
|
411
|
+
default: return undefined;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
534
414
|
/**
|
|
535
415
|
* Pulls `functionCall` parts out of a Gemini candidate and normalizes them.
|
|
536
416
|
*
|
|
@@ -562,102 +442,170 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
562
442
|
}
|
|
563
443
|
return calls.length > 0 ? calls : undefined;
|
|
564
444
|
}
|
|
445
|
+
/**
|
|
446
|
+
* Attach the caller's cancellation token to a Gemini per-request config. @google/genai reads
|
|
447
|
+
* `GenerateContentConfig.abortSignal` and forwards it to the underlying `fetch` call, so an
|
|
448
|
+
* abort tears down the HTTP socket instead of merely abandoning the promise.
|
|
449
|
+
*/
|
|
565
450
|
applyCancellationToken(requestConfig, token) {
|
|
566
451
|
if (token) {
|
|
567
452
|
requestConfig.abortSignal = token;
|
|
568
453
|
}
|
|
569
454
|
}
|
|
570
|
-
/**
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
455
|
+
/**
|
|
456
|
+
* Model + field pairs already warned about, so a prompt that sets `temperature` on every call
|
|
457
|
+
* logs once per process instead of once per request.
|
|
458
|
+
*/
|
|
459
|
+
static { this._warnedUnsupportedSampling = new Set(); }
|
|
460
|
+
/**
|
|
461
|
+
* Builds the per-request generation options: sampling, stop sequences, seed, response format.
|
|
462
|
+
*
|
|
463
|
+
* Sampling fields depend on the model's version. Models before Gemini 3.6 keep the original
|
|
464
|
+
* shape (`temperature` defaulting to 0.5, `topP`, `topK`) because they still honor it. Every
|
|
465
|
+
* other model gets none of the three: Google ignores them since Gemini 3.6 Flash and upcoming
|
|
466
|
+
* models reject them with a 400, so a caller-supplied value is dropped with a one-time warning.
|
|
467
|
+
*
|
|
468
|
+
* A `ModelSpecific` response format is merged in after this gate, so it can still set these
|
|
469
|
+
* fields explicitly; that is the caller's deliberate override.
|
|
470
|
+
*/
|
|
471
|
+
buildGenerationOptions(params, modelName) {
|
|
472
|
+
const modelOptions = {};
|
|
473
|
+
if (AcceptsCustomSampling(modelName)) {
|
|
474
|
+
modelOptions.temperature = params.temperature ?? 0.5;
|
|
475
|
+
if (params.topP != null) {
|
|
476
|
+
modelOptions.topP = params.topP;
|
|
477
|
+
}
|
|
478
|
+
if (params.topK != null) {
|
|
479
|
+
modelOptions.topK = params.topK;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
this.warnUnsupportedSampling(modelName, 'temperature', params.temperature);
|
|
484
|
+
this.warnUnsupportedSampling(modelName, 'topP', params.topP);
|
|
485
|
+
this.warnUnsupportedSampling(modelName, 'topK', params.topK);
|
|
486
|
+
}
|
|
487
|
+
switch (params.responseFormat) {
|
|
488
|
+
case 'JSON':
|
|
489
|
+
modelOptions.responseMimeType = 'application/json';
|
|
490
|
+
break;
|
|
491
|
+
case 'ModelSpecific':
|
|
492
|
+
if (params.modelSpecificResponseFormat) {
|
|
493
|
+
Object.assign(modelOptions, params.modelSpecificResponseFormat);
|
|
494
|
+
}
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
if (params.stopSequences != null && params.stopSequences.length > 0) {
|
|
498
|
+
modelOptions.stopSequences = params.stopSequences;
|
|
499
|
+
}
|
|
500
|
+
if (params.seed != null) {
|
|
501
|
+
modelOptions.seed = params.seed;
|
|
574
502
|
}
|
|
503
|
+
// Gemini doesn't support these parameters - warn if provided
|
|
504
|
+
if (params.frequencyPenalty != null) {
|
|
505
|
+
console.warn('Gemini provider does not support frequencyPenalty parameter, ignoring');
|
|
506
|
+
}
|
|
507
|
+
if (params.presencePenalty != null) {
|
|
508
|
+
console.warn('Gemini provider does not support presencePenalty parameter, ignoring');
|
|
509
|
+
}
|
|
510
|
+
if (params.minP != null) {
|
|
511
|
+
console.warn('Gemini provider does not support minP parameter, ignoring');
|
|
512
|
+
}
|
|
513
|
+
return modelOptions;
|
|
575
514
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
515
|
+
warnUnsupportedSampling(modelName, field, value) {
|
|
516
|
+
if (value == null) {
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
const key = `${modelName}:${field}`;
|
|
520
|
+
if (GeminiLLM_1._warnedUnsupportedSampling.has(key)) {
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
GeminiLLM_1._warnedUnsupportedSampling.add(key);
|
|
524
|
+
console.warn(`Gemini model ${modelName} does not accept a custom ${field}; omitting it so the model uses its default sampling.`);
|
|
581
525
|
}
|
|
582
|
-
/**
|
|
583
|
-
|
|
584
|
-
|
|
526
|
+
/**
|
|
527
|
+
* Thinking settings a model rejected in this process, mapped to what was sent instead (`null`
|
|
528
|
+
* for no setting). Keyed by driver, model and setting, so a rejected `MINIMAL` does not stop
|
|
529
|
+
* `HIGH` being sent, and a rejection through one driver does not affect another.
|
|
530
|
+
*/
|
|
531
|
+
static { this._thinkingReplacements = new Map(); }
|
|
532
|
+
/** Thinking warnings already logged, so each is logged once per process. */
|
|
533
|
+
static { this._warnedThinking = new Set(); }
|
|
534
|
+
thinkingReplacementKey(modelName, config) {
|
|
535
|
+
return `${this.constructor.name}|${modelName}|${JSON.stringify(config)}`;
|
|
585
536
|
}
|
|
586
|
-
/**
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
537
|
+
/**
|
|
538
|
+
* Puts the `thinkingConfig` for `effortLevel` on the request (see {@link ResolveGeminiThinkingConfig}),
|
|
539
|
+
* or what replaced it after the model rejected it earlier in this process. Nothing is added when
|
|
540
|
+
* no effort is set; an effort that cannot be used is reported once.
|
|
541
|
+
*/
|
|
542
|
+
applyThinkingConfig(requestConfig, modelName, effortLevel) {
|
|
543
|
+
const resolution = ResolveGeminiThinkingConfig(modelName, effortLevel);
|
|
544
|
+
if (resolution.Ignored) {
|
|
545
|
+
this.warnThinkingOnce(`${modelName}:${resolution.Ignored}`, `Gemini: ${resolution.Ignored}; sending no thinking setting, so the model thinks at its default.`);
|
|
546
|
+
}
|
|
547
|
+
if (!resolution.Config) {
|
|
548
|
+
return;
|
|
591
549
|
}
|
|
592
|
-
|
|
593
|
-
|
|
550
|
+
const key = this.thinkingReplacementKey(modelName, resolution.Config);
|
|
551
|
+
const config = GeminiLLM_1._thinkingReplacements.has(key) ? GeminiLLM_1._thinkingReplacements.get(key) : resolution.Config;
|
|
552
|
+
if (config) {
|
|
553
|
+
requestConfig.thinkingConfig = config;
|
|
594
554
|
}
|
|
595
|
-
return 'Gemini request cancelled by caller';
|
|
596
555
|
}
|
|
597
556
|
/**
|
|
598
|
-
*
|
|
599
|
-
*
|
|
557
|
+
* Sends a request, and when it carried a thinking setting and Google answered 400, sends it once
|
|
558
|
+
* more with the setting's fallback (see {@link GeminiThinkingFallback}: `LOW` for a rejected
|
|
559
|
+
* `MINIMAL`, otherwise none). Which levels a model accepts varies (Gemini 3.8 Flash rejects
|
|
560
|
+
* `MINIMAL`), so an unsupported level must not fail the request. When the retry succeeds, the
|
|
561
|
+
* rejected setting is replaced for this driver and model for the rest of the process; when it also
|
|
562
|
+
* fails, the 400 had another cause, so the original error is thrown and nothing is remembered.
|
|
600
563
|
*/
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
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
|
-
};
|
|
564
|
+
async sendWithThinkingFallback(modelName, requestConfig, cancellationToken, send) {
|
|
565
|
+
try {
|
|
566
|
+
return await send(requestConfig);
|
|
567
|
+
}
|
|
568
|
+
catch (error) {
|
|
569
|
+
const { thinkingConfig, ...withoutThinking } = requestConfig;
|
|
570
|
+
if (!thinkingConfig || !(error instanceof ApiError) || error.status !== 400 || cancellationToken?.aborted) {
|
|
571
|
+
throw error;
|
|
645
572
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
};
|
|
573
|
+
const fallback = GeminiThinkingFallback(thinkingConfig);
|
|
574
|
+
let result;
|
|
575
|
+
try {
|
|
576
|
+
result = await send(fallback ? { ...withoutThinking, thinkingConfig: fallback } : withoutThinking);
|
|
651
577
|
}
|
|
652
|
-
|
|
653
|
-
|
|
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
|
-
};
|
|
578
|
+
catch {
|
|
579
|
+
throw error;
|
|
658
580
|
}
|
|
581
|
+
GeminiLLM_1._thinkingReplacements.set(this.thinkingReplacementKey(modelName, thinkingConfig), fallback ?? null);
|
|
582
|
+
this.warnThinkingOnce(this.thinkingReplacementKey(modelName, thinkingConfig), `Gemini model ${modelName} rejected thinking setting ${JSON.stringify(thinkingConfig)} (${error.message}); ` +
|
|
583
|
+
`sending ${fallback ? JSON.stringify(fallback) : 'no thinking setting'} instead for the rest of the process.`);
|
|
584
|
+
return result;
|
|
659
585
|
}
|
|
660
586
|
}
|
|
587
|
+
warnThinkingOnce(key, message) {
|
|
588
|
+
if (GeminiLLM_1._warnedThinking.has(key)) {
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
GeminiLLM_1._warnedThinking.add(key);
|
|
592
|
+
console.warn(message);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Normalizes Gemini usage to the {@link ModelUsage} contract.
|
|
596
|
+
*
|
|
597
|
+
* - `promptTokenCount` includes cached tokens, reported separately as `cachedContentTokenCount`,
|
|
598
|
+
* so the cached count is subtracted (clamped at 0) and recorded as `cacheReadTokens`. Gemini
|
|
599
|
+
* reports no separate cache-write charge.
|
|
600
|
+
* - `candidatesTokenCount` leaves out thinking, which Google counts in `thoughtsTokenCount` and
|
|
601
|
+
* bills as output, so completion tokens are the sum of the two.
|
|
602
|
+
*/
|
|
603
|
+
static usageFromMetadata(metadata) {
|
|
604
|
+
const cached = metadata?.cachedContentTokenCount ?? 0;
|
|
605
|
+
const usage = new ModelUsage(Math.max(0, (metadata?.promptTokenCount ?? 0) - cached), (metadata?.candidatesTokenCount ?? 0) + (metadata?.thoughtsTokenCount ?? 0));
|
|
606
|
+
usage.cacheReadTokens = cached;
|
|
607
|
+
return usage;
|
|
608
|
+
}
|
|
661
609
|
/**
|
|
662
610
|
* Reset streaming state for a new request
|
|
663
611
|
*/
|
|
@@ -668,7 +616,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
668
616
|
pendingContent: '',
|
|
669
617
|
thinkingComplete: false
|
|
670
618
|
};
|
|
671
|
-
this._streamingCancellationToken = null;
|
|
672
619
|
}
|
|
673
620
|
/**
|
|
674
621
|
* Create a streaming request for Gemini
|
|
@@ -676,8 +623,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
676
623
|
async createStreamingRequest(params) {
|
|
677
624
|
// Reset streaming state for new request
|
|
678
625
|
this.resetStreamingState();
|
|
679
|
-
this.throwIfCancelled(params.cancellationToken);
|
|
680
|
-
this._streamingCancellationToken = params.cancellationToken ?? null;
|
|
681
626
|
const modelName = params.model || "gemini-pro";
|
|
682
627
|
// Filter out system messages and extract system instruction content
|
|
683
628
|
const noSystemMessages = params.messages.filter(m => m.role !== 'system');
|
|
@@ -708,70 +653,22 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
708
653
|
if (finalMessageParts.length === 0) {
|
|
709
654
|
finalMessageParts = [{ text: '' }];
|
|
710
655
|
}
|
|
711
|
-
//
|
|
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);
|
|
656
|
+
// Sampling + response-format options, shaped for the model's version (see buildGenerationOptions)
|
|
657
|
+
const modelOptions = this.buildGenerationOptions(params, modelName);
|
|
754
658
|
// Ensure Gemini client is initialized
|
|
755
659
|
const client = await this.ensureGeminiClient();
|
|
756
660
|
// 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
|
-
//
|
|
759
|
-
// avoids sending a thinking level some models reject (see nonStreamingChatCompletion).
|
|
661
|
+
// per-request config since @google/genai's sendMessage config REPLACES the session config;
|
|
662
|
+
// so must thinkingConfig.
|
|
760
663
|
const requestConfig = { ...modelOptions };
|
|
761
664
|
if (systemInstructionText) {
|
|
762
665
|
requestConfig.systemInstruction = systemInstructionText;
|
|
763
666
|
}
|
|
667
|
+
this.applyThinkingConfig(requestConfig, modelName, params.effortLevel);
|
|
764
668
|
this.applyCancellationToken(requestConfig, params.cancellationToken);
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
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
|
-
});
|
|
669
|
+
// Send the latest user message (streaming); system prompt rides in requestConfig. A rejected
|
|
670
|
+
// request throws here, before any chunk, so the thinking fallback works as it does above.
|
|
671
|
+
const streamResult = await this.sendWithThinkingFallback(modelName, requestConfig, params.cancellationToken, config => client.chats.create({ model: modelName, history }).sendMessageStream({ message: finalMessageParts, config }));
|
|
775
672
|
// Return the stream for the for-await loop to work
|
|
776
673
|
return streamResult;
|
|
777
674
|
}
|
|
@@ -811,16 +708,10 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
811
708
|
if (chunk?.candidates?.[0]?.finishReason) {
|
|
812
709
|
finishReason = chunk.candidates[0].finishReason;
|
|
813
710
|
}
|
|
814
|
-
// Extract usage from chunk if available (appears on final chunk).
|
|
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.
|
|
711
|
+
// Extract usage from chunk if available (appears on final chunk).
|
|
818
712
|
let usage = null;
|
|
819
713
|
if (chunk.usageMetadata) {
|
|
820
|
-
|
|
821
|
-
const chunkNetPromptTokens = Math.max(0, (chunk.usageMetadata.promptTokenCount || 0) - chunkCachedTokens);
|
|
822
|
-
usage = new ModelUsage(chunkNetPromptTokens, chunk.usageMetadata.candidatesTokenCount || 0);
|
|
823
|
-
usage.cacheReadTokens = chunkCachedTokens;
|
|
714
|
+
usage = GeminiLLM_1.usageFromMetadata(chunk.usageMetadata);
|
|
824
715
|
// Usage only appears on the final chunk — log the cache diagnostic once here.
|
|
825
716
|
this.logCacheDiagnostics('streaming', this._cacheDiagContext, chunk.usageMetadata);
|
|
826
717
|
}
|
|
@@ -965,14 +856,6 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
965
856
|
* Create the final response from streaming results for Gemini
|
|
966
857
|
*/
|
|
967
858
|
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
859
|
// Extract finish reason from last chunk if available
|
|
977
860
|
let finishReason = 'stop';
|
|
978
861
|
if (lastChunk?.candidates && lastChunk.candidates.length > 0 && lastChunk.candidates[0].finishReason) {
|
|
@@ -1146,6 +1029,51 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
1146
1029
|
const foreign = signatureOrigin !== undefined && typeof origin === 'string' && origin !== signatureOrigin;
|
|
1147
1030
|
return foreign ? GEMINI_INJECTED_CALL_THOUGHT_SIGNATURE : signature;
|
|
1148
1031
|
}
|
|
1032
|
+
/**
|
|
1033
|
+
* A turn's thought parts and signed text parts, as replayable reasoning.
|
|
1034
|
+
*
|
|
1035
|
+
* Thought parts are kept with their signature when they have one. Text parts are kept only when
|
|
1036
|
+
* at least one of them is signed, and then all of them, in order — the replay rebuilds the
|
|
1037
|
+
* turn's text from these blocks, so each signature lands back on the text it was minted for.
|
|
1038
|
+
* Function-call signatures travel on the calls themselves (see {@link extractToolCalls}).
|
|
1039
|
+
*
|
|
1040
|
+
* @param parts The candidate's content parts
|
|
1041
|
+
* @param signatureOrigin Where this response's signatures validate (see {@link thoughtSignatureOrigin})
|
|
1042
|
+
* @returns The blocks, or undefined when the turn had nothing to replay
|
|
1043
|
+
*/
|
|
1044
|
+
static extractReasoning(parts, signatureOrigin) {
|
|
1045
|
+
const all = parts ?? [];
|
|
1046
|
+
const signature = (part) => (part.thoughtSignature ? { signature: part.thoughtSignature } : {});
|
|
1047
|
+
const blocks = all
|
|
1048
|
+
.filter((part) => part.thought && part.text)
|
|
1049
|
+
.map((part) => ({ provider: GEMINI_REASONING_PROVIDER, kind: 'thought', text: part.text, ...signature(part), origin: signatureOrigin }));
|
|
1050
|
+
// Gemini can put a turn's signature on a trailing part with empty text; it has to come back too.
|
|
1051
|
+
const textParts = all.filter((part) => typeof part.text === 'string' && !part.thought && !part.functionCall
|
|
1052
|
+
&& (part.text.length > 0 || !!part.thoughtSignature));
|
|
1053
|
+
if (textParts.some((part) => part.thoughtSignature)) {
|
|
1054
|
+
blocks.push(...textParts.map((part) => ({ provider: GEMINI_REASONING_PROVIDER, kind: 'signed_text', text: part.text, ...signature(part), origin: signatureOrigin })));
|
|
1055
|
+
}
|
|
1056
|
+
return blocks.length > 0 ? blocks : undefined;
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* The parts that replay a model turn's own reasoning: its thought parts, and — when its text
|
|
1060
|
+
* parts were signed and the message text is still exactly theirs — those text parts with their
|
|
1061
|
+
* signatures. `text` is undefined when the message's content should be mapped as usual: no
|
|
1062
|
+
* signed text, or text that was changed after the turn (compaction), which a signature would
|
|
1063
|
+
* no longer match. Blocks from another provider, or signed where this request is not going,
|
|
1064
|
+
* are dropped — a foreign signature is a hard 400.
|
|
1065
|
+
*/
|
|
1066
|
+
static reasoningPartsForReplay(message, signatureOrigin) {
|
|
1067
|
+
const usable = (message.reasoning ?? []).filter((block) => block.provider === GEMINI_REASONING_PROVIDER
|
|
1068
|
+
&& !(signatureOrigin !== undefined && block.origin !== undefined && block.origin !== signatureOrigin));
|
|
1069
|
+
const toPart = (block, thought) => ({ text: block.text ?? '', ...(thought ? { thought: true } : {}), ...(block.signature ? { thoughtSignature: block.signature } : {}) });
|
|
1070
|
+
const thoughts = usable.filter((block) => block.kind === 'thought').map((block) => toPart(block, true));
|
|
1071
|
+
const signedText = usable.filter((block) => block.kind === 'signed_text');
|
|
1072
|
+
const textMatches = typeof message.content === 'string'
|
|
1073
|
+
&& signedText.length > 0
|
|
1074
|
+
&& signedText.map((block) => block.text ?? '').join('').trim() === message.content.trim();
|
|
1075
|
+
return { thoughts, text: textMatches ? signedText.map((block) => toPart(block, false)) : undefined };
|
|
1076
|
+
}
|
|
1149
1077
|
/**
|
|
1150
1078
|
* Maps one MJ message to a Gemini history entry.
|
|
1151
1079
|
*
|
|
@@ -1154,7 +1082,10 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
1154
1082
|
* call's thought signature from anywhere else is swapped for the placeholder.
|
|
1155
1083
|
*/
|
|
1156
1084
|
static MapMJMessageToGeminiHistoryEntry(message, signatureOrigin) {
|
|
1157
|
-
|
|
1085
|
+
// A model turn replays its own thoughts first, then its text, then its calls — the order
|
|
1086
|
+
// Gemini produced them in.
|
|
1087
|
+
const replay = message.role === 'assistant' ? GeminiLLM_1.reasoningPartsForReplay(message, signatureOrigin) : { thoughts: [] };
|
|
1088
|
+
const parts = [...replay.thoughts, ...(replay.text ?? GeminiLLM_1.MapMJContentToGeminiParts(message.content))];
|
|
1158
1089
|
// An assistant turn that called tools must replay those calls as `functionCall` parts so the
|
|
1159
1090
|
// `functionResponse` parts that follow have something to pair with.
|
|
1160
1091
|
if (message.toolCalls?.length) {
|
|
@@ -1166,8 +1097,9 @@ let GeminiLLM = GeminiLLM_1 = class GeminiLLM extends BaseLLM {
|
|
|
1166
1097
|
}
|
|
1167
1098
|
}
|
|
1168
1099
|
// Gemini rejects an empty part list, and a pure tool-call turn has no prose — drop the empty
|
|
1169
|
-
// text part that content mapping produces once real parts are carrying the turn.
|
|
1170
|
-
|
|
1100
|
+
// text part that content mapping produces once real parts are carrying the turn. An empty
|
|
1101
|
+
// part that carries a signature is the model's own, and stays.
|
|
1102
|
+
const meaningfulParts = parts.length > 1 ? parts.filter(p => p.text !== '' || !!p.thoughtSignature) : parts;
|
|
1171
1103
|
return {
|
|
1172
1104
|
role: message.role === 'assistant' ? 'model' : 'user', // google calls all messages other than the replies from the model 'user' which would include the system prompt
|
|
1173
1105
|
parts: meaningfulParts.length > 0 ? meaningfulParts : [{ text: '' }]
|