@langchain/google 0.2.3 → 0.2.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/CHANGELOG.md +40 -0
- package/dist/chat_models/base.cjs +1 -1
- package/dist/chat_models/base.cjs.map +1 -1
- package/dist/chat_models/base.js +1 -1
- package/dist/chat_models/index.cjs.map +1 -1
- package/dist/chat_models/node.cjs +2 -1
- package/dist/chat_models/node.cjs.map +1 -1
- package/dist/chat_models/node.js +2 -1
- package/dist/chat_models/node.js.map +1 -1
- package/dist/clients/index.cjs.map +1 -1
- package/dist/clients/node.cjs.map +1 -1
- package/dist/converters/messages.cjs +125 -51
- package/dist/converters/messages.cjs.map +1 -1
- package/dist/converters/messages.js +125 -51
- package/dist/converters/messages.js.map +1 -1
- package/dist/converters/params.cjs +14 -10
- package/dist/converters/params.cjs.map +1 -1
- package/dist/converters/params.js +14 -10
- package/dist/converters/params.js.map +1 -1
- package/dist/converters/tools.cjs +8 -5
- package/dist/converters/tools.cjs.map +1 -1
- package/dist/converters/tools.js +8 -5
- package/dist/converters/tools.js.map +1 -1
- package/dist/utils/gcp-auth.cjs +13 -11
- package/dist/utils/gcp-auth.cjs.map +1 -1
- package/dist/utils/gcp-auth.js +13 -11
- package/dist/utils/gcp-auth.js.map +1 -1
- package/dist/utils/stream_events.cjs +45 -44
- package/dist/utils/stream_events.cjs.map +1 -1
- package/dist/utils/stream_events.js +45 -44
- package/dist/utils/stream_events.js.map +1 -1
- package/package.json +8 -8
|
@@ -110,6 +110,24 @@ const geminiContentBlockConverter = {
|
|
|
110
110
|
throw new InvalidInputError(`File content blocks with source_type "${block.source_type}" are not supported for ChatGoogle. Supported source types are: "base64", "url", "id", "text".`);
|
|
111
111
|
}
|
|
112
112
|
};
|
|
113
|
+
const MEDIA_BLOCK_TYPES = /* @__PURE__ */ new Set([
|
|
114
|
+
"media",
|
|
115
|
+
"image",
|
|
116
|
+
"audio",
|
|
117
|
+
"video",
|
|
118
|
+
"file",
|
|
119
|
+
"text-plain"
|
|
120
|
+
]);
|
|
121
|
+
function isMediaContentBlock(item) {
|
|
122
|
+
if (typeof item !== "object" || item === null) return false;
|
|
123
|
+
if (isDataContentBlock(item)) return item.source_type !== "text";
|
|
124
|
+
if ("image_url" in item || "inlineData" in item || "fileData" in item) return true;
|
|
125
|
+
return MEDIA_BLOCK_TYPES.has(item.type);
|
|
126
|
+
}
|
|
127
|
+
function stripMediaBlocksForFunctionResponse(content) {
|
|
128
|
+
if (!Array.isArray(content)) return content;
|
|
129
|
+
return content.filter((item) => !isMediaContentBlock(item));
|
|
130
|
+
}
|
|
113
131
|
function convertStandardDataContentBlockToGeminiPart(block) {
|
|
114
132
|
function uint8arrayToString(data) {
|
|
115
133
|
return btoa(Array.from(data).map((byte) => String.fromCharCode(byte)).join(""));
|
|
@@ -146,6 +164,11 @@ function convertStandardVideoContentBlockToGeminiPart(block) {
|
|
|
146
164
|
if (ret && block.metadata && "videoMetadata" in block.metadata) ret.videoMetadata = block.metadata.videoMetadata;
|
|
147
165
|
return ret;
|
|
148
166
|
}
|
|
167
|
+
function convertStandardReasoningBlockToGeminiPart(block) {
|
|
168
|
+
const ret = "reasoningContentBlock" in block && block.reasoningContentBlock ? convertStandardContentBlockToGeminiPart(block.reasoningContentBlock) : { text: block.reasoning };
|
|
169
|
+
if (ret) ret.thought = true;
|
|
170
|
+
return ret;
|
|
171
|
+
}
|
|
149
172
|
/**
|
|
150
173
|
* Converts a single LangChain standard content block (v1 format)
|
|
151
174
|
* into a Gemini.Part.
|
|
@@ -153,15 +176,23 @@ function convertStandardVideoContentBlockToGeminiPart(block) {
|
|
|
153
176
|
* This is intended to be called from `convertStandardContentMessageToGeminiContent`
|
|
154
177
|
*/
|
|
155
178
|
function convertStandardContentBlockToGeminiPart(block) {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
179
|
+
function baseGeminiPart() {
|
|
180
|
+
switch (block.type) {
|
|
181
|
+
case "text": return { text: block.text };
|
|
182
|
+
case "reasoning": return convertStandardReasoningBlockToGeminiPart(block);
|
|
183
|
+
case "image":
|
|
184
|
+
case "audio":
|
|
185
|
+
case "text-plain":
|
|
186
|
+
case "file": return convertStandardDataContentBlockToGeminiPart(block);
|
|
187
|
+
case "video": return convertStandardVideoContentBlockToGeminiPart(block);
|
|
188
|
+
default: return null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const ret = baseGeminiPart();
|
|
192
|
+
if (ret) {
|
|
193
|
+
if ("thoughtSignature" in block) ret.thoughtSignature = block.thoughtSignature;
|
|
164
194
|
}
|
|
195
|
+
return ret;
|
|
165
196
|
}
|
|
166
197
|
/**
|
|
167
198
|
* Converts a single LangChain message with standard content blocks (v1 format) to Gemini Content.
|
|
@@ -182,17 +213,21 @@ function convertStandardContentMessageToGeminiContent(message, messages) {
|
|
|
182
213
|
else if (msgRole === "function" || msgRole === "tool") role = "user";
|
|
183
214
|
else role = "user";
|
|
184
215
|
} else role = "user";
|
|
185
|
-
|
|
216
|
+
let parts = [];
|
|
186
217
|
(Array.isArray(message.contentBlocks) ? message.contentBlocks : []).forEach((block) => {
|
|
187
218
|
const part = convertStandardContentBlockToGeminiPart(message.additional_kwargs.originalTextContentBlock || block);
|
|
188
219
|
if (part) parts.push(part);
|
|
189
220
|
});
|
|
190
|
-
if (AIMessage.isInstance(message) && message.tool_calls?.length) for (const toolCall of message.tool_calls)
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
221
|
+
if (AIMessage.isInstance(message) && message.tool_calls?.length) for (const toolCall of message.tool_calls) {
|
|
222
|
+
const part = { functionCall: {
|
|
223
|
+
name: toolCall.name,
|
|
224
|
+
args: toolCall.args ?? {}
|
|
225
|
+
} };
|
|
226
|
+
if ("thoughtSignature" in toolCall) part.thoughtSignature = toolCall.thoughtSignature;
|
|
227
|
+
parts.push(part);
|
|
228
|
+
}
|
|
194
229
|
if (ToolMessage.isInstance(message) && message.tool_call_id) {
|
|
195
|
-
const responseContent =
|
|
230
|
+
const responseContent = stripMediaBlocksForFunctionResponse(message.content);
|
|
196
231
|
const matchedToolCall = messages.filter(AIMessage.isInstance).find((msg) => msg.tool_calls?.find((tc) => tc.id === message.tool_call_id))?.tool_calls?.find((tc) => tc.id === message.tool_call_id);
|
|
197
232
|
const isGeneratedId = message.tool_call_id.startsWith("lc-tool-call-");
|
|
198
233
|
parts.push({ functionResponse: {
|
|
@@ -200,6 +235,7 @@ function convertStandardContentMessageToGeminiContent(message, messages) {
|
|
|
200
235
|
name: matchedToolCall?.name ?? message.name ?? "unknown",
|
|
201
236
|
response: { result: responseContent }
|
|
202
237
|
} });
|
|
238
|
+
parts = parts.filter((part) => "functionResponse" in part);
|
|
203
239
|
}
|
|
204
240
|
if (parts.length === 0) return null;
|
|
205
241
|
return {
|
|
@@ -207,14 +243,7 @@ function convertStandardContentMessageToGeminiContent(message, messages) {
|
|
|
207
243
|
parts
|
|
208
244
|
};
|
|
209
245
|
}
|
|
210
|
-
|
|
211
|
-
* Converts a single LangChain message with legacy content blocks (v0 format) to Gemini Content.
|
|
212
|
-
* This handles messages that have `response_metadata.output_version === "v0"`.
|
|
213
|
-
*
|
|
214
|
-
* This is intended to be called from `convertMessagesToGeminiContent`
|
|
215
|
-
*/
|
|
216
|
-
function convertLegacyContentMessageToGeminiContent(message, messages) {
|
|
217
|
-
if (SystemMessage.isInstance(message)) return null;
|
|
246
|
+
function convertLegacyPartToGeminiPart(item) {
|
|
218
247
|
/**
|
|
219
248
|
* @deprecated - This is for use by `convertLegacyContentMessageToGeminiContent` only
|
|
220
249
|
*/
|
|
@@ -300,6 +329,48 @@ function convertLegacyContentMessageToGeminiContent(message, messages) {
|
|
|
300
329
|
supplementVideoMetadata(content, ret);
|
|
301
330
|
return ret;
|
|
302
331
|
}
|
|
332
|
+
function baseGeminiPart() {
|
|
333
|
+
if (typeof item === "string") return { text: item };
|
|
334
|
+
else if (typeof item === "object" && item !== null) {
|
|
335
|
+
if (isMessageContentText(item)) return { text: item.text };
|
|
336
|
+
else if (isDataContentBlock(item)) return convertToProviderContentBlock(item, geminiContentBlockConverter);
|
|
337
|
+
else if ("type" in item && item?.type === "functionCall") {
|
|
338
|
+
const { type, functionCall, ...etc } = item;
|
|
339
|
+
return {
|
|
340
|
+
...etc,
|
|
341
|
+
functionCall
|
|
342
|
+
};
|
|
343
|
+
} else if ("type" in item && item?.type === "executableCode") {
|
|
344
|
+
const { type, executableCode, ...etc } = item;
|
|
345
|
+
return {
|
|
346
|
+
...etc,
|
|
347
|
+
executableCode
|
|
348
|
+
};
|
|
349
|
+
} else if ("type" in item && item?.type === "codeExecutionResult") {
|
|
350
|
+
const { type, codeExecutionResult, ...etc } = item;
|
|
351
|
+
return {
|
|
352
|
+
...etc,
|
|
353
|
+
codeExecutionResult
|
|
354
|
+
};
|
|
355
|
+
} else if (isMessageContentImageUrl(item)) return messageContentImageUrl(item);
|
|
356
|
+
else if (isMessageContentMedia(item)) return messageContentMedia(item);
|
|
357
|
+
}
|
|
358
|
+
return item;
|
|
359
|
+
}
|
|
360
|
+
const ret = baseGeminiPart();
|
|
361
|
+
const itemRecord = item;
|
|
362
|
+
if ("thought" in itemRecord) ret.thought = itemRecord.thought;
|
|
363
|
+
if ("thoughtSignature" in itemRecord) ret.thoughtSignature = itemRecord.thoughtSignature;
|
|
364
|
+
return ret;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Converts a single LangChain message with legacy content blocks (v0 format) to Gemini Content.
|
|
368
|
+
* This handles messages that have `response_metadata.output_version === "v0"`.
|
|
369
|
+
*
|
|
370
|
+
* This is intended to be called from `convertMessagesToGeminiContent`
|
|
371
|
+
*/
|
|
372
|
+
function convertLegacyContentMessageToGeminiContent(message, messages) {
|
|
373
|
+
if (SystemMessage.isInstance(message)) return null;
|
|
303
374
|
const role = iife(() => {
|
|
304
375
|
if (HumanMessage.isInstance(message)) return "user";
|
|
305
376
|
else if (AIMessage.isInstance(message)) return "model";
|
|
@@ -315,34 +386,12 @@ function convertLegacyContentMessageToGeminiContent(message, messages) {
|
|
|
315
386
|
let parts = [];
|
|
316
387
|
if (typeof message.content === "string") {
|
|
317
388
|
if (message.content.trim()) parts.push({ text: message.content });
|
|
318
|
-
} else if (Array.isArray(message.content)) {
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
else if (isDataContentBlock(item)) parts.push(convertToProviderContentBlock(item, geminiContentBlockConverter));
|
|
322
|
-
else if (item?.type === "functionCall") {
|
|
323
|
-
const { type, functionCall, ...etc } = item;
|
|
324
|
-
parts.push({
|
|
325
|
-
...etc,
|
|
326
|
-
functionCall
|
|
327
|
-
});
|
|
328
|
-
} else if (item?.type === "executableCode") {
|
|
329
|
-
const { type, executableCode, ...etc } = item;
|
|
330
|
-
parts.push({
|
|
331
|
-
...etc,
|
|
332
|
-
executableCode
|
|
333
|
-
});
|
|
334
|
-
} else if (item?.type === "codeExecutionResult") {
|
|
335
|
-
const { type, codeExecutionResult, ...etc } = item;
|
|
336
|
-
parts.push({
|
|
337
|
-
...etc,
|
|
338
|
-
codeExecutionResult
|
|
339
|
-
});
|
|
340
|
-
} else if (isMessageContentImageUrl(item)) parts.push(messageContentImageUrl(item));
|
|
341
|
-
else if (isMessageContentMedia(item)) parts.push(messageContentMedia(item));
|
|
342
|
-
else parts.push(item);
|
|
389
|
+
} else if (Array.isArray(message.content)) for (const item of message.content) {
|
|
390
|
+
const part = convertLegacyPartToGeminiPart(item);
|
|
391
|
+
parts.push(part);
|
|
343
392
|
}
|
|
344
393
|
if (ToolMessage.isInstance(message) && message.tool_call_id) {
|
|
345
|
-
const responseContent =
|
|
394
|
+
const responseContent = stripMediaBlocksForFunctionResponse(message.content);
|
|
346
395
|
const aiMsg = messages.filter(AIMessage.isInstance).find((msg) => msg.tool_calls?.find((tc) => tc.id === message.tool_call_id));
|
|
347
396
|
if (!aiMsg) throw new ToolCallNotFoundError(message.tool_call_id);
|
|
348
397
|
const isGeneratedId = message.tool_call_id.startsWith("lc-tool-call-");
|
|
@@ -352,7 +401,7 @@ function convertLegacyContentMessageToGeminiContent(message, messages) {
|
|
|
352
401
|
name: matchedToolCall?.name ?? message.name ?? "unknown",
|
|
353
402
|
response: { result: responseContent }
|
|
354
403
|
} });
|
|
355
|
-
parts = parts.filter((part) => "functionResponse" in part);
|
|
404
|
+
parts = parts.filter((part) => "functionResponse" in part || "inlineData" in part || "fileData" in part);
|
|
356
405
|
}
|
|
357
406
|
if (parts.length > 0) return {
|
|
358
407
|
role,
|
|
@@ -406,13 +455,38 @@ const convertMessagesToGeminiContents = (messages) => {
|
|
|
406
455
|
});
|
|
407
456
|
if (content) {
|
|
408
457
|
const prev = contents[contents.length - 1];
|
|
409
|
-
if (prev
|
|
410
|
-
|
|
458
|
+
if (canMergeInto(prev, content) && content.parts) {
|
|
459
|
+
prev.parts ??= [];
|
|
460
|
+
prev.parts.push(...content.parts);
|
|
461
|
+
} else contents.push(content);
|
|
411
462
|
}
|
|
412
463
|
}
|
|
413
464
|
return contents;
|
|
414
465
|
};
|
|
415
466
|
/**
|
|
467
|
+
* Returns true if any part of the given content is a functionResponse part
|
|
468
|
+
* (i.e. it was produced from a ToolMessage).
|
|
469
|
+
*/
|
|
470
|
+
function hasFunctionResponse(content) {
|
|
471
|
+
return content.parts?.some((part) => "functionResponse" in part) === true;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Adjacent same-role contents merge only when they are the same kind of
|
|
475
|
+
* turn:
|
|
476
|
+
*
|
|
477
|
+
* - Both carry functionResponse parts (a run of tool responses answering
|
|
478
|
+
* one model turn's parallel calls): the API requires those to share a
|
|
479
|
+
* single `user` content whose part count matches the call count.
|
|
480
|
+
* - Neither does (plain text turns): coalesced as before #11444.
|
|
481
|
+
*
|
|
482
|
+
* A functionResponse turn never merges with a plain one: a `user` content
|
|
483
|
+
* mixing the two is rejected by newer Gemini models and corrupts
|
|
484
|
+
* generation on older ones.
|
|
485
|
+
*/
|
|
486
|
+
function canMergeInto(prev, content) {
|
|
487
|
+
return prev !== void 0 && prev.role === content.role && hasFunctionResponse(prev) === hasFunctionResponse(content);
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
416
490
|
* Converts LangChain system messages to Gemini API system instruction format.
|
|
417
491
|
*
|
|
418
492
|
* This converter extracts system messages from a message array and transforms them
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","names":["uuidv4"],"sources":["../../src/converters/messages.ts"],"sourcesContent":["import {\n BaseMessage,\n AIMessage,\n isDataContentBlock,\n ContentBlock,\n parseBase64DataUrl,\n SystemMessage,\n HumanMessage,\n ToolMessage,\n ChatMessage,\n StandardContentBlockConverter,\n convertToProviderContentBlock,\n type Data,\n UsageMetadata,\n InputTokenDetails,\n OutputTokenDetails,\n ModalitiesTokenDetails,\n MessageContentImageUrl,\n MessageContentComplex,\n MessageContentText,\n} from \"@langchain/core/messages\";\nimport { v4 as uuidv4 } from \"@langchain/core/utils/uuid\";\nimport { Converter } from \"@langchain/core/utils/format\";\nimport type { Gemini } from \"../chat_models/types.js\";\nimport { iife } from \"../utils/misc.js\";\nimport { InvalidInputError, ToolCallNotFoundError } from \"../utils/errors.js\";\n\n/**\n * Standard content block converter for Google Gemini API.\n * Converts deprecated Data content blocks to Gemini Part format.\n *\n * @deprecated This converter is for backward compatibility with older message formats.\n * Use ContentBlock.Multimodal.Standard instead.\n */\nexport const geminiContentBlockConverter: StandardContentBlockConverter<{\n text: Gemini.Part;\n image: Gemini.Part;\n audio: Gemini.Part;\n file: Gemini.Part;\n}> = {\n providerName: \"ChatGoogle\",\n\n fromStandardTextBlock(block: Data.StandardTextBlock): Gemini.Part {\n return { text: block.text };\n },\n\n fromStandardImageBlock(block: Data.StandardImageBlock): Gemini.Part {\n if (isDataContentBlock(block)) {\n if (block.source_type === \"base64\") {\n if (!block.mime_type) {\n throw new InvalidInputError(\n \"mime_type is required for base64 image blocks\"\n );\n }\n const dataStr =\n typeof block.data === \"string\"\n ? block.data\n : typeof block.data === \"object\" && block.data !== null\n ? // Convert Uint8Array to base64 string\n btoa(\n Array.from(block.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n )\n : String(block.data);\n return {\n inlineData: {\n mimeType: block.mime_type,\n data: dataStr,\n },\n };\n }\n\n if (block.source_type === \"url\") {\n // Check if it's a data URL\n const parsed = parseBase64DataUrl({ dataUrl: block.url });\n if (parsed) {\n const dataStr =\n typeof parsed.data === \"string\"\n ? parsed.data\n : // Convert Uint8Array to base64 string\n btoa(\n Array.from(parsed.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n return {\n inlineData: {\n mimeType: parsed.mime_type || block.mime_type || \"image/jpeg\",\n data: dataStr,\n },\n };\n }\n // Otherwise, treat as file URI\n return {\n fileData: {\n mimeType: block.mime_type || \"image/jpeg\",\n fileUri: block.url,\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n fileData: {\n mimeType: block.mime_type || \"image/jpeg\",\n fileUri: block.id,\n },\n };\n }\n }\n\n throw new InvalidInputError(\n `Image content blocks with source_type \"${\n (block as Data.DataContentBlock).source_type\n }\" are not supported for ChatGoogle. Supported source types are: \"base64\", \"url\", \"id\".`\n );\n },\n\n fromStandardAudioBlock(block: Data.StandardAudioBlock): Gemini.Part {\n if (isDataContentBlock(block)) {\n if (block.source_type === \"base64\") {\n if (!block.mime_type) {\n throw new InvalidInputError(\n \"mime_type is required for base64 audio blocks\"\n );\n }\n const dataStr =\n typeof block.data === \"string\"\n ? block.data\n : typeof block.data === \"object\" && block.data !== null\n ? // Convert Uint8Array to base64 string\n btoa(\n Array.from(block.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n )\n : String(block.data);\n return {\n inlineData: {\n mimeType: block.mime_type,\n data: dataStr,\n },\n };\n }\n\n if (block.source_type === \"url\") {\n // Check if it's a data URL\n const parsed = parseBase64DataUrl({ dataUrl: block.url });\n if (parsed) {\n const dataStr =\n typeof parsed.data === \"string\"\n ? parsed.data\n : // Convert Uint8Array to base64 string\n btoa(\n Array.from(parsed.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n return {\n inlineData: {\n mimeType: parsed.mime_type || block.mime_type || \"audio/mpeg\",\n data: dataStr,\n },\n };\n }\n // Otherwise, treat as file URI\n return {\n fileData: {\n mimeType: block.mime_type || \"audio/mpeg\",\n fileUri: block.url,\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n fileData: {\n mimeType: block.mime_type || \"audio/mpeg\",\n fileUri: block.id,\n },\n };\n }\n }\n\n throw new InvalidInputError(\n `Audio content blocks with source_type \"${\n (block as Data.DataContentBlock).source_type\n }\" are not supported for ChatGoogle. Supported source types are: \"base64\", \"url\", \"id\".`\n );\n },\n\n fromStandardFileBlock(block: Data.StandardFileBlock): Gemini.Part {\n if (isDataContentBlock(block)) {\n if (block.source_type === \"base64\") {\n if (!block.mime_type) {\n throw new InvalidInputError(\n \"mime_type is required for base64 file blocks\"\n );\n }\n const dataStr =\n typeof block.data === \"string\"\n ? block.data\n : typeof block.data === \"object\" && block.data !== null\n ? // Convert Uint8Array to base64 string\n btoa(\n Array.from(block.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n )\n : String(block.data);\n return {\n inlineData: {\n mimeType: block.mime_type,\n data: dataStr,\n },\n };\n }\n\n if (block.source_type === \"url\") {\n // Check if it's a data URL\n const parsed = parseBase64DataUrl({ dataUrl: block.url });\n if (parsed) {\n const dataStr =\n typeof parsed.data === \"string\"\n ? parsed.data\n : // Convert Uint8Array to base64 string\n btoa(\n Array.from(parsed.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n return {\n inlineData: {\n mimeType:\n parsed.mime_type ||\n block.mime_type ||\n \"application/octet-stream\",\n data: dataStr,\n },\n };\n }\n // Otherwise, treat as file URI\n return {\n fileData: {\n mimeType: block.mime_type || \"application/octet-stream\",\n fileUri: block.url,\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n fileData: {\n mimeType: block.mime_type || \"application/octet-stream\",\n fileUri: block.id,\n },\n };\n }\n }\n\n // Handle text source type (for plain text file blocks)\n if (\n \"source_type\" in block &&\n block.source_type === \"text\" &&\n \"text\" in block\n ) {\n return {\n text: block.text,\n };\n }\n\n throw new InvalidInputError(\n `File content blocks with source_type \"${\n (block as Data.DataContentBlock).source_type\n }\" are not supported for ChatGoogle. Supported source types are: \"base64\", \"url\", \"id\", \"text\".`\n );\n },\n};\n\nfunction convertStandardDataContentBlockToGeminiPart(\n block: ContentBlock.Multimodal.Data\n): Gemini.Part | null {\n function uint8arrayToString(data: Uint8Array): string {\n return btoa(\n Array.from(data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n }\n\n function extractMimeType(str: string): {\n mimeType: string | null;\n data: string | null;\n } {\n if (str.startsWith(\"data:\")) {\n return {\n mimeType: str.split(\":\")[1].split(\";\")[0],\n data: str.split(\",\")[1],\n };\n }\n return {\n mimeType: null,\n data: null,\n };\n }\n\n if (\"mimeType\" in block && \"data\" in block) {\n const mimeType = block.mimeType!;\n const data: string =\n typeof block.data === \"string\"\n ? block.data\n : uint8arrayToString(block.data!);\n return {\n inlineData: {\n mimeType,\n data,\n },\n };\n } else if (\"mimeType\" in block && \"url\" in block) {\n const mimeType = block.mimeType!;\n const fileUri = block.url!;\n return {\n fileData: {\n mimeType,\n fileUri,\n },\n };\n } else if (\"url\" in block && block.url?.startsWith(\"data:\")) {\n const { mimeType, data } = extractMimeType(block.url!);\n if (mimeType && data) {\n return {\n inlineData: {\n mimeType,\n data,\n },\n };\n }\n }\n // FIXME - report this somehow?\n return null;\n}\n\nfunction convertStandardVideoContentBlockToGeminiPart(\n block: ContentBlock.Multimodal.Video\n): Gemini.Part | null {\n const ret: Gemini.Part | null =\n convertStandardDataContentBlockToGeminiPart(block);\n if (ret && block.metadata && \"videoMetadata\" in block.metadata) {\n (ret as Gemini.Part.FileData).videoMetadata = block.metadata.videoMetadata!;\n }\n return ret;\n}\n\n/**\n * Converts a single LangChain standard content block (v1 format)\n * into a Gemini.Part.\n *\n * This is intended to be called from `convertStandardContentMessageToGeminiContent`\n */\nfunction convertStandardContentBlockToGeminiPart(\n block: ContentBlock.Standard\n): Gemini.Part | null {\n switch (block.type) {\n case \"text\":\n return { text: block.text };\n case \"image\":\n case \"audio\":\n case \"text-plain\":\n case \"file\":\n return convertStandardDataContentBlockToGeminiPart(block);\n case \"video\":\n return convertStandardVideoContentBlockToGeminiPart(block);\n default:\n return null;\n }\n}\n\n/**\n * Converts a single LangChain message with standard content blocks (v1 format) to Gemini Content.\n * This handles messages that have `response_metadata.output_version === \"v1\"`.\n *\n * This is intended to be called from `convertMessagesToGeminiContent`\n */\nfunction convertStandardContentMessageToGeminiContent(\n message: BaseMessage,\n messages: BaseMessage[]\n): Gemini.Content | null {\n // Skip system messages - they're handled separately\n if (SystemMessage.isInstance(message)) {\n return null;\n }\n\n let role: Gemini.Role;\n if (HumanMessage.isInstance(message)) {\n role = \"user\";\n } else if (AIMessage.isInstance(message)) {\n role = \"model\";\n } else if (ToolMessage.isInstance(message)) {\n // Tool messages in Gemini were represented as function responses, but now are \"user\"\n role = \"user\";\n } else if (ChatMessage.isInstance(message)) {\n // Map ChatMessage roles to Gemini roles\n const msgRole = message.role.toLowerCase();\n if (msgRole === \"user\" || msgRole === \"human\") {\n role = \"user\";\n } else if (\n msgRole === \"assistant\" ||\n msgRole === \"ai\" ||\n msgRole === \"model\"\n ) {\n role = \"model\";\n } else if (msgRole === \"function\" || msgRole === \"tool\") {\n role = \"user\";\n } else {\n // Default to user for unknown roles\n role = \"user\";\n }\n } else {\n // Unknown message type - default to user\n role = \"user\";\n }\n\n const parts: Gemini.Part[] = [];\n\n // Process standard content blocks\n const contentBlocks = Array.isArray(message.contentBlocks)\n ? message.contentBlocks\n : [];\n contentBlocks.forEach((block: ContentBlock.Standard) => {\n const contentBlock =\n (message.additional_kwargs\n .originalTextContentBlock as ContentBlock.Standard) || block;\n const part: Gemini.Part | null =\n convertStandardContentBlockToGeminiPart(contentBlock);\n if (part) {\n parts.push(part);\n }\n });\n\n // Convert AIMessage tool_calls to functionCall parts\n if (AIMessage.isInstance(message) && message.tool_calls?.length) {\n for (const toolCall of message.tool_calls) {\n parts.push({\n functionCall: {\n name: toolCall.name,\n args: toolCall.args ?? {},\n },\n } as Gemini.Part.FunctionCall);\n }\n }\n\n // Handle tool messages as function responses\n if (ToolMessage.isInstance(message) && message.tool_call_id) {\n const responseContent =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n // Find the matching tool call in a preceding AIMessage to get the function name\n const aiMsg = messages\n .filter(AIMessage.isInstance)\n .find((msg) =>\n msg.tool_calls?.find((tc) => tc.id === message.tool_call_id)\n );\n const matchedToolCall = aiMsg?.tool_calls?.find(\n (tc) => tc.id === message.tool_call_id\n );\n const isGeneratedId = message.tool_call_id.startsWith(\"lc-tool-call-\");\n parts.push({\n functionResponse: {\n ...(isGeneratedId ? {} : { id: message.tool_call_id }),\n name: matchedToolCall?.name ?? message.name ?? \"unknown\",\n response: { result: responseContent },\n },\n });\n }\n\n // Only return content if we have parts\n if (parts.length === 0) {\n return null;\n }\n\n return { role, parts };\n}\n\n/**\n * Converts a single LangChain message with legacy content blocks (v0 format) to Gemini Content.\n * This handles messages that have `response_metadata.output_version === \"v0\"`.\n *\n * This is intended to be called from `convertMessagesToGeminiContent`\n */\nfunction convertLegacyContentMessageToGeminiContent(\n message: BaseMessage,\n messages: BaseMessage[]\n): Gemini.Content | null {\n // Skip system messages - they're handled separately\n if (SystemMessage.isInstance(message)) {\n return null;\n }\n\n /**\n * @deprecated - This is for use by `convertLegacyContentMessageToGeminiContent` only\n */\n function isMessageContentText(\n content: object\n ): content is MessageContentText {\n return typeof content === \"object\" && content !== null && \"text\" in content;\n }\n\n /**\n * @deprecated - This is for use by `convertLegacyContentMessageToGeminiContent` only\n */\n function isMessageContentImageUrl(\n content: object\n ): content is MessageContentImageUrl {\n return (\n typeof content === \"object\" && content !== null && \"image_url\" in content\n );\n }\n\n /**\n * @deprecated - This is for use by `convertLegacyContentMessageToGeminiContent` only\n */\n function isMessageContentMedia(\n content: object\n ): content is MessageContentComplex {\n return (\n typeof content === \"object\" &&\n content !== null &&\n \"type\" in content &&\n content.type === \"media\"\n );\n }\n\n /**\n * Infers the MIME type from a URL based on its file extension.\n * This is used as a fallback when the MIME type is not provided.\n *\n * @param url - The URL to infer the MIME type from\n * @returns The inferred MIME type or a generic type if it cannot be determined\n */\n function inferMimeTypeFromUrl(url: string): string {\n const mimeTypeMap: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n bmp: \"image/bmp\",\n svg: \"image/svg+xml\",\n ico: \"image/x-icon\",\n tiff: \"image/tiff\",\n tif: \"image/tiff\",\n };\n\n try {\n // Extract the pathname from the URL\n const pathname = new URL(url).pathname;\n // Get the file extension (handle query params and fragments)\n const extension = pathname\n .split(\".\")\n .pop()\n ?.toLowerCase()\n .split(/[?#]/)[0];\n return extension ? mimeTypeMap[extension] : \"application/octet-stream\";\n } catch {\n // If URL parsing fails, try a simple extension extraction\n const match = url.match(/\\.([a-zA-Z0-9]+)(?:[?#]|$)/);\n if (match) {\n const extension = match[1].toLowerCase();\n return mimeTypeMap[extension];\n }\n return \"application/octet-stream\";\n }\n }\n\n function messageContentImageUrlData(\n content: MessageContentImageUrl\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n const url: string =\n typeof content.image_url === \"string\"\n ? content.image_url\n : content.image_url.url;\n if (!url) {\n throw new InvalidInputError(\n \"Missing image URL in image_url content block.\"\n );\n }\n\n const dataUrl = parseBase64DataUrl({ dataUrl: url });\n if (dataUrl?.data && dataUrl?.mime_type) {\n return {\n inlineData: {\n data: dataUrl.data,\n mimeType: dataUrl.mime_type,\n },\n };\n } else {\n // Infer MIME type from URL extension\n const mimeType = inferMimeTypeFromUrl(url) || \"image/png\";\n return {\n fileData: {\n mimeType,\n fileUri: url,\n },\n };\n }\n }\n\n function messageContentImageUrl(\n content: MessageContentImageUrl\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n const ret = messageContentImageUrlData(content);\n supplementVideoMetadata(content, ret);\n return ret;\n }\n\n function messageContentMediaData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: Record<string, any>\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n } else if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n } else {\n // The old version would attempt to read the URL, but we're\n // not in an async function, so we can't do that.\n }\n\n throw new InvalidInputError(\n `Invalid media content: ${JSON.stringify(\n content,\n null,\n 1\n )}. Expected either { mimeType, data } for inline data or { mimeType, fileUri } for file references.`\n );\n }\n\n function supplementVideoMetadata(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: MessageContentImageUrl | Record<string, any>,\n ret: Gemini.Part.InlineData | Gemini.Part.FileData\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n // Add videoMetadata if defined\n if (\"videoMetadata\" in content && typeof ret === \"object\") {\n ret.videoMetadata = content.videoMetadata;\n }\n return ret;\n }\n\n function messageContentMedia(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: Record<string, any>\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n const ret = messageContentMediaData(content);\n supplementVideoMetadata(content, ret);\n return ret;\n }\n\n const role: Gemini.Role = iife(() => {\n if (HumanMessage.isInstance(message)) {\n return \"user\";\n } else if (AIMessage.isInstance(message)) {\n return \"model\";\n } else if (ToolMessage.isInstance(message)) {\n // Tool messages in Gemini were represented as function responses, but now are \"user\"\n return \"user\";\n } else if (ChatMessage.isInstance(message)) {\n // Map ChatMessage roles to Gemini roles\n const msgRole = message.role.toLowerCase();\n if (msgRole === \"user\" || msgRole === \"human\") {\n return \"user\";\n } else if (\n msgRole === \"assistant\" ||\n msgRole === \"ai\" ||\n msgRole === \"model\"\n ) {\n return \"model\";\n } else if (msgRole === \"function\" || msgRole === \"tool\") {\n return \"user\";\n } else {\n // Default to user for unknown roles\n return \"user\";\n }\n } else {\n // Unknown message type - skip or default to user\n return \"user\";\n }\n });\n\n let parts: Gemini.Part[] = [];\n\n // Handle legacy content formats\n if (typeof message.content === \"string\") {\n // Simple string content\n if (message.content.trim()) {\n parts.push({ text: message.content });\n }\n } else if (Array.isArray(message.content)) {\n // Array of content blocks (legacy format)\n for (const item of message.content) {\n if (typeof item === \"string\") {\n parts.push({ text: item });\n } else if (typeof item === \"object\" && item !== null) {\n if (isMessageContentText(item)) {\n parts.push({ text: item.text });\n } else if (isDataContentBlock(item)) {\n parts.push(\n convertToProviderContentBlock(item, geminiContentBlockConverter)\n );\n } else if (item?.type === \"functionCall\") {\n const { type, functionCall, ...etc } = item;\n parts.push({\n ...etc,\n functionCall,\n } as Gemini.Part.FunctionCall);\n } else if (item?.type === \"executableCode\") {\n const { type, executableCode, ...etc } = item;\n parts.push({\n ...etc,\n executableCode,\n } as Gemini.Part.ExecutableCode);\n } else if (item?.type === \"codeExecutionResult\") {\n const { type, codeExecutionResult, ...etc } = item;\n parts.push({\n ...etc,\n codeExecutionResult,\n } as Gemini.Part.CodeExecutionResult);\n } else if (isMessageContentImageUrl(item)) {\n parts.push(messageContentImageUrl(item));\n } else if (isMessageContentMedia(item)) {\n parts.push(messageContentMedia(item));\n } else {\n parts.push(item as Gemini.Part);\n }\n }\n }\n }\n\n // Handle tool messages as function responses\n if (ToolMessage.isInstance(message) && message.tool_call_id) {\n const responseContent =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n // Find the matching tool call in a preceding AIMessage to get the function name\n const aiMsg = messages\n .filter(AIMessage.isInstance)\n .find((msg) =>\n msg.tool_calls?.find((tc) => tc.id === message.tool_call_id)\n );\n if (!aiMsg) {\n throw new ToolCallNotFoundError(message.tool_call_id);\n }\n const isGeneratedId = message.tool_call_id.startsWith(\"lc-tool-call-\");\n const matchedToolCall = aiMsg.tool_calls?.find(\n (tc) => tc.id === message.tool_call_id\n );\n parts.push({\n functionResponse: {\n ...(isGeneratedId ? {} : { id: message.tool_call_id }),\n name: matchedToolCall?.name ?? message.name ?? \"unknown\",\n response: { result: responseContent },\n },\n });\n\n // For tool messages, only keep functionResponse parts since the text content\n // is already included in the functionResponse.response.result\n parts = parts.filter((part) => \"functionResponse\" in part);\n }\n\n // Only add content if we have parts\n if (parts.length > 0) {\n return { role, parts };\n }\n\n return null;\n}\n\n/**\n * Converts an array of LangChain messages to Gemini API content format.\n *\n * This converter transforms LangChain's message types into the content structure\n * expected by Google's Gemini API.\n *\n * @remarks\n * The converter processes messages in two distinct ways based on their format:\n *\n * **V1 Standard Content Format**:\n * Messages with `output_version: \"v1\"` in their response metadata use the\n * standardized content block format. These are processed through\n * `convertStandardContentMessageToGeminiContent`, which extracts text blocks\n * from the `contentBlocks` array and maps message roles appropriately.\n *\n * **Google Format**:\n * Messages without the v1 marker are processed using generic logic that handles:\n * - String content: Simple text strings are converted to text parts\n * - Array content: Arrays of strings or content blocks are processed individually\n * - Tool messages: Converted to function response parts with tool call metadata\n *\n * @example\n * ```typescript\n * // Simple conversation with text messages\n * const messages = [\n * new HumanMessage(\"What is the weather?\"),\n * new AIMessage(\"I'll check that for you.\")\n * ];\n * const contents = convertMessagesToGeminiContents(messages);\n * // Returns: [\n * // { role: \"user\", parts: [{ text: \"What is the weather?\" }] },\n * // { role: \"model\", parts: [{ text: \"I'll check that for you.\" }] }\n * // ]\n * ```\n */\nexport const convertMessagesToGeminiContents: Converter<\n BaseMessage[],\n Gemini.GenerateContentRequest[\"contents\"]\n> = (messages) => {\n const contents: Gemini.Content[] = [];\n\n for (const message of messages) {\n // const content: Gemini.Content | null = convertContentMessageToGeminiContent(message, messages);\n const content: Gemini.Content | null = iife(() => {\n const outputVersion =\n \"output_version\" in message.response_metadata\n ? (message.response_metadata?.output_version as string)\n : \"v0\";\n switch (outputVersion) {\n case \"v1\":\n return convertStandardContentMessageToGeminiContent(\n message,\n messages\n );\n case \"v0\":\n default:\n return convertLegacyContentMessageToGeminiContent(message, messages);\n }\n });\n if (content) {\n const prev = contents[contents.length - 1];\n if (prev && prev.role === content.role) {\n prev.parts.push(...content.parts);\n } else {\n contents.push(content);\n }\n }\n }\n\n return contents;\n};\n\n/**\n * Converts LangChain system messages to Gemini API system instruction format.\n *\n * This converter extracts system messages from a message array and transforms them\n * into the format expected by Google's Gemini API for system instructions. System\n * instructions provide context and guidelines that influence the model's behavior\n * throughout the conversation.\n *\n * @remarks\n * The converter handles two distinct message formats:\n *\n * 1. **V1 Standard Content Format**: Messages with `output_version: \"v1\"` in their\n * response metadata use the standardized content block format. Only text blocks\n * are extracted from the `contentBlocks` array.\n *\n * 2. **Legacy Google Format**: Messages without the v1 marker use the legacy format\n * where content can be:\n * - A simple string (trimmed and converted to a text part)\n * - An array of strings or objects with `type: \"text\"` and a `text` property\n *\n * The converter filters out non-SystemMessage instances and only processes text\n * content, ignoring other content types like images or tool calls that may be\n * present in the message array.\n *\n * @example\n * ```typescript\n * // Simple string system message\n * const messages = [\n * new SystemMessage(\"You are a helpful assistant.\")\n * ];\n * const instruction = convertMessagesToGeminiSystemInstruction(messages);\n * // Returns: { parts: [{ text: \"You are a helpful assistant.\" }] }\n * ```\n *\n * @param messages - Array of LangChain messages to extract system instructions from\n * @returns A Gemini system instruction object with text parts, or undefined if no\n * system messages with text content are found\n */\nexport const convertMessagesToGeminiSystemInstruction: Converter<\n BaseMessage[],\n Gemini.GenerateContentRequest[\"systemInstruction\"]\n> = (messages) => {\n const systemParts: Gemini.Part[] = [];\n\n for (const message of messages) {\n if (SystemMessage.isInstance(message)) {\n if (message.text.trim()) {\n systemParts.push({ text: message.text });\n }\n }\n }\n\n if (systemParts.length === 0) {\n return undefined;\n }\n\n return { parts: systemParts };\n};\n\n/**\n * Converts an array of Gemini API parts into an array of LangChain tool calls.\n *\n * This function iterates through a given array of `Gemini.Part` objects,\n * identifies parts that represent a function call, and transforms them into\n * LangChain's standardized `ToolCall` format. Each resulting tool call is\n * assigned a unique, sequential ID.\n *\n * @param parts - An array of `Gemini.Part` objects, which may or may not\n * contain function calls.\n * @returns An array of `ContentBlock.Tools.ToolCall` objects. If no function\n * call parts are found, an empty array is returned.\n *\n * @remarks\n * The `id` for each tool call is generated sequentially in the format `call_0`,\n * `call_1`, and so on, based on its order of appearance in the input array.\n *\n * @example\n * ```typescript\n * const geminiParts: Gemini.Part[] = [\n * { text: \"Thinking about what to do...\" },\n * {\n * functionCall: {\n * name: \"search_web\",\n * args: { query: \"latest AI news\" }\n * }\n * },\n * {\n * functionCall: {\n * name: \"calculator\",\n * args: { expression: \"2 + 2\" }\n * }\n * }\n * ];\n *\n * const toolCalls = convertGeminiPartsToToolCalls(geminiParts);\n * // toolCalls will be:\n * // [\n * // { type: \"tool_call\", id: \"call_0\", name: \"search_web\", args: { query: \"latest AI news\" } },\n * // { type: \"tool_call\", id: \"call_1\", name: \"calculator\", args: { expression: \"2 + 2\" } }\n * // ]\n * ```\n */\nexport const convertGeminiPartsToToolCalls: Converter<\n Gemini.Part[],\n ContentBlock.Tools.ToolCall<string, Record<string, unknown>>[]\n> = (\n parts: Gemini.Part[]\n): ContentBlock.Tools.ToolCall<string, Record<string, unknown>>[] => {\n const toolCalls: ContentBlock.Tools.ToolCall<\n string,\n Record<string, unknown>\n >[] = [];\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (\"functionCall\" in part && part.functionCall) {\n const functionCallPart = part as Gemini.Part.FunctionCall;\n toolCalls.push({\n type: \"tool_call\",\n id:\n functionCallPart.functionCall.id ??\n `lc-tool-call-${uuidv4().replace(/-/g, \"\")}`,\n name: functionCallPart.functionCall.name,\n args: functionCallPart.functionCall.args ?? {},\n thoughtSignature: functionCallPart.thoughtSignature,\n });\n }\n }\n\n return toolCalls;\n};\n\nexport const convertGeminiPartToContentBlock: Converter<\n Gemini.Part,\n ContentBlock\n> = (part: Gemini.Part): ContentBlock => {\n const block: ContentBlock = iife(() => {\n if (\"text\" in part && typeof part.text === \"string\") {\n return {\n type: \"text\",\n text: part.text,\n };\n } else if (\"inlineData\" in part && part.inlineData) {\n return {\n type: \"inlineData\",\n inlineData: part.inlineData,\n };\n } else if (\"fileData\" in part && part.fileData) {\n return {\n type: \"fileData\",\n fileData: part.fileData,\n };\n } else if (\"functionCall\" in part && part.functionCall) {\n return {\n type: \"functionCall\",\n functionCall: part.functionCall,\n };\n } else if (\"functionResponse\" in part && part.functionResponse) {\n return {\n type: \"functionResponse\",\n functionResponse: part.functionResponse,\n };\n } else if (\"executableCode\" in part && part.executableCode) {\n return {\n type: \"executableCode\",\n executableCode: part.executableCode,\n };\n } else if (\"codeExecutionResult\" in part && part.codeExecutionResult) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: part.codeExecutionResult,\n };\n }\n return part as unknown as ContentBlock;\n });\n const ret: ContentBlock = {\n thought: part.thought,\n thoughtSignature: part.thoughtSignature,\n partMetadata: part.partMetadata,\n ...block,\n };\n for (const attribute in ret) {\n if (ret[attribute] === undefined) {\n delete ret[attribute];\n }\n }\n\n return ret;\n};\n\n/**\n * Converts a Gemini API candidate response to a LangChain AIMessage.\n *\n * This converter transforms the response from Google's Gemini API into a standardized\n * AIMessage format that can be used throughout the LangChain ecosystem. It handles\n * various types of content including text, inline data, file data, function calls,\n * and code execution results.\n *\n * @remarks\n * The converter performs the following transformations:\n * - Extracts tool calls from function call parts and assigns sequential IDs\n * - Converts single text responses to string format for simplicity\n * - Converts multi-part responses to ContentBlock array format\n * - Preserves metadata including finish reason, safety ratings, and citations\n * - Handles various Gemini part types (text, inlineData, fileData, functionCall, etc.)\n *\n * @example\n * ```typescript\n * const candidate: Gemini.Candidate = {\n * content: {\n * parts: [\n * { text: \"Hello, how can I help you?\" }\n * ]\n * },\n * finishReason: \"STOP\",\n * safetyRatings: [...]\n * };\n *\n * const aiMessage = convertGeminiCandidateToAIMessage(candidate);\n * // Returns: AIMessage with content \"Hello, how can I help you?\"\n * ```\n *\n * @param candidate - The Gemini API candidate response containing content parts and metadata\n * @returns An AIMessage instance with converted content, tool calls, and metadata\n */\nexport const convertGeminiCandidateToAIMessage: Converter<\n Gemini.Candidate,\n AIMessage\n> = (candidate) => {\n function groundingSupportByPart(\n groundingSupports?: Gemini.GroundingSupport[]\n ): Gemini.GroundingSupport[][] {\n const ret: Gemini.GroundingSupport[][] = [];\n\n if (!groundingSupports || groundingSupports.length === 0) {\n return [[]];\n }\n\n groundingSupports?.forEach((groundingSupport) => {\n const segment = groundingSupport?.segment;\n const partIndex = segment?.partIndex ?? 0;\n if (ret[partIndex]) {\n ret[partIndex].push(groundingSupport);\n } else {\n ret[partIndex] = [groundingSupport];\n }\n });\n\n return ret;\n }\n\n const parts = candidate.content?.parts || [];\n\n // Extract tool calls from function call parts\n const toolCalls = convertGeminiPartsToToolCalls(parts);\n\n // Convert parts to content format that the translator understands\n // Format: array of objects with type field matching the part type\n let content: string | ContentBlock[];\n let originalTextContentBlock: ContentBlock | undefined = undefined;\n\n const groundingMetadata = candidate?.groundingMetadata;\n const citationMetadata = candidate?.citationMetadata;\n const groundingParts = groundingSupportByPart(\n groundingMetadata?.groundingSupports\n );\n\n // Determine if a part carries actual content vs. just metadata.\n // Metadata-only parts (e.g. empty text with only thoughtSignature) should not\n // prevent collapsing a single-text response into a string.\n const hasContentPayload = (p: Gemini.Part): boolean =>\n !!p.text ||\n !!p.thought ||\n !!p.inlineData ||\n !!p.fileData ||\n !!p.functionCall ||\n !!p.functionResponse ||\n !!p.executableCode ||\n !!p.codeExecutionResult;\n\n const contentParts = parts.filter(hasContentPayload);\n\n if (contentParts.length === 0) {\n // No content-bearing parts (may still have metadata-only parts)\n content = \"\";\n if (parts.length > 0) {\n originalTextContentBlock = convertGeminiPartToContentBlock(parts[0]);\n }\n } else if (\n contentParts.length === 1 &&\n \"text\" in contentParts[0] &&\n !(\"thought\" in contentParts[0])\n ) {\n // Single text content part (possibly alongside metadata-only parts like\n // thoughtSignature) - store as string\n content = contentParts[0].text ?? \"\";\n // Merge metadata from any metadata-only parts into the content block\n const mergedPart: Gemini.Part = { ...contentParts[0] };\n for (const p of parts) {\n if (p !== contentParts[0] && p.thoughtSignature) {\n mergedPart.thoughtSignature = p.thoughtSignature;\n }\n }\n originalTextContentBlock = convertGeminiPartToContentBlock(mergedPart);\n } else {\n // Multiple content parts - convert to array format with type fields\n content = parts.map((p: Gemini.Part) => convertGeminiPartToContentBlock(p));\n }\n\n const additional_kwargs: Record<string, unknown> = {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n tokenCount: candidate.tokenCount,\n citationMetadata: candidate.citationMetadata,\n groundingMetadata: candidate.groundingMetadata,\n groundingAttributions: candidate.groundingAttributions,\n urlRetrievalMetadata: candidate.urlRetrievalMetadata,\n urlContextMetadata: candidate.urlContextMetadata,\n avgLogprobs: candidate.avgLogprobs,\n logprobsResult: candidate.logprobsResult,\n originalTextContentBlock,\n };\n\n const response_metadata: Record<string, unknown> = {\n model_provider: \"google\",\n finish_reason: candidate.finishReason,\n safety_ratings: candidate.safetyRatings,\n citation_metadata: candidate.citationMetadata,\n grounding_metadata: candidate.groundingMetadata,\n grounding_attributions: candidate.groundingAttributions,\n url_retrieval_metadata: candidate.urlRetrievalMetadata,\n url_context_metadata: candidate.urlContextMetadata,\n avg_logprobs: candidate.avgLogprobs,\n logprobs_result: candidate.logprobsResult,\n\n // Backwards compatibility\n citationMetadata,\n groundingMetadata,\n groundingSupport: groundingParts[0],\n };\n // Remove any undefined properties, so we don't include them\n for (const attribute in additional_kwargs) {\n if (additional_kwargs[attribute] === undefined) {\n delete additional_kwargs[attribute];\n }\n }\n for (const attribute in response_metadata) {\n if (response_metadata[attribute] === undefined) {\n delete response_metadata[attribute];\n }\n }\n\n return new AIMessage({\n content,\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n additional_kwargs,\n response_metadata,\n });\n};\n\nexport const convertAIMessageToText: Converter<AIMessage, string> = (\n message: AIMessage\n): string => {\n if (typeof message.content === \"string\") {\n return message.content;\n } else if (Array.isArray(message.content)) {\n return message.content\n .filter(\n (c) => typeof c === \"string\" || (c as { type?: string }).type === \"text\"\n )\n .map((c) =>\n typeof c === \"string\" ? c : (c as { text?: string }).text || \"\"\n )\n .join(\"\");\n } else {\n return \"\";\n }\n};\n\nexport const convertGeminiGenerateContentResponseToUsageMetadata: Converter<\n Gemini.GenerateContentResponse,\n UsageMetadata\n> = (data: Gemini.GenerateContentResponse): UsageMetadata => {\n function addModalityCounts(\n modalityTokenCounts: Gemini.ModalityTokenCount[] | undefined,\n details: InputTokenDetails | OutputTokenDetails\n ): void {\n modalityTokenCounts?.forEach((modalityTokenCount) => {\n const { modality, tokenCount } = modalityTokenCount;\n if (\n typeof modality === \"undefined\" ||\n typeof tokenCount === \"undefined\"\n ) {\n return;\n }\n const modalityLc: keyof ModalitiesTokenDetails =\n modality.toLowerCase() as keyof ModalitiesTokenDetails;\n const currentCount = details[modalityLc] ?? 0;\n details[modalityLc] = currentCount + tokenCount;\n });\n }\n\n const usageMetadata: Gemini.UsageMetadata | undefined = data.usageMetadata;\n\n const inputTokenCount = usageMetadata?.promptTokenCount ?? 0;\n const candidatesTokenCount = usageMetadata?.candidatesTokenCount ?? 0;\n const thoughtsTokenCount = usageMetadata?.thoughtsTokenCount ?? 0;\n const outputTokenCount = candidatesTokenCount + thoughtsTokenCount;\n const totalTokens =\n usageMetadata?.totalTokenCount ?? inputTokenCount + outputTokenCount;\n\n const input_token_details: InputTokenDetails = {};\n addModalityCounts(usageMetadata?.promptTokensDetails, input_token_details);\n input_token_details.cache_read = usageMetadata?.cachedContentTokenCount ?? 0;\n\n const output_token_details: OutputTokenDetails = {};\n addModalityCounts(\n usageMetadata?.candidatesTokensDetails,\n output_token_details\n );\n output_token_details.reasoning = usageMetadata?.thoughtsTokenCount ?? 0;\n\n return {\n input_tokens: inputTokenCount,\n output_tokens: outputTokenCount,\n total_tokens: totalTokens,\n input_token_details,\n output_token_details,\n };\n};\n"],"mappings":";;;;;;;;;;;;AAkCA,MAAa,8BAKR;CACH,cAAc;CAEd,sBAAsB,OAA4C;EAChE,OAAO,EAAE,MAAM,MAAM,KAAK;CAC5B;CAEA,uBAAuB,OAA6C;EAClE,IAAI,mBAAmB,KAAK,GAAG;GAC7B,IAAI,MAAM,gBAAgB,UAAU;IAClC,IAAI,CAAC,MAAM,WACT,MAAM,IAAI,kBACR,+CACF;IAEF,MAAM,UACJ,OAAO,MAAM,SAAS,WAClB,MAAM,OACN,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,OAE/C,KACE,MAAM,KAAK,MAAM,IAAkB,CAAC,CACjC,KAAK,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CACxC,KAAK,EAAE,CACZ,IACA,OAAO,MAAM,IAAI;IACzB,OAAO,EACL,YAAY;KACV,UAAU,MAAM;KAChB,MAAM;IACR,EACF;GACF;GAEA,IAAI,MAAM,gBAAgB,OAAO;IAE/B,MAAM,SAAS,mBAAmB,EAAE,SAAS,MAAM,IAAI,CAAC;IACxD,IAAI,QAAQ;KACV,MAAM,UACJ,OAAO,OAAO,SAAS,WACnB,OAAO,OAEP,KACE,MAAM,KAAK,OAAO,IAAkB,CAAC,CAClC,KAAK,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CACxC,KAAK,EAAE,CACZ;KACN,OAAO,EACL,YAAY;MACV,UAAU,OAAO,aAAa,MAAM,aAAa;MACjD,MAAM;KACR,EACF;IACF;IAEA,OAAO,EACL,UAAU;KACR,UAAU,MAAM,aAAa;KAC7B,SAAS,MAAM;IACjB,EACF;GACF;GAEA,IAAI,MAAM,gBAAgB,MACxB,OAAO,EACL,UAAU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;GACjC,IACE,OAAO,aAAa,eACpB,OAAO,eAAe,aAEtB;GAEF,MAAM,aACJ,SAAS,YAAY;GAEvB,QAAQ,eADa,QAAQ,eAAe,KACP;EACvC,CAAC;CACH;CAEA,MAAM,gBAAkD,KAAK;CAE7D,MAAM,kBAAkB,eAAe,oBAAoB;CAG3D,MAAM,oBAFuB,eAAe,wBAAwB,MACzC,eAAe,sBAAsB;CAEhE,MAAM,cACJ,eAAe,mBAAmB,kBAAkB;CAEtD,MAAM,sBAAyC,CAAC;CAChD,kBAAkB,eAAe,qBAAqB,mBAAmB;CACzE,oBAAoB,aAAa,eAAe,2BAA2B;CAE3E,MAAM,uBAA2C,CAAC;CAClD,kBACE,eAAe,yBACf,oBACF;CACA,qBAAqB,YAAY,eAAe,sBAAsB;CAEtE,OAAO;EACL,cAAc;EACd,eAAe;EACf,cAAc;EACd;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"messages.js","names":["uuidv4"],"sources":["../../src/converters/messages.ts"],"sourcesContent":["import {\n BaseMessage,\n AIMessage,\n isDataContentBlock,\n ContentBlock,\n parseBase64DataUrl,\n SystemMessage,\n HumanMessage,\n ToolMessage,\n ChatMessage,\n StandardContentBlockConverter,\n convertToProviderContentBlock,\n type Data,\n UsageMetadata,\n InputTokenDetails,\n OutputTokenDetails,\n ModalitiesTokenDetails,\n MessageContentImageUrl,\n MessageContentComplex,\n MessageContentText,\n} from \"@langchain/core/messages\";\nimport { v4 as uuidv4 } from \"@langchain/core/utils/uuid\";\nimport { Converter } from \"@langchain/core/utils/format\";\nimport type { Gemini } from \"../chat_models/types.js\";\nimport { iife } from \"../utils/misc.js\";\nimport { InvalidInputError, ToolCallNotFoundError } from \"../utils/errors.js\";\n\n/**\n * Standard content block converter for Google Gemini API.\n * Converts deprecated Data content blocks to Gemini Part format.\n *\n * @deprecated This converter is for backward compatibility with older message formats.\n * Use ContentBlock.Multimodal.Standard instead.\n */\nexport const geminiContentBlockConverter: StandardContentBlockConverter<{\n text: Gemini.Part;\n image: Gemini.Part;\n audio: Gemini.Part;\n file: Gemini.Part;\n}> = {\n providerName: \"ChatGoogle\",\n\n fromStandardTextBlock(block: Data.StandardTextBlock): Gemini.Part {\n return { text: block.text };\n },\n\n fromStandardImageBlock(block: Data.StandardImageBlock): Gemini.Part {\n if (isDataContentBlock(block)) {\n if (block.source_type === \"base64\") {\n if (!block.mime_type) {\n throw new InvalidInputError(\n \"mime_type is required for base64 image blocks\"\n );\n }\n const dataStr =\n typeof block.data === \"string\"\n ? block.data\n : typeof block.data === \"object\" && block.data !== null\n ? // Convert Uint8Array to base64 string\n btoa(\n Array.from(block.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n )\n : String(block.data);\n return {\n inlineData: {\n mimeType: block.mime_type,\n data: dataStr,\n },\n };\n }\n\n if (block.source_type === \"url\") {\n // Check if it's a data URL\n const parsed = parseBase64DataUrl({ dataUrl: block.url });\n if (parsed) {\n const dataStr =\n typeof parsed.data === \"string\"\n ? parsed.data\n : // Convert Uint8Array to base64 string\n btoa(\n Array.from(parsed.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n return {\n inlineData: {\n mimeType: parsed.mime_type || block.mime_type || \"image/jpeg\",\n data: dataStr,\n },\n };\n }\n // Otherwise, treat as file URI\n return {\n fileData: {\n mimeType: block.mime_type || \"image/jpeg\",\n fileUri: block.url,\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n fileData: {\n mimeType: block.mime_type || \"image/jpeg\",\n fileUri: block.id,\n },\n };\n }\n }\n\n throw new InvalidInputError(\n `Image content blocks with source_type \"${\n (block as Data.DataContentBlock).source_type\n }\" are not supported for ChatGoogle. Supported source types are: \"base64\", \"url\", \"id\".`\n );\n },\n\n fromStandardAudioBlock(block: Data.StandardAudioBlock): Gemini.Part {\n if (isDataContentBlock(block)) {\n if (block.source_type === \"base64\") {\n if (!block.mime_type) {\n throw new InvalidInputError(\n \"mime_type is required for base64 audio blocks\"\n );\n }\n const dataStr =\n typeof block.data === \"string\"\n ? block.data\n : typeof block.data === \"object\" && block.data !== null\n ? // Convert Uint8Array to base64 string\n btoa(\n Array.from(block.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n )\n : String(block.data);\n return {\n inlineData: {\n mimeType: block.mime_type,\n data: dataStr,\n },\n };\n }\n\n if (block.source_type === \"url\") {\n // Check if it's a data URL\n const parsed = parseBase64DataUrl({ dataUrl: block.url });\n if (parsed) {\n const dataStr =\n typeof parsed.data === \"string\"\n ? parsed.data\n : // Convert Uint8Array to base64 string\n btoa(\n Array.from(parsed.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n return {\n inlineData: {\n mimeType: parsed.mime_type || block.mime_type || \"audio/mpeg\",\n data: dataStr,\n },\n };\n }\n // Otherwise, treat as file URI\n return {\n fileData: {\n mimeType: block.mime_type || \"audio/mpeg\",\n fileUri: block.url,\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n fileData: {\n mimeType: block.mime_type || \"audio/mpeg\",\n fileUri: block.id,\n },\n };\n }\n }\n\n throw new InvalidInputError(\n `Audio content blocks with source_type \"${\n (block as Data.DataContentBlock).source_type\n }\" are not supported for ChatGoogle. Supported source types are: \"base64\", \"url\", \"id\".`\n );\n },\n\n fromStandardFileBlock(block: Data.StandardFileBlock): Gemini.Part {\n if (isDataContentBlock(block)) {\n if (block.source_type === \"base64\") {\n if (!block.mime_type) {\n throw new InvalidInputError(\n \"mime_type is required for base64 file blocks\"\n );\n }\n const dataStr =\n typeof block.data === \"string\"\n ? block.data\n : typeof block.data === \"object\" && block.data !== null\n ? // Convert Uint8Array to base64 string\n btoa(\n Array.from(block.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n )\n : String(block.data);\n return {\n inlineData: {\n mimeType: block.mime_type,\n data: dataStr,\n },\n };\n }\n\n if (block.source_type === \"url\") {\n // Check if it's a data URL\n const parsed = parseBase64DataUrl({ dataUrl: block.url });\n if (parsed) {\n const dataStr =\n typeof parsed.data === \"string\"\n ? parsed.data\n : // Convert Uint8Array to base64 string\n btoa(\n Array.from(parsed.data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n return {\n inlineData: {\n mimeType:\n parsed.mime_type ||\n block.mime_type ||\n \"application/octet-stream\",\n data: dataStr,\n },\n };\n }\n // Otherwise, treat as file URI\n return {\n fileData: {\n mimeType: block.mime_type || \"application/octet-stream\",\n fileUri: block.url,\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n fileData: {\n mimeType: block.mime_type || \"application/octet-stream\",\n fileUri: block.id,\n },\n };\n }\n }\n\n // Handle text source type (for plain text file blocks)\n if (\n \"source_type\" in block &&\n block.source_type === \"text\" &&\n \"text\" in block\n ) {\n return {\n text: block.text,\n };\n }\n\n throw new InvalidInputError(\n `File content blocks with source_type \"${\n (block as Data.DataContentBlock).source_type\n }\" are not supported for ChatGoogle. Supported source types are: \"base64\", \"url\", \"id\", \"text\".`\n );\n },\n};\n\nconst MEDIA_BLOCK_TYPES = new Set([\n \"media\",\n \"image\",\n \"audio\",\n \"video\",\n \"file\",\n \"text-plain\",\n]);\n\nfunction isMediaContentBlock(item: unknown): boolean {\n if (typeof item !== \"object\" || item === null) {\n return false;\n }\n if (isDataContentBlock(item)) {\n return item.source_type !== \"text\";\n }\n if (\"image_url\" in item || \"inlineData\" in item || \"fileData\" in item) {\n return true;\n }\n return MEDIA_BLOCK_TYPES.has((item as { type?: unknown }).type as string);\n}\n\nfunction stripMediaBlocksForFunctionResponse(content: unknown): unknown {\n if (!Array.isArray(content)) {\n return content;\n }\n return content.filter((item) => !isMediaContentBlock(item));\n}\n\nfunction convertStandardDataContentBlockToGeminiPart(\n block: ContentBlock.Multimodal.Data\n): Gemini.Part | null {\n function uint8arrayToString(data: Uint8Array): string {\n return btoa(\n Array.from(data as Uint8Array)\n .map((byte) => String.fromCharCode(byte))\n .join(\"\")\n );\n }\n\n function extractMimeType(str: string): {\n mimeType: string | null;\n data: string | null;\n } {\n if (str.startsWith(\"data:\")) {\n return {\n mimeType: str.split(\":\")[1].split(\";\")[0],\n data: str.split(\",\")[1],\n };\n }\n return {\n mimeType: null,\n data: null,\n };\n }\n\n if (\"mimeType\" in block && \"data\" in block) {\n const mimeType = block.mimeType!;\n const data: string =\n typeof block.data === \"string\"\n ? block.data\n : uint8arrayToString(block.data!);\n return {\n inlineData: {\n mimeType,\n data,\n },\n };\n } else if (\"mimeType\" in block && \"url\" in block) {\n const mimeType = block.mimeType!;\n const fileUri = block.url!;\n return {\n fileData: {\n mimeType,\n fileUri,\n },\n };\n } else if (\"url\" in block && block.url?.startsWith(\"data:\")) {\n const { mimeType, data } = extractMimeType(block.url!);\n if (mimeType && data) {\n return {\n inlineData: {\n mimeType,\n data,\n },\n };\n }\n }\n // FIXME - report this somehow?\n return null;\n}\n\nfunction convertStandardVideoContentBlockToGeminiPart(\n block: ContentBlock.Multimodal.Video\n): Gemini.Part | null {\n const ret: Gemini.Part | null =\n convertStandardDataContentBlockToGeminiPart(block);\n if (ret && block.metadata && \"videoMetadata\" in block.metadata) {\n (ret as Gemini.Part.FileData).videoMetadata = block.metadata.videoMetadata!;\n }\n return ret;\n}\n\nfunction convertStandardReasoningBlockToGeminiPart(\n block: ContentBlock.Reasoning\n): Gemini.Part | null {\n // Reasoning blocks created from Gemini should contain the base\n // standard block they would be if \"thought\" wasn't set to true.\n // If it exists, we'll use that. Otherwise, we'll assume it was\n // originally a text block.\n const ret =\n \"reasoningContentBlock\" in block && block.reasoningContentBlock\n ? convertStandardContentBlockToGeminiPart(\n block.reasoningContentBlock as ContentBlock.Standard\n )\n : { text: block.reasoning };\n\n // Then add that this came from the thinking process\n if (ret) {\n ret.thought = true;\n }\n\n return ret;\n}\n\n/**\n * Converts a single LangChain standard content block (v1 format)\n * into a Gemini.Part.\n *\n * This is intended to be called from `convertStandardContentMessageToGeminiContent`\n */\nfunction convertStandardContentBlockToGeminiPart(\n block: ContentBlock.Standard\n): Gemini.Part | null {\n function baseGeminiPart(): Gemini.Part | null {\n switch (block.type) {\n case \"text\":\n return { text: block.text };\n case \"reasoning\":\n return convertStandardReasoningBlockToGeminiPart(block);\n case \"image\":\n case \"audio\":\n case \"text-plain\":\n case \"file\":\n return convertStandardDataContentBlockToGeminiPart(block);\n case \"video\":\n return convertStandardVideoContentBlockToGeminiPart(block);\n default:\n return null;\n }\n }\n\n const ret: Gemini.Part | null = baseGeminiPart();\n if (ret) {\n if (\"thoughtSignature\" in block) {\n ret.thoughtSignature = block.thoughtSignature! as string;\n }\n }\n return ret;\n}\n\n/**\n * Converts a single LangChain message with standard content blocks (v1 format) to Gemini Content.\n * This handles messages that have `response_metadata.output_version === \"v1\"`.\n *\n * This is intended to be called from `convertMessagesToGeminiContent`\n */\nfunction convertStandardContentMessageToGeminiContent(\n message: BaseMessage,\n messages: BaseMessage[]\n): Gemini.Content | null {\n // Skip system messages - they're handled separately\n if (SystemMessage.isInstance(message)) {\n return null;\n }\n\n let role: Gemini.Role;\n if (HumanMessage.isInstance(message)) {\n role = \"user\";\n } else if (AIMessage.isInstance(message)) {\n role = \"model\";\n } else if (ToolMessage.isInstance(message)) {\n // Tool messages in Gemini were represented as function responses, but now are \"user\"\n role = \"user\";\n } else if (ChatMessage.isInstance(message)) {\n // Map ChatMessage roles to Gemini roles\n const msgRole = message.role.toLowerCase();\n if (msgRole === \"user\" || msgRole === \"human\") {\n role = \"user\";\n } else if (\n msgRole === \"assistant\" ||\n msgRole === \"ai\" ||\n msgRole === \"model\"\n ) {\n role = \"model\";\n } else if (msgRole === \"function\" || msgRole === \"tool\") {\n role = \"user\";\n } else {\n // Default to user for unknown roles\n role = \"user\";\n }\n } else {\n // Unknown message type - default to user\n role = \"user\";\n }\n\n let parts: Gemini.Part[] = [];\n\n // Process standard content blocks\n const contentBlocks = Array.isArray(message.contentBlocks)\n ? message.contentBlocks\n : [];\n contentBlocks.forEach((block: ContentBlock.Standard) => {\n const contentBlock =\n (message.additional_kwargs\n .originalTextContentBlock as ContentBlock.Standard) || block;\n const part: Gemini.Part | null =\n convertStandardContentBlockToGeminiPart(contentBlock);\n if (part) {\n parts.push(part);\n }\n });\n\n // Convert AIMessage tool_calls to functionCall parts\n if (AIMessage.isInstance(message) && message.tool_calls?.length) {\n for (const toolCall of message.tool_calls) {\n const part = {\n functionCall: {\n name: toolCall.name,\n args: toolCall.args ?? {},\n },\n } as Gemini.Part.FunctionCall;\n if (\"thoughtSignature\" in toolCall) {\n part.thoughtSignature = toolCall.thoughtSignature as string;\n }\n parts.push(part);\n }\n }\n\n // Handle tool messages as function responses\n if (ToolMessage.isInstance(message) && message.tool_call_id) {\n const responseContent = stripMediaBlocksForFunctionResponse(\n message.content\n );\n // Find the matching tool call in a preceding AIMessage to get the function name\n const aiMsg = messages\n .filter(AIMessage.isInstance)\n .find((msg) =>\n msg.tool_calls?.find((tc) => tc.id === message.tool_call_id)\n );\n const matchedToolCall = aiMsg?.tool_calls?.find(\n (tc) => tc.id === message.tool_call_id\n );\n const isGeneratedId = message.tool_call_id.startsWith(\"lc-tool-call-\");\n parts.push({\n functionResponse: {\n ...(isGeneratedId ? {} : { id: message.tool_call_id }),\n name: matchedToolCall?.name ?? message.name ?? \"unknown\",\n response: { result: responseContent },\n },\n });\n\n // For tool messages, keep only the functionResponse part(s): any text is\n // already included in functionResponse.response.result, and a `user`\n // content mixing a functionResponse with text is rejected or corrupted\n // by the API. Mirrors the legacy-path filter.\n parts = parts.filter((part) => \"functionResponse\" in part);\n }\n\n // Only return content if we have parts\n if (parts.length === 0) {\n return null;\n }\n\n return { role, parts };\n}\n\nfunction convertLegacyPartToGeminiPart(\n item: string | ContentBlock | Text\n): Gemini.Part {\n /**\n * @deprecated - This is for use by `convertLegacyContentMessageToGeminiContent` only\n */\n function isMessageContentText(\n content: object\n ): content is MessageContentText {\n return typeof content === \"object\" && content !== null && \"text\" in content;\n }\n\n /**\n * @deprecated - This is for use by `convertLegacyContentMessageToGeminiContent` only\n */\n function isMessageContentImageUrl(\n content: object\n ): content is MessageContentImageUrl {\n return (\n typeof content === \"object\" && content !== null && \"image_url\" in content\n );\n }\n\n /**\n * @deprecated - This is for use by `convertLegacyContentMessageToGeminiContent` only\n */\n function isMessageContentMedia(\n content: object\n ): content is MessageContentComplex {\n return (\n typeof content === \"object\" &&\n content !== null &&\n \"type\" in content &&\n content.type === \"media\"\n );\n }\n\n /**\n * Infers the MIME type from a URL based on its file extension.\n * This is used as a fallback when the MIME type is not provided.\n *\n * @param url - The URL to infer the MIME type from\n * @returns The inferred MIME type or a generic type if it cannot be determined\n */\n function inferMimeTypeFromUrl(url: string): string {\n const mimeTypeMap: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n bmp: \"image/bmp\",\n svg: \"image/svg+xml\",\n ico: \"image/x-icon\",\n tiff: \"image/tiff\",\n tif: \"image/tiff\",\n };\n\n try {\n // Extract the pathname from the URL\n const pathname = new URL(url).pathname;\n // Get the file extension (handle query params and fragments)\n const extension = pathname\n .split(\".\")\n .pop()\n ?.toLowerCase()\n .split(/[?#]/)[0];\n return extension ? mimeTypeMap[extension] : \"application/octet-stream\";\n } catch {\n // If URL parsing fails, try a simple extension extraction\n const match = url.match(/\\.([a-zA-Z0-9]+)(?:[?#]|$)/);\n if (match) {\n const extension = match[1].toLowerCase();\n return mimeTypeMap[extension];\n }\n return \"application/octet-stream\";\n }\n }\n\n function messageContentImageUrlData(\n content: MessageContentImageUrl\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n const url: string =\n typeof content.image_url === \"string\"\n ? content.image_url\n : content.image_url.url;\n if (!url) {\n throw new InvalidInputError(\n \"Missing image URL in image_url content block.\"\n );\n }\n\n const dataUrl = parseBase64DataUrl({ dataUrl: url });\n if (dataUrl?.data && dataUrl?.mime_type) {\n return {\n inlineData: {\n data: dataUrl.data,\n mimeType: dataUrl.mime_type,\n },\n };\n } else {\n // Infer MIME type from URL extension\n const mimeType = inferMimeTypeFromUrl(url) || \"image/png\";\n return {\n fileData: {\n mimeType,\n fileUri: url,\n },\n };\n }\n }\n\n function messageContentImageUrl(\n content: MessageContentImageUrl\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n const ret = messageContentImageUrlData(content);\n supplementVideoMetadata(content, ret);\n return ret;\n }\n\n function messageContentMediaData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: Record<string, any>\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n } else if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n } else {\n // The old version would attempt to read the URL, but we're\n // not in an async function, so we can't do that.\n }\n\n throw new InvalidInputError(\n `Invalid media content: ${JSON.stringify(\n content,\n null,\n 1\n )}. Expected either { mimeType, data } for inline data or { mimeType, fileUri } for file references.`\n );\n }\n\n function supplementVideoMetadata(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: MessageContentImageUrl | Record<string, any>,\n ret: Gemini.Part.InlineData | Gemini.Part.FileData\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n // Add videoMetadata if defined\n if (\"videoMetadata\" in content && typeof ret === \"object\") {\n ret.videoMetadata = content.videoMetadata;\n }\n return ret;\n }\n\n function messageContentMedia(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n content: Record<string, any>\n ): Gemini.Part.InlineData | Gemini.Part.FileData {\n const ret = messageContentMediaData(content);\n supplementVideoMetadata(content, ret);\n return ret;\n }\n\n function baseGeminiPart(): Gemini.Part {\n if (typeof item === \"string\") {\n return { text: item };\n } else if (typeof item === \"object\" && item !== null) {\n if (isMessageContentText(item)) {\n return { text: item.text };\n } else if (isDataContentBlock(item)) {\n return convertToProviderContentBlock(item, geminiContentBlockConverter);\n } else if (\"type\" in item && item?.type === \"functionCall\") {\n const { type, functionCall, ...etc } = item;\n return {\n ...etc,\n functionCall,\n } as Gemini.Part.FunctionCall;\n } else if (\"type\" in item && item?.type === \"executableCode\") {\n const { type, executableCode, ...etc } = item;\n return {\n ...etc,\n executableCode,\n } as Gemini.Part.ExecutableCode;\n } else if (\"type\" in item && item?.type === \"codeExecutionResult\") {\n const { type, codeExecutionResult, ...etc } = item;\n return {\n ...etc,\n codeExecutionResult,\n } as Gemini.Part.CodeExecutionResult;\n } else if (isMessageContentImageUrl(item)) {\n return messageContentImageUrl(item);\n } else if (isMessageContentMedia(item)) {\n return messageContentMedia(item);\n }\n }\n return item as Gemini.Part;\n }\n\n const ret = baseGeminiPart();\n const itemRecord = item as Record<string, unknown>;\n if (\"thought\" in itemRecord) {\n ret.thought = itemRecord.thought as boolean;\n }\n if (\"thoughtSignature\" in itemRecord) {\n ret.thoughtSignature = itemRecord.thoughtSignature as string;\n }\n return ret;\n}\n\n/**\n * Converts a single LangChain message with legacy content blocks (v0 format) to Gemini Content.\n * This handles messages that have `response_metadata.output_version === \"v0\"`.\n *\n * This is intended to be called from `convertMessagesToGeminiContent`\n */\nfunction convertLegacyContentMessageToGeminiContent(\n message: BaseMessage,\n messages: BaseMessage[]\n): Gemini.Content | null {\n // Skip system messages - they're handled separately\n if (SystemMessage.isInstance(message)) {\n return null;\n }\n\n const role: Gemini.Role = iife(() => {\n if (HumanMessage.isInstance(message)) {\n return \"user\";\n } else if (AIMessage.isInstance(message)) {\n return \"model\";\n } else if (ToolMessage.isInstance(message)) {\n // Tool messages in Gemini were represented as function responses, but now are \"user\"\n return \"user\";\n } else if (ChatMessage.isInstance(message)) {\n // Map ChatMessage roles to Gemini roles\n const msgRole = message.role.toLowerCase();\n if (msgRole === \"user\" || msgRole === \"human\") {\n return \"user\";\n } else if (\n msgRole === \"assistant\" ||\n msgRole === \"ai\" ||\n msgRole === \"model\"\n ) {\n return \"model\";\n } else if (msgRole === \"function\" || msgRole === \"tool\") {\n return \"user\";\n } else {\n // Default to user for unknown roles\n return \"user\";\n }\n } else {\n // Unknown message type - skip or default to user\n return \"user\";\n }\n });\n\n let parts: Gemini.Part[] = [];\n\n // Handle legacy content formats\n if (typeof message.content === \"string\") {\n // Simple string content\n if (message.content.trim()) {\n parts.push({ text: message.content });\n }\n } else if (Array.isArray(message.content)) {\n // Array of content blocks (legacy format)\n for (const item of message.content) {\n const part = convertLegacyPartToGeminiPart(item);\n parts.push(part);\n }\n }\n\n // Handle tool messages as function responses\n if (ToolMessage.isInstance(message) && message.tool_call_id) {\n const responseContent = stripMediaBlocksForFunctionResponse(\n message.content\n );\n // Find the matching tool call in a preceding AIMessage to get the function name\n const aiMsg = messages\n .filter(AIMessage.isInstance)\n .find((msg) =>\n msg.tool_calls?.find((tc) => tc.id === message.tool_call_id)\n );\n if (!aiMsg) {\n throw new ToolCallNotFoundError(message.tool_call_id);\n }\n const isGeneratedId = message.tool_call_id.startsWith(\"lc-tool-call-\");\n const matchedToolCall = aiMsg.tool_calls?.find(\n (tc) => tc.id === message.tool_call_id\n );\n parts.push({\n functionResponse: {\n ...(isGeneratedId ? {} : { id: message.tool_call_id }),\n name: matchedToolCall?.name ?? message.name ?? \"unknown\",\n response: { result: responseContent },\n },\n });\n\n // For tool messages, drop the redundant text parts - their content is\n // already folded into functionResponse.response.result above - but keep\n // any media parts (inlineData/fileData) as siblings so images/audio/video\n // reach Gemini as real parts instead of being lost inside the JSON string.\n parts = parts.filter(\n (part) =>\n \"functionResponse\" in part || \"inlineData\" in part || \"fileData\" in part\n );\n }\n\n // Only add content if we have parts\n if (parts.length > 0) {\n return { role, parts };\n }\n\n return null;\n}\n\n/**\n * Converts an array of LangChain messages to Gemini API content format.\n *\n * This converter transforms LangChain's message types into the content structure\n * expected by Google's Gemini API.\n *\n * @remarks\n * The converter processes messages in two distinct ways based on their format:\n *\n * **V1 Standard Content Format**:\n * Messages with `output_version: \"v1\"` in their response metadata use the\n * standardized content block format. These are processed through\n * `convertStandardContentMessageToGeminiContent`, which extracts text blocks\n * from the `contentBlocks` array and maps message roles appropriately.\n *\n * **Google Format**:\n * Messages without the v1 marker are processed using generic logic that handles:\n * - String content: Simple text strings are converted to text parts\n * - Array content: Arrays of strings or content blocks are processed individually\n * - Tool messages: Converted to function response parts with tool call metadata\n *\n * @example\n * ```typescript\n * // Simple conversation with text messages\n * const messages = [\n * new HumanMessage(\"What is the weather?\"),\n * new AIMessage(\"I'll check that for you.\")\n * ];\n * const contents = convertMessagesToGeminiContents(messages);\n * // Returns: [\n * // { role: \"user\", parts: [{ text: \"What is the weather?\" }] },\n * // { role: \"model\", parts: [{ text: \"I'll check that for you.\" }] }\n * // ]\n * ```\n */\nexport const convertMessagesToGeminiContents: Converter<\n BaseMessage[],\n Gemini.GenerateContentRequest[\"contents\"]\n> = (messages) => {\n const contents: Gemini.Content[] = [];\n\n for (const message of messages) {\n // const content: Gemini.Content | null = convertContentMessageToGeminiContent(message, messages);\n const content: Gemini.Content | null = iife(() => {\n const outputVersion =\n \"output_version\" in message.response_metadata\n ? (message.response_metadata?.output_version as string)\n : \"v0\";\n switch (outputVersion) {\n case \"v1\":\n return convertStandardContentMessageToGeminiContent(\n message,\n messages\n );\n case \"v0\":\n default:\n return convertLegacyContentMessageToGeminiContent(message, messages);\n }\n });\n if (content) {\n const prev = contents[contents.length - 1];\n if (canMergeInto(prev, content) && content.parts) {\n prev.parts ??= [];\n prev.parts.push(...content.parts);\n } else {\n contents.push(content);\n }\n }\n }\n\n return contents;\n};\n\n/**\n * Returns true if any part of the given content is a functionResponse part\n * (i.e. it was produced from a ToolMessage).\n */\nfunction hasFunctionResponse(content: Gemini.Content): boolean {\n return content.parts?.some((part) => \"functionResponse\" in part) === true;\n}\n\n/**\n * Adjacent same-role contents merge only when they are the same kind of\n * turn:\n *\n * - Both carry functionResponse parts (a run of tool responses answering\n * one model turn's parallel calls): the API requires those to share a\n * single `user` content whose part count matches the call count.\n * - Neither does (plain text turns): coalesced as before #11444.\n *\n * A functionResponse turn never merges with a plain one: a `user` content\n * mixing the two is rejected by newer Gemini models and corrupts\n * generation on older ones.\n */\nfunction canMergeInto(\n prev: Gemini.Content | undefined,\n content: Gemini.Content\n): boolean {\n return (\n prev !== undefined &&\n prev.role === content.role &&\n hasFunctionResponse(prev) === hasFunctionResponse(content)\n );\n}\n\n/**\n * Converts LangChain system messages to Gemini API system instruction format.\n *\n * This converter extracts system messages from a message array and transforms them\n * into the format expected by Google's Gemini API for system instructions. System\n * instructions provide context and guidelines that influence the model's behavior\n * throughout the conversation.\n *\n * @remarks\n * The converter handles two distinct message formats:\n *\n * 1. **V1 Standard Content Format**: Messages with `output_version: \"v1\"` in their\n * response metadata use the standardized content block format. Only text blocks\n * are extracted from the `contentBlocks` array.\n *\n * 2. **Legacy Google Format**: Messages without the v1 marker use the legacy format\n * where content can be:\n * - A simple string (trimmed and converted to a text part)\n * - An array of strings or objects with `type: \"text\"` and a `text` property\n *\n * The converter filters out non-SystemMessage instances and only processes text\n * content, ignoring other content types like images or tool calls that may be\n * present in the message array.\n *\n * @example\n * ```typescript\n * // Simple string system message\n * const messages = [\n * new SystemMessage(\"You are a helpful assistant.\")\n * ];\n * const instruction = convertMessagesToGeminiSystemInstruction(messages);\n * // Returns: { parts: [{ text: \"You are a helpful assistant.\" }] }\n * ```\n *\n * @param messages - Array of LangChain messages to extract system instructions from\n * @returns A Gemini system instruction object with text parts, or undefined if no\n * system messages with text content are found\n */\nexport const convertMessagesToGeminiSystemInstruction: Converter<\n BaseMessage[],\n Gemini.GenerateContentRequest[\"systemInstruction\"]\n> = (messages) => {\n const systemParts: Gemini.Part[] = [];\n\n for (const message of messages) {\n if (SystemMessage.isInstance(message)) {\n if (message.text.trim()) {\n systemParts.push({ text: message.text });\n }\n }\n }\n\n if (systemParts.length === 0) {\n return undefined;\n }\n\n return { parts: systemParts };\n};\n\n/**\n * Converts an array of Gemini API parts into an array of LangChain tool calls.\n *\n * This function iterates through a given array of `Gemini.Part` objects,\n * identifies parts that represent a function call, and transforms them into\n * LangChain's standardized `ToolCall` format. Each resulting tool call is\n * assigned a unique, sequential ID.\n *\n * @param parts - An array of `Gemini.Part` objects, which may or may not\n * contain function calls.\n * @returns An array of `ContentBlock.Tools.ToolCall` objects. If no function\n * call parts are found, an empty array is returned.\n *\n * @remarks\n * The `id` for each tool call is generated sequentially in the format `call_0`,\n * `call_1`, and so on, based on its order of appearance in the input array.\n *\n * @example\n * ```typescript\n * const geminiParts: Gemini.Part[] = [\n * { text: \"Thinking about what to do...\" },\n * {\n * functionCall: {\n * name: \"search_web\",\n * args: { query: \"latest AI news\" }\n * }\n * },\n * {\n * functionCall: {\n * name: \"calculator\",\n * args: { expression: \"2 + 2\" }\n * }\n * }\n * ];\n *\n * const toolCalls = convertGeminiPartsToToolCalls(geminiParts);\n * // toolCalls will be:\n * // [\n * // { type: \"tool_call\", id: \"call_0\", name: \"search_web\", args: { query: \"latest AI news\" } },\n * // { type: \"tool_call\", id: \"call_1\", name: \"calculator\", args: { expression: \"2 + 2\" } }\n * // ]\n * ```\n */\nexport const convertGeminiPartsToToolCalls: Converter<\n Gemini.Part[],\n ContentBlock.Tools.ToolCall<string, Record<string, unknown>>[]\n> = (\n parts: Gemini.Part[]\n): ContentBlock.Tools.ToolCall<string, Record<string, unknown>>[] => {\n const toolCalls: ContentBlock.Tools.ToolCall<\n string,\n Record<string, unknown>\n >[] = [];\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (\"functionCall\" in part && part.functionCall) {\n const functionCallPart = part as Gemini.Part.FunctionCall;\n toolCalls.push({\n type: \"tool_call\",\n id:\n functionCallPart.functionCall.id ??\n `lc-tool-call-${uuidv4().replace(/-/g, \"\")}`,\n name: functionCallPart.functionCall.name,\n args: functionCallPart.functionCall.args ?? {},\n thoughtSignature: functionCallPart.thoughtSignature,\n });\n }\n }\n\n return toolCalls;\n};\n\nexport const convertGeminiPartToContentBlock: Converter<\n Gemini.Part,\n ContentBlock\n> = (part: Gemini.Part): ContentBlock => {\n const block: ContentBlock = iife(() => {\n if (\"text\" in part && typeof part.text === \"string\") {\n return {\n type: \"text\",\n text: part.text,\n };\n } else if (\"inlineData\" in part && part.inlineData) {\n return {\n type: \"inlineData\",\n inlineData: part.inlineData,\n };\n } else if (\"fileData\" in part && part.fileData) {\n return {\n type: \"fileData\",\n fileData: part.fileData,\n };\n } else if (\"functionCall\" in part && part.functionCall) {\n return {\n type: \"functionCall\",\n functionCall: part.functionCall,\n };\n } else if (\"functionResponse\" in part && part.functionResponse) {\n return {\n type: \"functionResponse\",\n functionResponse: part.functionResponse,\n };\n } else if (\"executableCode\" in part && part.executableCode) {\n return {\n type: \"executableCode\",\n executableCode: part.executableCode,\n };\n } else if (\"codeExecutionResult\" in part && part.codeExecutionResult) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: part.codeExecutionResult,\n };\n }\n return part as unknown as ContentBlock;\n });\n const ret: ContentBlock = {\n thought: part.thought,\n thoughtSignature: part.thoughtSignature,\n partMetadata: part.partMetadata,\n ...block,\n };\n for (const attribute in ret) {\n if (ret[attribute] === undefined) {\n delete ret[attribute];\n }\n }\n\n return ret;\n};\n\n/**\n * Converts a Gemini API candidate response to a LangChain AIMessage.\n *\n * This converter transforms the response from Google's Gemini API into a standardized\n * AIMessage format that can be used throughout the LangChain ecosystem. It handles\n * various types of content including text, inline data, file data, function calls,\n * and code execution results.\n *\n * @remarks\n * The converter performs the following transformations:\n * - Extracts tool calls from function call parts and assigns sequential IDs\n * - Converts single text responses to string format for simplicity\n * - Converts multi-part responses to ContentBlock array format\n * - Preserves metadata including finish reason, safety ratings, and citations\n * - Handles various Gemini part types (text, inlineData, fileData, functionCall, etc.)\n *\n * @example\n * ```typescript\n * const candidate: Gemini.Candidate = {\n * content: {\n * parts: [\n * { text: \"Hello, how can I help you?\" }\n * ]\n * },\n * finishReason: \"STOP\",\n * safetyRatings: [...]\n * };\n *\n * const aiMessage = convertGeminiCandidateToAIMessage(candidate);\n * // Returns: AIMessage with content \"Hello, how can I help you?\"\n * ```\n *\n * @param candidate - The Gemini API candidate response containing content parts and metadata\n * @returns An AIMessage instance with converted content, tool calls, and metadata\n */\nexport const convertGeminiCandidateToAIMessage: Converter<\n Gemini.Candidate,\n AIMessage\n> = (candidate) => {\n function groundingSupportByPart(\n groundingSupports?: Gemini.GroundingSupport[]\n ): Gemini.GroundingSupport[][] {\n const ret: Gemini.GroundingSupport[][] = [];\n\n if (!groundingSupports || groundingSupports.length === 0) {\n return [[]];\n }\n\n groundingSupports?.forEach((groundingSupport) => {\n const segment = groundingSupport?.segment;\n const partIndex = segment?.partIndex ?? 0;\n if (ret[partIndex]) {\n ret[partIndex].push(groundingSupport);\n } else {\n ret[partIndex] = [groundingSupport];\n }\n });\n\n return ret;\n }\n\n const parts = candidate.content?.parts || [];\n\n // Extract tool calls from function call parts\n const toolCalls = convertGeminiPartsToToolCalls(parts);\n\n // Convert parts to content format that the translator understands\n // Format: array of objects with type field matching the part type\n let content: string | ContentBlock[];\n let originalTextContentBlock: ContentBlock | undefined = undefined;\n\n const groundingMetadata = candidate?.groundingMetadata;\n const citationMetadata = candidate?.citationMetadata;\n const groundingParts = groundingSupportByPart(\n groundingMetadata?.groundingSupports\n );\n\n // Determine if a part carries actual content vs. just metadata.\n // Metadata-only parts (e.g. empty text with only thoughtSignature) should not\n // prevent collapsing a single-text response into a string.\n const hasContentPayload = (p: Gemini.Part): boolean =>\n !!p.text ||\n !!p.thought ||\n !!p.inlineData ||\n !!p.fileData ||\n !!p.functionCall ||\n !!p.functionResponse ||\n !!p.executableCode ||\n !!p.codeExecutionResult;\n\n const contentParts = parts.filter(hasContentPayload);\n\n if (contentParts.length === 0) {\n // No content-bearing parts (may still have metadata-only parts)\n content = \"\";\n if (parts.length > 0) {\n originalTextContentBlock = convertGeminiPartToContentBlock(parts[0]);\n }\n } else if (\n contentParts.length === 1 &&\n \"text\" in contentParts[0] &&\n !(\"thought\" in contentParts[0])\n ) {\n // Single text content part (possibly alongside metadata-only parts like\n // thoughtSignature) - store as string\n content = contentParts[0].text ?? \"\";\n // Merge metadata from any metadata-only parts into the content block\n const mergedPart: Gemini.Part = { ...contentParts[0] };\n for (const p of parts) {\n if (p !== contentParts[0] && p.thoughtSignature) {\n mergedPart.thoughtSignature = p.thoughtSignature;\n }\n }\n originalTextContentBlock = convertGeminiPartToContentBlock(mergedPart);\n } else {\n // Multiple content parts - convert to array format with type fields\n content = parts.map((p: Gemini.Part) => convertGeminiPartToContentBlock(p));\n }\n\n const additional_kwargs: Record<string, unknown> = {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n tokenCount: candidate.tokenCount,\n citationMetadata: candidate.citationMetadata,\n groundingMetadata: candidate.groundingMetadata,\n groundingAttributions: candidate.groundingAttributions,\n urlRetrievalMetadata: candidate.urlRetrievalMetadata,\n urlContextMetadata: candidate.urlContextMetadata,\n avgLogprobs: candidate.avgLogprobs,\n logprobsResult: candidate.logprobsResult,\n originalTextContentBlock,\n };\n\n const response_metadata: Record<string, unknown> = {\n model_provider: \"google\",\n finish_reason: candidate.finishReason,\n safety_ratings: candidate.safetyRatings,\n citation_metadata: candidate.citationMetadata,\n grounding_metadata: candidate.groundingMetadata,\n grounding_attributions: candidate.groundingAttributions,\n url_retrieval_metadata: candidate.urlRetrievalMetadata,\n url_context_metadata: candidate.urlContextMetadata,\n avg_logprobs: candidate.avgLogprobs,\n logprobs_result: candidate.logprobsResult,\n\n // Backwards compatibility\n citationMetadata,\n groundingMetadata,\n groundingSupport: groundingParts[0],\n };\n // Remove any undefined properties, so we don't include them\n for (const attribute in additional_kwargs) {\n if (additional_kwargs[attribute] === undefined) {\n delete additional_kwargs[attribute];\n }\n }\n for (const attribute in response_metadata) {\n if (response_metadata[attribute] === undefined) {\n delete response_metadata[attribute];\n }\n }\n\n return new AIMessage({\n content,\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n additional_kwargs,\n response_metadata,\n });\n};\n\nexport const convertAIMessageToText: Converter<AIMessage, string> = (\n message: AIMessage\n): string => {\n if (typeof message.content === \"string\") {\n return message.content;\n } else if (Array.isArray(message.content)) {\n return message.content\n .filter(\n (c) => typeof c === \"string\" || (c as { type?: string }).type === \"text\"\n )\n .map((c) =>\n typeof c === \"string\" ? c : (c as { text?: string }).text || \"\"\n )\n .join(\"\");\n } else {\n return \"\";\n }\n};\n\nexport const convertGeminiGenerateContentResponseToUsageMetadata: Converter<\n Gemini.GenerateContentResponse,\n UsageMetadata\n> = (data: Gemini.GenerateContentResponse): UsageMetadata => {\n function addModalityCounts(\n modalityTokenCounts: Gemini.ModalityTokenCount[] | undefined,\n details: InputTokenDetails | OutputTokenDetails\n ): void {\n modalityTokenCounts?.forEach((modalityTokenCount) => {\n const { modality, tokenCount } = modalityTokenCount;\n if (\n typeof modality === \"undefined\" ||\n typeof tokenCount === \"undefined\"\n ) {\n return;\n }\n const modalityLc: keyof ModalitiesTokenDetails =\n modality.toLowerCase() as keyof ModalitiesTokenDetails;\n const currentCount = details[modalityLc] ?? 0;\n details[modalityLc] = currentCount + tokenCount;\n });\n }\n\n const usageMetadata: Gemini.UsageMetadata | undefined = data.usageMetadata;\n\n const inputTokenCount = usageMetadata?.promptTokenCount ?? 0;\n const candidatesTokenCount = usageMetadata?.candidatesTokenCount ?? 0;\n const thoughtsTokenCount = usageMetadata?.thoughtsTokenCount ?? 0;\n const outputTokenCount = candidatesTokenCount + thoughtsTokenCount;\n const totalTokens =\n usageMetadata?.totalTokenCount ?? inputTokenCount + outputTokenCount;\n\n const input_token_details: InputTokenDetails = {};\n addModalityCounts(usageMetadata?.promptTokensDetails, input_token_details);\n input_token_details.cache_read = usageMetadata?.cachedContentTokenCount ?? 0;\n\n const output_token_details: OutputTokenDetails = {};\n addModalityCounts(\n usageMetadata?.candidatesTokensDetails,\n output_token_details\n );\n output_token_details.reasoning = usageMetadata?.thoughtsTokenCount ?? 0;\n\n return {\n input_tokens: inputTokenCount,\n output_tokens: outputTokenCount,\n total_tokens: totalTokens,\n input_token_details,\n output_token_details,\n };\n};\n"],"mappings":";;;;;;;;;;;;AAkCA,MAAa,8BAKR;CACH,cAAc;CAEd,sBAAsB,OAA4C;EAChE,OAAO,EAAE,MAAM,MAAM,KAAK;CAC5B;CAEA,uBAAuB,OAA6C;EAClE,IAAI,mBAAmB,KAAK,GAAG;GAC7B,IAAI,MAAM,gBAAgB,UAAU;IAClC,IAAI,CAAC,MAAM,WACT,MAAM,IAAI,kBACR,+CACF;IAEF,MAAM,UACJ,OAAO,MAAM,SAAS,WAClB,MAAM,OACN,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,OAE/C,KACE,MAAM,KAAK,MAAM,IAAkB,CAAC,CACjC,KAAK,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CACxC,KAAK,EAAE,CACZ,IACA,OAAO,MAAM,IAAI;IACzB,OAAO,EACL,YAAY;KACV,UAAU,MAAM;KAChB,MAAM;IACR,EACF;GACF;GAEA,IAAI,MAAM,gBAAgB,OAAO;IAE/B,MAAM,SAAS,mBAAmB,EAAE,SAAS,MAAM,IAAI,CAAC;IACxD,IAAI,QAAQ;KACV,MAAM,UACJ,OAAO,OAAO,SAAS,WACnB,OAAO,OAEP,KACE,MAAM,KAAK,OAAO,IAAkB,CAAC,CAClC,KAAK,SAAS,OAAO,aAAa,IAAI,CAAC,CAAC,CACxC,KAAK,EAAE,CACZ;KACN,OAAO,EACL,YAAY;MACV,UAAU,OAAO,aAAa,MAAM,aAAa;MACjD,MAAM;KACR,EACF;IACF;IAEA,OAAO,EACL,UAAU;KACR,UAAU,MAAM,aAAa;KAC7B,SAAS,MAAM;IACjB,EACF;GACF;GAEA,IAAI,MAAM,gBAAgB,MACxB,OAAO,EACL,UAAU;IACR,UAAU,MAAM,aAAa;IAC7B,SAAS,MAAM;GACjB,EACF;EAEJ;EAEA,MAAM,IAAI,kBACR,0CACG,MAAgC,YAClC,uFACH;CACF;CAEA,uBAAuB,OAA6C;E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ACJ,SAAS,YAAY;GAEvB,QAAQ,eADa,QAAQ,eAAe,KACP;EACvC,CAAC;CACH;CAEA,MAAM,gBAAkD,KAAK;CAE7D,MAAM,kBAAkB,eAAe,oBAAoB;CAG3D,MAAM,oBAFuB,eAAe,wBAAwB,MACzC,eAAe,sBAAsB;CAEhE,MAAM,cACJ,eAAe,mBAAmB,kBAAkB;CAEtD,MAAM,sBAAyC,CAAC;CAChD,kBAAkB,eAAe,qBAAqB,mBAAmB;CACzE,oBAAoB,aAAa,eAAe,2BAA2B;CAE3E,MAAM,uBAA2C,CAAC;CAClD,kBACE,eAAe,yBACf,oBACF;CACA,qBAAqB,YAAY,eAAe,sBAAsB;CAEtE,OAAO;EACL,cAAc;EACd,eAAe;EACf,cAAc;EACd;EACA;CACF;AACF"}
|
|
@@ -38,12 +38,12 @@ const require_types = require("../chat_models/types.cjs");
|
|
|
38
38
|
function convertReasoningEffortToReasoningTokens(modelName, effort) {
|
|
39
39
|
if (effort === void 0) return;
|
|
40
40
|
const minTokens = modelName?.startsWith("gemini-2.5-flash") ? 0 : 128;
|
|
41
|
-
const maxTokens = modelName?.startsWith("gemini-2.5-flash") ?
|
|
41
|
+
const maxTokens = modelName?.startsWith("gemini-2.5-flash") ? 24576 : 32768;
|
|
42
42
|
switch (effort.toLowerCase()) {
|
|
43
43
|
case "none":
|
|
44
44
|
case "minimal": return minTokens;
|
|
45
45
|
case "low": return 1024;
|
|
46
|
-
case "medium": return
|
|
46
|
+
case "medium": return 8192;
|
|
47
47
|
case "high": return maxTokens;
|
|
48
48
|
default: return;
|
|
49
49
|
}
|
|
@@ -87,12 +87,14 @@ function convertReasoningTokensToReasoningEffort(model, reasoningTokens) {
|
|
|
87
87
|
else if (reasoningTokens === -1) {
|
|
88
88
|
if (model && getModelLevel(model) === "flash-lite") return "minimal";
|
|
89
89
|
return "high";
|
|
90
|
-
} else if (reasoningTokens === 0)
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
else if (reasoningTokens <=
|
|
94
|
-
else
|
|
95
|
-
|
|
90
|
+
} else if (reasoningTokens === 0) {
|
|
91
|
+
if (model?.startsWith("gemini-3-pro")) return "low";
|
|
92
|
+
else return "minimal";
|
|
93
|
+
} else if (reasoningTokens <= 1024) return "low";
|
|
94
|
+
else if (reasoningTokens <= 8192) {
|
|
95
|
+
if (model?.startsWith("gemini-3-pro")) return "low";
|
|
96
|
+
else return "medium";
|
|
97
|
+
} else return "high";
|
|
96
98
|
}
|
|
97
99
|
/**
|
|
98
100
|
* Infers and returns the Google platform type from the provided chat model parameters.
|
|
@@ -162,8 +164,10 @@ function convertFieldsToThinkingConfig(model, fields) {
|
|
|
162
164
|
const modelSpecialty = getModelSpecialty(model);
|
|
163
165
|
if (modelVersion === "2.5" && modelSpecialty === "image" || typeof thinkingBudget === "undefined" || typeof thinkingLevel === "undefined") return;
|
|
164
166
|
const thinkingConfig = { includeThoughts };
|
|
165
|
-
if (modelSpecialty === "")
|
|
166
|
-
|
|
167
|
+
if (modelSpecialty === "") {
|
|
168
|
+
if (model.startsWith("gemini-2.5")) thinkingConfig.thinkingBudget = thinkingBudget;
|
|
169
|
+
else thinkingConfig.thinkingLevel = thinkingLevel;
|
|
170
|
+
}
|
|
167
171
|
return thinkingConfig;
|
|
168
172
|
}
|
|
169
173
|
/**
|