@langchain/google-genai 2.1.17 → 2.1.19
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 +16 -0
- package/dist/chat_models.cjs +20 -24
- package/dist/chat_models.cjs.map +1 -1
- package/dist/chat_models.d.cts.map +1 -1
- package/dist/chat_models.d.ts.map +1 -1
- package/dist/chat_models.js +8 -11
- package/dist/chat_models.js.map +1 -1
- package/dist/embeddings.cjs +11 -16
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts +0 -1
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts +0 -1
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js +3 -7
- package/dist/embeddings.js.map +1 -1
- package/dist/index.cjs +1 -0
- package/dist/output_parsers.cjs +6 -8
- package/dist/output_parsers.cjs.map +1 -1
- package/dist/output_parsers.js +1 -2
- package/dist/output_parsers.js.map +1 -1
- package/dist/profiles.cjs +112 -85
- package/dist/profiles.cjs.map +1 -1
- package/dist/profiles.js +112 -85
- package/dist/profiles.js.map +1 -1
- package/dist/types.d.cts +2 -5
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +2 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/common.cjs +45 -54
- package/dist/utils/common.cjs.map +1 -1
- package/dist/utils/common.js +27 -35
- package/dist/utils/common.js.map +1 -1
- package/dist/utils/tools.cjs +11 -15
- package/dist/utils/tools.cjs.map +1 -1
- package/dist/utils/tools.js +2 -5
- package/dist/utils/tools.js.map +1 -1
- package/dist/utils/validate_schema.cjs.map +1 -1
- package/dist/utils/validate_schema.js.map +1 -1
- package/dist/utils/zod_to_genai_parameters.cjs +4 -7
- package/dist/utils/zod_to_genai_parameters.cjs.map +1 -1
- package/dist/utils/zod_to_genai_parameters.js +2 -4
- package/dist/utils/zod_to_genai_parameters.js.map +1 -1
- package/package.json +5 -5
- package/dist/_virtual/rolldown_runtime.cjs +0 -25
package/dist/utils/common.cjs
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
1
|
const require_zod_to_genai_parameters = require('./zod_to_genai_parameters.cjs');
|
|
3
2
|
const require_validate_schema = require('./validate_schema.cjs');
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
let _langchain_core_messages = require("@langchain/core/messages");
|
|
4
|
+
let _langchain_core_outputs = require("@langchain/core/outputs");
|
|
5
|
+
let _langchain_core_utils_function_calling = require("@langchain/core/utils/function_calling");
|
|
6
|
+
let _langchain_core_language_models_base = require("@langchain/core/language_models/base");
|
|
7
|
+
let uuid = require("uuid");
|
|
9
8
|
|
|
10
9
|
//#region src/utils/common.ts
|
|
11
10
|
const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = "__gemini_function_call_thought_signatures__";
|
|
12
11
|
const DUMMY_SIGNATURE = "ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==";
|
|
13
12
|
const iife = (fn) => fn();
|
|
14
13
|
function getMessageAuthor(message) {
|
|
15
|
-
if (
|
|
14
|
+
if (_langchain_core_messages.ChatMessage.isInstance(message)) return message.role;
|
|
16
15
|
return message.type;
|
|
17
16
|
}
|
|
18
17
|
/**
|
|
@@ -46,14 +45,14 @@ function messageContentMedia(content) {
|
|
|
46
45
|
}
|
|
47
46
|
function inferToolNameFromPreviousMessages(message, previousMessages) {
|
|
48
47
|
return previousMessages.map((msg) => {
|
|
49
|
-
if ((0,
|
|
48
|
+
if ((0, _langchain_core_messages.isAIMessage)(msg)) return msg.tool_calls ?? [];
|
|
50
49
|
return [];
|
|
51
50
|
}).flat().find((toolCall) => {
|
|
52
51
|
return toolCall.id === message.tool_call_id;
|
|
53
52
|
})?.name;
|
|
54
53
|
}
|
|
55
54
|
function _getStandardContentBlockConverter(isMultimodalModel) {
|
|
56
|
-
|
|
55
|
+
return {
|
|
57
56
|
providerName: "Google Gemini",
|
|
58
57
|
fromStandardTextBlock(block) {
|
|
59
58
|
return { text: block.text };
|
|
@@ -61,7 +60,7 @@ function _getStandardContentBlockConverter(isMultimodalModel) {
|
|
|
61
60
|
fromStandardImageBlock(block) {
|
|
62
61
|
if (!isMultimodalModel) throw new Error("This model does not support images");
|
|
63
62
|
if (block.source_type === "url") {
|
|
64
|
-
const data = (0,
|
|
63
|
+
const data = (0, _langchain_core_messages.parseBase64DataUrl)({ dataUrl: block.url });
|
|
65
64
|
if (data) return { inlineData: {
|
|
66
65
|
mimeType: data.mime_type,
|
|
67
66
|
data: data.data
|
|
@@ -80,7 +79,7 @@ function _getStandardContentBlockConverter(isMultimodalModel) {
|
|
|
80
79
|
fromStandardAudioBlock(block) {
|
|
81
80
|
if (!isMultimodalModel) throw new Error("This model does not support audio");
|
|
82
81
|
if (block.source_type === "url") {
|
|
83
|
-
const data = (0,
|
|
82
|
+
const data = (0, _langchain_core_messages.parseBase64DataUrl)({ dataUrl: block.url });
|
|
84
83
|
if (data) return { inlineData: {
|
|
85
84
|
mimeType: data.mime_type,
|
|
86
85
|
data: data.data
|
|
@@ -100,7 +99,7 @@ function _getStandardContentBlockConverter(isMultimodalModel) {
|
|
|
100
99
|
if (!isMultimodalModel) throw new Error("This model does not support files");
|
|
101
100
|
if (block.source_type === "text") return { text: block.text };
|
|
102
101
|
if (block.source_type === "url") {
|
|
103
|
-
const data = (0,
|
|
102
|
+
const data = (0, _langchain_core_messages.parseBase64DataUrl)({ dataUrl: block.url });
|
|
104
103
|
if (data) return { inlineData: {
|
|
105
104
|
mimeType: data.mime_type,
|
|
106
105
|
data: data.data
|
|
@@ -117,10 +116,9 @@ function _getStandardContentBlockConverter(isMultimodalModel) {
|
|
|
117
116
|
throw new Error(`Unsupported source type: ${block.source_type}`);
|
|
118
117
|
}
|
|
119
118
|
};
|
|
120
|
-
return standardContentBlockConverter;
|
|
121
119
|
}
|
|
122
120
|
function _convertLangChainContentToPart(content, isMultimodalModel) {
|
|
123
|
-
if ((0,
|
|
121
|
+
if ((0, _langchain_core_messages.isDataContentBlock)(content)) return (0, _langchain_core_messages.convertToProviderContentBlock)(content, _getStandardContentBlockConverter(isMultimodalModel));
|
|
124
122
|
if (content.type === "text") return { text: content.text };
|
|
125
123
|
else if (content.type === "executableCode") return { executableCode: content.executableCode };
|
|
126
124
|
else if (content.type === "codeExecutionResult") return { codeExecutionResult: content.codeExecutionResult };
|
|
@@ -151,12 +149,12 @@ function _convertLangChainContentToPart(content, isMultimodalModel) {
|
|
|
151
149
|
mimeType: content.type,
|
|
152
150
|
data: content.data
|
|
153
151
|
} };
|
|
154
|
-
else if ("functionCall" in content) return
|
|
152
|
+
else if ("functionCall" in content) return;
|
|
155
153
|
else if ("type" in content) throw new Error(`Unknown content type ${content.type}`);
|
|
156
154
|
else throw new Error(`Unknown content ${JSON.stringify(content)}`);
|
|
157
155
|
}
|
|
158
156
|
function convertMessageContentToParts(message, isMultimodalModel, previousMessages, model) {
|
|
159
|
-
if ((0,
|
|
157
|
+
if ((0, _langchain_core_messages.isToolMessage)(message)) {
|
|
160
158
|
const messageName = message.name ?? inferToolNameFromPreviousMessages(message, previousMessages);
|
|
161
159
|
if (messageName === void 0) throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${message.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);
|
|
162
160
|
const result = Array.isArray(message.content) ? message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0) : message.content;
|
|
@@ -174,7 +172,7 @@ function convertMessageContentToParts(message, isMultimodalModel, previousMessag
|
|
|
174
172
|
if (typeof message.content === "string" && message.content) messageParts.push({ text: message.content });
|
|
175
173
|
if (Array.isArray(message.content)) messageParts.push(...message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0));
|
|
176
174
|
const functionThoughtSignatures = message.additional_kwargs?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY];
|
|
177
|
-
if ((0,
|
|
175
|
+
if ((0, _langchain_core_messages.isAIMessage)(message) && message.tool_calls?.length) functionCalls = message.tool_calls.map((tc) => {
|
|
178
176
|
const thoughtSignature = iife(() => {
|
|
179
177
|
if (tc.id) {
|
|
180
178
|
const signature = functionThoughtSignatures?.[tc.id];
|
|
@@ -195,7 +193,7 @@ function convertMessageContentToParts(message, isMultimodalModel, previousMessag
|
|
|
195
193
|
}
|
|
196
194
|
function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false, model) {
|
|
197
195
|
return messages.reduce((acc, message, index) => {
|
|
198
|
-
if (!(0,
|
|
196
|
+
if (!(0, _langchain_core_messages.isBaseMessage)(message)) throw new Error("Unsupported message input");
|
|
199
197
|
const author = getMessageAuthor(message);
|
|
200
198
|
if (author === "system" && index !== 0) throw new Error("System message should be the first one");
|
|
201
199
|
const role = convertAuthorToRole(author);
|
|
@@ -203,9 +201,9 @@ function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystem
|
|
|
203
201
|
if (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) throw new Error("Google Generative AI requires alternate messages between authors");
|
|
204
202
|
const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index), model);
|
|
205
203
|
if (acc.mergeWithPreviousContent) {
|
|
206
|
-
const prevContent
|
|
207
|
-
if (!prevContent
|
|
208
|
-
prevContent
|
|
204
|
+
const prevContent = acc.content[acc.content.length - 1];
|
|
205
|
+
if (!prevContent) throw new Error("There was a problem parsing your system message. Please try a prompt without one.");
|
|
206
|
+
prevContent.parts.push(...parts);
|
|
209
207
|
return {
|
|
210
208
|
mergeWithPreviousContent: false,
|
|
211
209
|
content: acc.content
|
|
@@ -232,7 +230,7 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
232
230
|
llmOutput: { filters: response.promptFeedback }
|
|
233
231
|
};
|
|
234
232
|
const [candidate] = response.candidates;
|
|
235
|
-
const { content: candidateContent
|
|
233
|
+
const { content: candidateContent, ...generationInfo } = candidate;
|
|
236
234
|
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
237
235
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
238
236
|
...p,
|
|
@@ -286,30 +284,26 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
286
284
|
}, {});
|
|
287
285
|
let text = "";
|
|
288
286
|
if (typeof content === "string") text = content;
|
|
289
|
-
else if (Array.isArray(content) && content.length > 0)
|
|
290
|
-
const block = content.find((b) => "text" in b);
|
|
291
|
-
text = block?.text ?? text;
|
|
292
|
-
}
|
|
293
|
-
const generation = {
|
|
294
|
-
text,
|
|
295
|
-
message: new __langchain_core_messages.AIMessage({
|
|
296
|
-
content: content ?? "",
|
|
297
|
-
tool_calls: functionCalls?.map((fc) => ({
|
|
298
|
-
type: "tool_call",
|
|
299
|
-
id: fc.id,
|
|
300
|
-
name: fc.functionCall.name,
|
|
301
|
-
args: fc.functionCall.args
|
|
302
|
-
})),
|
|
303
|
-
additional_kwargs: {
|
|
304
|
-
...generationInfo,
|
|
305
|
-
[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures
|
|
306
|
-
},
|
|
307
|
-
usage_metadata: extra?.usageMetadata
|
|
308
|
-
}),
|
|
309
|
-
generationInfo
|
|
310
|
-
};
|
|
287
|
+
else if (Array.isArray(content) && content.length > 0) text = content.find((b) => "text" in b)?.text ?? text;
|
|
311
288
|
return {
|
|
312
|
-
generations: [
|
|
289
|
+
generations: [{
|
|
290
|
+
text,
|
|
291
|
+
message: new _langchain_core_messages.AIMessage({
|
|
292
|
+
content: content ?? "",
|
|
293
|
+
tool_calls: functionCalls?.map((fc) => ({
|
|
294
|
+
type: "tool_call",
|
|
295
|
+
id: fc.id,
|
|
296
|
+
name: fc.functionCall.name,
|
|
297
|
+
args: fc.functionCall.args
|
|
298
|
+
})),
|
|
299
|
+
additional_kwargs: {
|
|
300
|
+
...generationInfo,
|
|
301
|
+
[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures
|
|
302
|
+
},
|
|
303
|
+
usage_metadata: extra?.usageMetadata
|
|
304
|
+
}),
|
|
305
|
+
generationInfo
|
|
306
|
+
}],
|
|
313
307
|
llmOutput: { tokenUsage: {
|
|
314
308
|
promptTokens: extra?.usageMetadata?.input_tokens,
|
|
315
309
|
completionTokens: extra?.usageMetadata?.output_tokens,
|
|
@@ -320,7 +314,7 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
320
314
|
function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
321
315
|
if (!response.candidates || response.candidates.length === 0) return null;
|
|
322
316
|
const [candidate] = response.candidates;
|
|
323
|
-
const { content: candidateContent
|
|
317
|
+
const { content: candidateContent, ...generationInfo } = candidate;
|
|
324
318
|
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
325
319
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
326
320
|
...p,
|
|
@@ -370,10 +364,7 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
|
370
364
|
else content = [];
|
|
371
365
|
let text = "";
|
|
372
366
|
if (content && typeof content === "string") text = content;
|
|
373
|
-
else if (Array.isArray(content))
|
|
374
|
-
const block = content.find((b) => "text" in b);
|
|
375
|
-
text = block?.text ?? "";
|
|
376
|
-
}
|
|
367
|
+
else if (Array.isArray(content)) text = content.find((b) => "text" in b)?.text ?? "";
|
|
377
368
|
const toolCallChunks = [];
|
|
378
369
|
if (functionCalls) toolCallChunks.push(...functionCalls.map((fc) => ({
|
|
379
370
|
type: "tool_call_chunk",
|
|
@@ -385,9 +376,9 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
|
385
376
|
if ("thoughtSignature" in fc && typeof fc.thoughtSignature === "string") acc[fc.id] = fc.thoughtSignature;
|
|
386
377
|
return acc;
|
|
387
378
|
}, {});
|
|
388
|
-
return new
|
|
379
|
+
return new _langchain_core_outputs.ChatGenerationChunk({
|
|
389
380
|
text,
|
|
390
|
-
message: new
|
|
381
|
+
message: new _langchain_core_messages.AIMessageChunk({
|
|
391
382
|
content: content || "",
|
|
392
383
|
name: !candidateContent ? void 0 : candidateContent.role,
|
|
393
384
|
tool_call_chunks: toolCallChunks,
|
|
@@ -401,7 +392,7 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
|
401
392
|
function convertToGenerativeAITools(tools) {
|
|
402
393
|
if (tools.every((tool) => "functionDeclarations" in tool && Array.isArray(tool.functionDeclarations))) return tools;
|
|
403
394
|
return [{ functionDeclarations: tools.map((tool) => {
|
|
404
|
-
if ((0,
|
|
395
|
+
if ((0, _langchain_core_utils_function_calling.isLangChainTool)(tool)) {
|
|
405
396
|
const jsonSchema = require_zod_to_genai_parameters.schemaToGenerativeAIParameters(tool.schema);
|
|
406
397
|
if (jsonSchema.type === "object" && "properties" in jsonSchema && Object.keys(jsonSchema.properties).length === 0) return {
|
|
407
398
|
name: tool.name,
|
|
@@ -414,7 +405,7 @@ function convertToGenerativeAITools(tools) {
|
|
|
414
405
|
parameters: jsonSchema
|
|
415
406
|
};
|
|
416
407
|
}
|
|
417
|
-
if ((0,
|
|
408
|
+
if ((0, _langchain_core_language_models_base.isOpenAITool)(tool)) {
|
|
418
409
|
const params = require_zod_to_genai_parameters.jsonSchemaToGeminiParameters(tool.function.parameters);
|
|
419
410
|
require_validate_schema.assertNoEmptyStringEnums(params, tool.function.name);
|
|
420
411
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.cjs","names":["fn: () => string","message: BaseMessage","ChatMessage","author: string","content: MessageContentComplex","message: ToolMessage | ToolMessageChunk","previousMessages: BaseMessage[]","isMultimodalModel: boolean","standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }>","model?: string","functionCalls: FunctionCallPart[]","messageParts: Part[]","messages: BaseMessage[]","convertSystemMessageToHumanContent: boolean","model: string","prevContent","content: Content","response: EnhancedGenerateContentResponse","extra?: {\n usageMetadata: UsageMetadata | undefined;\n }","content: MessageContent | undefined","generation: ChatGeneration","AIMessage","extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }","toolCallChunks: ToolCallChunk[]","ChatGenerationChunk","AIMessageChunk","tools: GoogleGenerativeAIToolType[]","schemaToGenerativeAIParameters","assertNoEmptyStringEnums","jsonSchemaToGeminiParameters","usageMetadata: GenerateContentResponse[\"usageMetadata\"]","output: UsageMetadata"],"sources":["../../src/utils/common.ts"],"sourcesContent":["import {\n EnhancedGenerateContentResponse,\n Content,\n Part,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n POSSIBLE_ROLES,\n FunctionCallPart,\n TextPart,\n FileDataPart,\n InlineDataPart,\n type GenerateContentResponse,\n} from \"@google/generative-ai\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n InputTokenDetails,\n} from \"@langchain/core/messages\";\nimport {\n ChatGeneration,\n ChatGenerationChunk,\n ChatResult,\n} from \"@langchain/core/outputs\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { ToolCallChunk } from \"@langchain/core/messages/tool\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from \"./zod_to_genai_parameters.js\";\nimport {\n GoogleGenerativeAIPart,\n GoogleGenerativeAIToolType,\n} from \"../types.js\";\nimport { assertNoEmptyStringEnums } from \"./validate_schema.js\";\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n \"__gemini_function_call_thought_signatures__\";\nconst DUMMY_SIGNATURE =\n \"ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==\";\n\nconst iife = (fn: () => string) => fn();\n\nexport function getMessageAuthor(message: BaseMessage) {\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n return message.type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case \"supervisor\":\n case \"ai\":\n case \"model\":\n return \"model\";\n case \"system\":\n return \"system\";\n case \"human\":\n return \"user\";\n case \"tool\":\n case \"function\":\n return \"function\";\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error(\"Invalid media content\");\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(isMultimodalModel: boolean) {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: \"Google Gemini\",\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support images\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support audio\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support files\");\n }\n if (block.source_type === \"text\") {\n return {\n text: block.text,\n };\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (content.type === \"text\") {\n return { text: content.text };\n } else if (content.type === \"executableCode\") {\n return { executableCode: content.executableCode };\n } else if (content.type === \"codeExecutionResult\") {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === \"image_url\") {\n if (!isMultimodalModel) {\n throw new Error(`This model does not support images`);\n }\n let source;\n if (typeof content.image_url === \"string\") {\n source = content.image_url;\n } else if (\n typeof content.image_url === \"object\" &&\n \"url\" in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n const [dm, data] = source.split(\",\");\n if (!dm.startsWith(\"data:\")) {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, \"\").split(\";\");\n if (encoding !== \"base64\") {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === \"media\") {\n return messageContentMedia(content);\n } else if (content.type === \"tool_use\") {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (content.type === \"tool_call\") {\n return {\n functionCall: {\n name: content.name,\n args: content.args,\n },\n };\n } else if (\n content.type?.includes(\"/\") &&\n // Ensure it's a single slash.\n content.type.split(\"/\").length === 2 &&\n \"data\" in content &&\n typeof content.data === \"string\"\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if (\"functionCall\" in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if (\"type\" in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === \"error\") {\n return [\n {\n functionResponse: {\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n },\n },\n ];\n }\n\n return [\n {\n functionResponse: {\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n },\n },\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === \"string\" && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = message.additional_kwargs?.[\n _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY\n ] as Record<string, string>;\n\n if (isAIMessage(message) && message.tool_calls?.length) {\n functionCalls = message.tool_calls.map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id) {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature) {\n return signature;\n }\n }\n if (model?.includes(\"gemini-3\")) {\n return DUMMY_SIGNATURE;\n }\n return \"\";\n });\n return {\n functionCall: {\n name: tc.name,\n args: tc.args,\n },\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n model: string\n) {\n return messages.reduce<{\n content: Content[];\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error(\"Unsupported message input\");\n }\n const author = getMessageAuthor(message);\n if (author === \"system\" && index !== 0) {\n throw new Error(\"System message should be the first one\");\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n \"Google Generative AI requires alternate messages between authors\"\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n \"There was a problem parsing your system message. Please try a prompt without one.\"\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === \"function\" ||\n (actualRole === \"system\" && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = \"user\";\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === \"system\" && !convertSystemMessageToHumanContent,\n content: [...acc.content, content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n // if rejected or error, return empty generations with reason in filters\n if (\n !response.candidates ||\n response.candidates.length === 0 ||\n !response.candidates[0]\n ) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n\n const parts = candidateContent?.parts as GoogleGenerativeAIPart[] | undefined;\n\n if (\n Array.isArray(parts) &&\n parts.length === 1 &&\n \"text\" in parts[0] &&\n parts[0].text &&\n !parts[0].thought\n ) {\n content = parts[0].text;\n } else if (Array.isArray(parts) && parts.length > 0) {\n content = parts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n const functionThoughtSignatures = functionCalls?.reduce(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content: content ?? \"\",\n tool_calls: functionCalls?.map((fc) => ({\n type: \"tool_call\",\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n })),\n additional_kwargs: {\n ...generationInfo,\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n const streamParts = candidateContent?.parts as\n | GoogleGenerativeAIPart[]\n | undefined;\n\n // Checks if all parts are plain text (no thought flags). If so, join as string.\n if (\n Array.isArray(streamParts) &&\n streamParts.every((p) => \"text\" in p && !p.thought)\n ) {\n content = streamParts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(streamParts)) {\n content = streamParts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = \"\";\n if (content && typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? \"\";\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: \"tool_call_chunk\" as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: JSON.stringify(fc.functionCall.args),\n }))\n );\n }\n\n const functionThoughtSignatures = functionCalls?.reduce(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content || \"\",\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs: {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n response_metadata: {\n model_provider: \"google-genai\",\n },\n usage_metadata: extra.usageMetadata,\n }),\n generationInfo,\n });\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n \"functionDeclarations\" in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === \"object\" &&\n \"properties\" in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n assertNoEmptyStringEnums(jsonSchema, tool.name);\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n const params = jsonSchemaToGeminiParameters(\n tool.function.parameters\n );\n assertNoEmptyStringEnums(params, tool.function.name);\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: params,\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n\nexport function convertUsageMetadata(\n usageMetadata: GenerateContentResponse[\"usageMetadata\"],\n model: string\n): UsageMetadata {\n const output: UsageMetadata = {\n input_tokens: usageMetadata?.promptTokenCount ?? 0,\n output_tokens: usageMetadata?.candidatesTokenCount ?? 0,\n total_tokens: usageMetadata?.totalTokenCount ?? 0,\n };\n if (usageMetadata?.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n // FIXME(hntrl): move this usageMetadata calculation elsewhere\n if (model === \"gemini-3-pro-preview\") {\n const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? 0 - 200000);\n const cachedOver200k = Math.max(\n 0,\n usageMetadata?.cachedContentTokenCount ?? 0 - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n return output;\n}\n"],"mappings":";;;;;;;;;;AAmDA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,OAAO,CAACA,OAAqB,IAAI;AAEvC,SAAgB,iBAAiBC,SAAsB;AACrD,KAAI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ACb;EACF;AACD,SAAO;CACR,EACF,CACF,CACF;AACF;AAED,SAAgB,qBACdE,eACAhB,OACe;CACf,MAAMiB,SAAwB;EAC5B,cAAc,eAAe,oBAAoB;EACjD,eAAe,eAAe,wBAAwB;EACtD,cAAc,eAAe,mBAAmB;CACjD;AACD,KAAI,eAAe,yBAAyB;EAC1C,OAAO,wBAAwB,CAAE;EACjC,OAAO,oBAAoB,aACzB,cAAc;CACjB;AAGD,KAAI,UAAU,wBAAwB;EACpC,MAAM,WAAW,KAAK,IAAI,GAAG,eAAe,oBAAoB,KAAW;EAC3E,MAAM,iBAAiB,KAAK,IAC1B,GACA,eAAe,2BAA2B,KAC3C;AACD,MAAI,UACF,OAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,WAAW;EACZ;AAEH,MAAI,gBACF,OAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,sBAAsB;EACvB;CAEJ;AACD,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"common.cjs","names":["ChatMessage","AIMessage","ChatGenerationChunk","AIMessageChunk","schemaToGenerativeAIParameters","jsonSchemaToGeminiParameters"],"sources":["../../src/utils/common.ts"],"sourcesContent":["import {\n EnhancedGenerateContentResponse,\n Content,\n Part,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n POSSIBLE_ROLES,\n FunctionCallPart,\n TextPart,\n FileDataPart,\n InlineDataPart,\n type GenerateContentResponse,\n} from \"@google/generative-ai\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n InputTokenDetails,\n} from \"@langchain/core/messages\";\nimport {\n ChatGeneration,\n ChatGenerationChunk,\n ChatResult,\n} from \"@langchain/core/outputs\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { ToolCallChunk } from \"@langchain/core/messages/tool\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from \"./zod_to_genai_parameters.js\";\nimport {\n GoogleGenerativeAIPart,\n GoogleGenerativeAIToolType,\n} from \"../types.js\";\nimport { assertNoEmptyStringEnums } from \"./validate_schema.js\";\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n \"__gemini_function_call_thought_signatures__\";\nconst DUMMY_SIGNATURE =\n \"ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==\";\n\nconst iife = (fn: () => string) => fn();\n\nexport function getMessageAuthor(message: BaseMessage) {\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n return message.type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case \"supervisor\":\n case \"ai\":\n case \"model\":\n return \"model\";\n case \"system\":\n return \"system\";\n case \"human\":\n return \"user\";\n case \"tool\":\n case \"function\":\n return \"function\";\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error(\"Invalid media content\");\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(isMultimodalModel: boolean) {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: \"Google Gemini\",\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support images\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support audio\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support files\");\n }\n if (block.source_type === \"text\") {\n return {\n text: block.text,\n };\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (content.type === \"text\") {\n return { text: content.text };\n } else if (content.type === \"executableCode\") {\n return { executableCode: content.executableCode };\n } else if (content.type === \"codeExecutionResult\") {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === \"image_url\") {\n if (!isMultimodalModel) {\n throw new Error(`This model does not support images`);\n }\n let source;\n if (typeof content.image_url === \"string\") {\n source = content.image_url;\n } else if (\n typeof content.image_url === \"object\" &&\n \"url\" in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n const [dm, data] = source.split(\",\");\n if (!dm.startsWith(\"data:\")) {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, \"\").split(\";\");\n if (encoding !== \"base64\") {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === \"media\") {\n return messageContentMedia(content);\n } else if (content.type === \"tool_use\") {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (content.type === \"tool_call\") {\n return {\n functionCall: {\n name: content.name,\n args: content.args,\n },\n };\n } else if (\n content.type?.includes(\"/\") &&\n // Ensure it's a single slash.\n content.type.split(\"/\").length === 2 &&\n \"data\" in content &&\n typeof content.data === \"string\"\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if (\"functionCall\" in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if (\"type\" in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === \"error\") {\n return [\n {\n functionResponse: {\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n },\n },\n ];\n }\n\n return [\n {\n functionResponse: {\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n },\n },\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === \"string\" && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = message.additional_kwargs?.[\n _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY\n ] as Record<string, string>;\n\n if (isAIMessage(message) && message.tool_calls?.length) {\n functionCalls = message.tool_calls.map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id) {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature) {\n return signature;\n }\n }\n if (model?.includes(\"gemini-3\")) {\n return DUMMY_SIGNATURE;\n }\n return \"\";\n });\n return {\n functionCall: {\n name: tc.name,\n args: tc.args,\n },\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n model: string\n) {\n return messages.reduce<{\n content: Content[];\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error(\"Unsupported message input\");\n }\n const author = getMessageAuthor(message);\n if (author === \"system\" && index !== 0) {\n throw new Error(\"System message should be the first one\");\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n \"Google Generative AI requires alternate messages between authors\"\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n \"There was a problem parsing your system message. Please try a prompt without one.\"\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === \"function\" ||\n (actualRole === \"system\" && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = \"user\";\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === \"system\" && !convertSystemMessageToHumanContent,\n content: [...acc.content, content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n // if rejected or error, return empty generations with reason in filters\n if (\n !response.candidates ||\n response.candidates.length === 0 ||\n !response.candidates[0]\n ) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n\n const parts = candidateContent?.parts as GoogleGenerativeAIPart[] | undefined;\n\n if (\n Array.isArray(parts) &&\n parts.length === 1 &&\n \"text\" in parts[0] &&\n parts[0].text &&\n !parts[0].thought\n ) {\n content = parts[0].text;\n } else if (Array.isArray(parts) && parts.length > 0) {\n content = parts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n const functionThoughtSignatures = functionCalls?.reduce(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content: content ?? \"\",\n tool_calls: functionCalls?.map((fc) => ({\n type: \"tool_call\",\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n })),\n additional_kwargs: {\n ...generationInfo,\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n const streamParts = candidateContent?.parts as\n | GoogleGenerativeAIPart[]\n | undefined;\n\n // Checks if all parts are plain text (no thought flags). If so, join as string.\n if (\n Array.isArray(streamParts) &&\n streamParts.every((p) => \"text\" in p && !p.thought)\n ) {\n content = streamParts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(streamParts)) {\n content = streamParts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = \"\";\n if (content && typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? \"\";\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: \"tool_call_chunk\" as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: JSON.stringify(fc.functionCall.args),\n }))\n );\n }\n\n const functionThoughtSignatures = functionCalls?.reduce(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content || \"\",\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs: {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n response_metadata: {\n model_provider: \"google-genai\",\n },\n usage_metadata: extra.usageMetadata,\n }),\n generationInfo,\n });\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n \"functionDeclarations\" in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === \"object\" &&\n \"properties\" in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n assertNoEmptyStringEnums(jsonSchema, tool.name);\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n const params = jsonSchemaToGeminiParameters(\n tool.function.parameters\n );\n assertNoEmptyStringEnums(params, tool.function.name);\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: params,\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n\nexport function convertUsageMetadata(\n usageMetadata: GenerateContentResponse[\"usageMetadata\"],\n model: string\n): UsageMetadata {\n const output: UsageMetadata = {\n input_tokens: usageMetadata?.promptTokenCount ?? 0,\n output_tokens: usageMetadata?.candidatesTokenCount ?? 0,\n total_tokens: usageMetadata?.totalTokenCount ?? 0,\n };\n if (usageMetadata?.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n // FIXME(hntrl): move this usageMetadata calculation elsewhere\n if (model === \"gemini-3-pro-preview\") {\n const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? 0 - 200000);\n const cachedOver200k = Math.max(\n 0,\n usageMetadata?.cachedContentTokenCount ?? 0 - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n return output;\n}\n"],"mappings":";;;;;;;;;AAmDA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,QAAQ,OAAqB,IAAI;AAEvC,SAAgB,iBAAiB,SAAsB;AACrD,KAAIA,qCAAY,WAAW,QAAQ,CACjC,QAAO,QAAQ;AAEjB,QAAO,QAAQ;;;;;;;;AASjB,SAAgB,oBACd,QACiC;AACjC,SAAQ,QAAR;EAKE,KAAK;EACL,KAA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@ -52,7 +52,7 @@ function inferToolNameFromPreviousMessages(message, previousMessages) {
|
|
|
52
52
|
})?.name;
|
|
53
53
|
}
|
|
54
54
|
function _getStandardContentBlockConverter(isMultimodalModel) {
|
|
55
|
-
|
|
55
|
+
return {
|
|
56
56
|
providerName: "Google Gemini",
|
|
57
57
|
fromStandardTextBlock(block) {
|
|
58
58
|
return { text: block.text };
|
|
@@ -116,7 +116,6 @@ function _getStandardContentBlockConverter(isMultimodalModel) {
|
|
|
116
116
|
throw new Error(`Unsupported source type: ${block.source_type}`);
|
|
117
117
|
}
|
|
118
118
|
};
|
|
119
|
-
return standardContentBlockConverter;
|
|
120
119
|
}
|
|
121
120
|
function _convertLangChainContentToPart(content, isMultimodalModel) {
|
|
122
121
|
if (isDataContentBlock(content)) return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel));
|
|
@@ -150,7 +149,7 @@ function _convertLangChainContentToPart(content, isMultimodalModel) {
|
|
|
150
149
|
mimeType: content.type,
|
|
151
150
|
data: content.data
|
|
152
151
|
} };
|
|
153
|
-
else if ("functionCall" in content) return
|
|
152
|
+
else if ("functionCall" in content) return;
|
|
154
153
|
else if ("type" in content) throw new Error(`Unknown content type ${content.type}`);
|
|
155
154
|
else throw new Error(`Unknown content ${JSON.stringify(content)}`);
|
|
156
155
|
}
|
|
@@ -202,9 +201,9 @@ function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystem
|
|
|
202
201
|
if (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) throw new Error("Google Generative AI requires alternate messages between authors");
|
|
203
202
|
const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index), model);
|
|
204
203
|
if (acc.mergeWithPreviousContent) {
|
|
205
|
-
const prevContent
|
|
206
|
-
if (!prevContent
|
|
207
|
-
prevContent
|
|
204
|
+
const prevContent = acc.content[acc.content.length - 1];
|
|
205
|
+
if (!prevContent) throw new Error("There was a problem parsing your system message. Please try a prompt without one.");
|
|
206
|
+
prevContent.parts.push(...parts);
|
|
208
207
|
return {
|
|
209
208
|
mergeWithPreviousContent: false,
|
|
210
209
|
content: acc.content
|
|
@@ -231,7 +230,7 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
231
230
|
llmOutput: { filters: response.promptFeedback }
|
|
232
231
|
};
|
|
233
232
|
const [candidate] = response.candidates;
|
|
234
|
-
const { content: candidateContent
|
|
233
|
+
const { content: candidateContent, ...generationInfo } = candidate;
|
|
235
234
|
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
236
235
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
237
236
|
...p,
|
|
@@ -285,30 +284,26 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
285
284
|
}, {});
|
|
286
285
|
let text = "";
|
|
287
286
|
if (typeof content === "string") text = content;
|
|
288
|
-
else if (Array.isArray(content) && content.length > 0)
|
|
289
|
-
const block = content.find((b) => "text" in b);
|
|
290
|
-
text = block?.text ?? text;
|
|
291
|
-
}
|
|
292
|
-
const generation = {
|
|
293
|
-
text,
|
|
294
|
-
message: new AIMessage({
|
|
295
|
-
content: content ?? "",
|
|
296
|
-
tool_calls: functionCalls?.map((fc) => ({
|
|
297
|
-
type: "tool_call",
|
|
298
|
-
id: fc.id,
|
|
299
|
-
name: fc.functionCall.name,
|
|
300
|
-
args: fc.functionCall.args
|
|
301
|
-
})),
|
|
302
|
-
additional_kwargs: {
|
|
303
|
-
...generationInfo,
|
|
304
|
-
[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures
|
|
305
|
-
},
|
|
306
|
-
usage_metadata: extra?.usageMetadata
|
|
307
|
-
}),
|
|
308
|
-
generationInfo
|
|
309
|
-
};
|
|
287
|
+
else if (Array.isArray(content) && content.length > 0) text = content.find((b) => "text" in b)?.text ?? text;
|
|
310
288
|
return {
|
|
311
|
-
generations: [
|
|
289
|
+
generations: [{
|
|
290
|
+
text,
|
|
291
|
+
message: new AIMessage({
|
|
292
|
+
content: content ?? "",
|
|
293
|
+
tool_calls: functionCalls?.map((fc) => ({
|
|
294
|
+
type: "tool_call",
|
|
295
|
+
id: fc.id,
|
|
296
|
+
name: fc.functionCall.name,
|
|
297
|
+
args: fc.functionCall.args
|
|
298
|
+
})),
|
|
299
|
+
additional_kwargs: {
|
|
300
|
+
...generationInfo,
|
|
301
|
+
[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures
|
|
302
|
+
},
|
|
303
|
+
usage_metadata: extra?.usageMetadata
|
|
304
|
+
}),
|
|
305
|
+
generationInfo
|
|
306
|
+
}],
|
|
312
307
|
llmOutput: { tokenUsage: {
|
|
313
308
|
promptTokens: extra?.usageMetadata?.input_tokens,
|
|
314
309
|
completionTokens: extra?.usageMetadata?.output_tokens,
|
|
@@ -319,7 +314,7 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
319
314
|
function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
320
315
|
if (!response.candidates || response.candidates.length === 0) return null;
|
|
321
316
|
const [candidate] = response.candidates;
|
|
322
|
-
const { content: candidateContent
|
|
317
|
+
const { content: candidateContent, ...generationInfo } = candidate;
|
|
323
318
|
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
324
319
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
325
320
|
...p,
|
|
@@ -369,10 +364,7 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
|
369
364
|
else content = [];
|
|
370
365
|
let text = "";
|
|
371
366
|
if (content && typeof content === "string") text = content;
|
|
372
|
-
else if (Array.isArray(content))
|
|
373
|
-
const block = content.find((b) => "text" in b);
|
|
374
|
-
text = block?.text ?? "";
|
|
375
|
-
}
|
|
367
|
+
else if (Array.isArray(content)) text = content.find((b) => "text" in b)?.text ?? "";
|
|
376
368
|
const toolCallChunks = [];
|
|
377
369
|
if (functionCalls) toolCallChunks.push(...functionCalls.map((fc) => ({
|
|
378
370
|
type: "tool_call_chunk",
|