@langchain/google-genai 0.2.18 → 1.0.0

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +6 -6
  3. package/README.md +8 -8
  4. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  5. package/dist/chat_models.cjs +667 -847
  6. package/dist/chat_models.cjs.map +1 -0
  7. package/dist/chat_models.d.cts +556 -0
  8. package/dist/chat_models.d.cts.map +1 -0
  9. package/dist/chat_models.d.ts +171 -157
  10. package/dist/chat_models.d.ts.map +1 -0
  11. package/dist/chat_models.js +665 -842
  12. package/dist/chat_models.js.map +1 -0
  13. package/dist/embeddings.cjs +97 -151
  14. package/dist/embeddings.cjs.map +1 -0
  15. package/dist/embeddings.d.cts +104 -0
  16. package/dist/embeddings.d.cts.map +1 -0
  17. package/dist/embeddings.d.ts +76 -70
  18. package/dist/embeddings.d.ts.map +1 -0
  19. package/dist/embeddings.js +93 -144
  20. package/dist/embeddings.js.map +1 -0
  21. package/dist/index.cjs +5 -18
  22. package/dist/index.d.cts +3 -0
  23. package/dist/index.d.ts +3 -2
  24. package/dist/index.js +4 -2
  25. package/dist/output_parsers.cjs +47 -75
  26. package/dist/output_parsers.cjs.map +1 -0
  27. package/dist/output_parsers.js +47 -72
  28. package/dist/output_parsers.js.map +1 -0
  29. package/dist/types.d.cts +8 -0
  30. package/dist/types.d.cts.map +1 -0
  31. package/dist/types.d.ts +7 -2
  32. package/dist/types.d.ts.map +1 -0
  33. package/dist/utils/common.cjs +356 -549
  34. package/dist/utils/common.cjs.map +1 -0
  35. package/dist/utils/common.js +357 -545
  36. package/dist/utils/common.js.map +1 -0
  37. package/dist/utils/tools.cjs +65 -102
  38. package/dist/utils/tools.cjs.map +1 -0
  39. package/dist/utils/tools.js +64 -99
  40. package/dist/utils/tools.js.map +1 -0
  41. package/dist/utils/zod_to_genai_parameters.cjs +31 -49
  42. package/dist/utils/zod_to_genai_parameters.cjs.map +1 -0
  43. package/dist/utils/zod_to_genai_parameters.js +29 -45
  44. package/dist/utils/zod_to_genai_parameters.js.map +1 -0
  45. package/package.json +42 -51
  46. package/dist/output_parsers.d.ts +0 -20
  47. package/dist/types.cjs +0 -2
  48. package/dist/types.js +0 -1
  49. package/dist/utils/common.d.ts +0 -22
  50. package/dist/utils/tools.d.ts +0 -10
  51. package/dist/utils/zod_to_genai_parameters.d.ts +0 -14
  52. package/index.cjs +0 -1
  53. package/index.d.cts +0 -1
  54. package/index.d.ts +0 -1
  55. package/index.js +0 -1
@@ -1,563 +1,375 @@
1
- import { AIMessage, AIMessageChunk, ChatMessage, isAIMessage, isBaseMessage, isToolMessage, parseBase64DataUrl, convertToProviderContentBlock, isDataContentBlock, } from "@langchain/core/messages";
2
- import { ChatGenerationChunk, } from "@langchain/core/outputs";
1
+ import { jsonSchemaToGeminiParameters, schemaToGenerativeAIParameters } from "./zod_to_genai_parameters.js";
2
+ import { AIMessage, AIMessageChunk, ChatMessage, convertToProviderContentBlock, isAIMessage, isBaseMessage, isDataContentBlock, isToolMessage, parseBase64DataUrl } from "@langchain/core/messages";
3
+ import { ChatGenerationChunk } from "@langchain/core/outputs";
3
4
  import { isLangChainTool } from "@langchain/core/utils/function_calling";
4
5
  import { isOpenAITool } from "@langchain/core/language_models/base";
5
- import { v4 as uuidv4 } from "uuid";
6
- import { jsonSchemaToGeminiParameters, schemaToGenerativeAIParameters, } from "./zod_to_genai_parameters.js";
7
- export function getMessageAuthor(message) {
8
- const type = message._getType();
9
- if (ChatMessage.isInstance(message)) {
10
- return message.role;
11
- }
12
- if (type === "tool") {
13
- return type;
14
- }
15
- return message.name ?? type;
6
+ import { v4 } from "uuid";
7
+
8
+ //#region src/utils/common.ts
9
+ function getMessageAuthor(message) {
10
+ const type = message._getType();
11
+ if (ChatMessage.isInstance(message)) return message.role;
12
+ if (type === "tool") return type;
13
+ return message.name ?? type;
16
14
  }
17
15
  /**
18
- * Maps a message type to a Google Generative AI chat author.
19
- * @param message The message to map.
20
- * @param model The model to use for mapping.
21
- * @returns The message type mapped to a Google Generative AI chat author.
22
- */
23
- export function convertAuthorToRole(author) {
24
- switch (author) {
25
- /**
26
- * Note: Gemini currently is not supporting system messages
27
- * we will convert them to human messages and merge with following
28
- * */
29
- case "supervisor":
30
- case "ai":
31
- case "model": // getMessageAuthor returns message.name. code ex.: return message.name ?? type;
32
- return "model";
33
- case "system":
34
- return "system";
35
- case "human":
36
- return "user";
37
- case "tool":
38
- case "function":
39
- return "function";
40
- default:
41
- throw new Error(`Unknown / unsupported author: ${author}`);
42
- }
16
+ * Maps a message type to a Google Generative AI chat author.
17
+ * @param message The message to map.
18
+ * @param model The model to use for mapping.
19
+ * @returns The message type mapped to a Google Generative AI chat author.
20
+ */
21
+ function convertAuthorToRole(author) {
22
+ switch (author) {
23
+ case "supervisor":
24
+ case "ai":
25
+ case "model": return "model";
26
+ case "system": return "system";
27
+ case "human": return "user";
28
+ case "tool":
29
+ case "function": return "function";
30
+ default: throw new Error(`Unknown / unsupported author: ${author}`);
31
+ }
43
32
  }
44
33
  function messageContentMedia(content) {
45
- if ("mimeType" in content && "data" in content) {
46
- return {
47
- inlineData: {
48
- mimeType: content.mimeType,
49
- data: content.data,
50
- },
51
- };
52
- }
53
- if ("mimeType" in content && "fileUri" in content) {
54
- return {
55
- fileData: {
56
- mimeType: content.mimeType,
57
- fileUri: content.fileUri,
58
- },
59
- };
60
- }
61
- throw new Error("Invalid media content");
34
+ if ("mimeType" in content && "data" in content) return { inlineData: {
35
+ mimeType: content.mimeType,
36
+ data: content.data
37
+ } };
38
+ if ("mimeType" in content && "fileUri" in content) return { fileData: {
39
+ mimeType: content.mimeType,
40
+ fileUri: content.fileUri
41
+ } };
42
+ throw new Error("Invalid media content");
62
43
  }
63
44
  function inferToolNameFromPreviousMessages(message, previousMessages) {
64
- return previousMessages
65
- .map((msg) => {
66
- if (isAIMessage(msg)) {
67
- return msg.tool_calls ?? [];
68
- }
69
- return [];
70
- })
71
- .flat()
72
- .find((toolCall) => {
73
- return toolCall.id === message.tool_call_id;
74
- })?.name;
45
+ return previousMessages.map((msg) => {
46
+ if (isAIMessage(msg)) return msg.tool_calls ?? [];
47
+ return [];
48
+ }).flat().find((toolCall) => {
49
+ return toolCall.id === message.tool_call_id;
50
+ })?.name;
75
51
  }
76
52
  function _getStandardContentBlockConverter(isMultimodalModel) {
77
- const standardContentBlockConverter = {
78
- providerName: "Google Gemini",
79
- fromStandardTextBlock(block) {
80
- return {
81
- text: block.text,
82
- };
83
- },
84
- fromStandardImageBlock(block) {
85
- if (!isMultimodalModel) {
86
- throw new Error("This model does not support images");
87
- }
88
- if (block.source_type === "url") {
89
- const data = parseBase64DataUrl({ dataUrl: block.url });
90
- if (data) {
91
- return {
92
- inlineData: {
93
- mimeType: data.mime_type,
94
- data: data.data,
95
- },
96
- };
97
- }
98
- else {
99
- return {
100
- fileData: {
101
- mimeType: block.mime_type ?? "",
102
- fileUri: block.url,
103
- },
104
- };
105
- }
106
- }
107
- if (block.source_type === "base64") {
108
- return {
109
- inlineData: {
110
- mimeType: block.mime_type ?? "",
111
- data: block.data,
112
- },
113
- };
114
- }
115
- throw new Error(`Unsupported source type: ${block.source_type}`);
116
- },
117
- fromStandardAudioBlock(block) {
118
- if (!isMultimodalModel) {
119
- throw new Error("This model does not support audio");
120
- }
121
- if (block.source_type === "url") {
122
- const data = parseBase64DataUrl({ dataUrl: block.url });
123
- if (data) {
124
- return {
125
- inlineData: {
126
- mimeType: data.mime_type,
127
- data: data.data,
128
- },
129
- };
130
- }
131
- else {
132
- return {
133
- fileData: {
134
- mimeType: block.mime_type ?? "",
135
- fileUri: block.url,
136
- },
137
- };
138
- }
139
- }
140
- if (block.source_type === "base64") {
141
- return {
142
- inlineData: {
143
- mimeType: block.mime_type ?? "",
144
- data: block.data,
145
- },
146
- };
147
- }
148
- throw new Error(`Unsupported source type: ${block.source_type}`);
149
- },
150
- fromStandardFileBlock(block) {
151
- if (!isMultimodalModel) {
152
- throw new Error("This model does not support files");
153
- }
154
- if (block.source_type === "text") {
155
- return {
156
- text: block.text,
157
- };
158
- }
159
- if (block.source_type === "url") {
160
- const data = parseBase64DataUrl({ dataUrl: block.url });
161
- if (data) {
162
- return {
163
- inlineData: {
164
- mimeType: data.mime_type,
165
- data: data.data,
166
- },
167
- };
168
- }
169
- else {
170
- return {
171
- fileData: {
172
- mimeType: block.mime_type ?? "",
173
- fileUri: block.url,
174
- },
175
- };
176
- }
177
- }
178
- if (block.source_type === "base64") {
179
- return {
180
- inlineData: {
181
- mimeType: block.mime_type ?? "",
182
- data: block.data,
183
- },
184
- };
185
- }
186
- throw new Error(`Unsupported source type: ${block.source_type}`);
187
- },
188
- };
189
- return standardContentBlockConverter;
53
+ const standardContentBlockConverter = {
54
+ providerName: "Google Gemini",
55
+ fromStandardTextBlock(block) {
56
+ return { text: block.text };
57
+ },
58
+ fromStandardImageBlock(block) {
59
+ if (!isMultimodalModel) throw new Error("This model does not support images");
60
+ if (block.source_type === "url") {
61
+ const data = parseBase64DataUrl({ dataUrl: block.url });
62
+ if (data) return { inlineData: {
63
+ mimeType: data.mime_type,
64
+ data: data.data
65
+ } };
66
+ else return { fileData: {
67
+ mimeType: block.mime_type ?? "",
68
+ fileUri: block.url
69
+ } };
70
+ }
71
+ if (block.source_type === "base64") return { inlineData: {
72
+ mimeType: block.mime_type ?? "",
73
+ data: block.data
74
+ } };
75
+ throw new Error(`Unsupported source type: ${block.source_type}`);
76
+ },
77
+ fromStandardAudioBlock(block) {
78
+ if (!isMultimodalModel) throw new Error("This model does not support audio");
79
+ if (block.source_type === "url") {
80
+ const data = parseBase64DataUrl({ dataUrl: block.url });
81
+ if (data) return { inlineData: {
82
+ mimeType: data.mime_type,
83
+ data: data.data
84
+ } };
85
+ else return { fileData: {
86
+ mimeType: block.mime_type ?? "",
87
+ fileUri: block.url
88
+ } };
89
+ }
90
+ if (block.source_type === "base64") return { inlineData: {
91
+ mimeType: block.mime_type ?? "",
92
+ data: block.data
93
+ } };
94
+ throw new Error(`Unsupported source type: ${block.source_type}`);
95
+ },
96
+ fromStandardFileBlock(block) {
97
+ if (!isMultimodalModel) throw new Error("This model does not support files");
98
+ if (block.source_type === "text") return { text: block.text };
99
+ if (block.source_type === "url") {
100
+ const data = parseBase64DataUrl({ dataUrl: block.url });
101
+ if (data) return { inlineData: {
102
+ mimeType: data.mime_type,
103
+ data: data.data
104
+ } };
105
+ else return { fileData: {
106
+ mimeType: block.mime_type ?? "",
107
+ fileUri: block.url
108
+ } };
109
+ }
110
+ if (block.source_type === "base64") return { inlineData: {
111
+ mimeType: block.mime_type ?? "",
112
+ data: block.data
113
+ } };
114
+ throw new Error(`Unsupported source type: ${block.source_type}`);
115
+ }
116
+ };
117
+ return standardContentBlockConverter;
190
118
  }
191
119
  function _convertLangChainContentToPart(content, isMultimodalModel) {
192
- if (isDataContentBlock(content)) {
193
- return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel));
194
- }
195
- if (content.type === "text") {
196
- return { text: content.text };
197
- }
198
- else if (content.type === "executableCode") {
199
- return { executableCode: content.executableCode };
200
- }
201
- else if (content.type === "codeExecutionResult") {
202
- return { codeExecutionResult: content.codeExecutionResult };
203
- }
204
- else if (content.type === "image_url") {
205
- if (!isMultimodalModel) {
206
- throw new Error(`This model does not support images`);
207
- }
208
- let source;
209
- if (typeof content.image_url === "string") {
210
- source = content.image_url;
211
- }
212
- else if (typeof content.image_url === "object" &&
213
- "url" in content.image_url) {
214
- source = content.image_url.url;
215
- }
216
- else {
217
- throw new Error("Please provide image as base64 encoded data URL");
218
- }
219
- const [dm, data] = source.split(",");
220
- if (!dm.startsWith("data:")) {
221
- throw new Error("Please provide image as base64 encoded data URL");
222
- }
223
- const [mimeType, encoding] = dm.replace(/^data:/, "").split(";");
224
- if (encoding !== "base64") {
225
- throw new Error("Please provide image as base64 encoded data URL");
226
- }
227
- return {
228
- inlineData: {
229
- data,
230
- mimeType,
231
- },
232
- };
233
- }
234
- else if (content.type === "media") {
235
- return messageContentMedia(content);
236
- }
237
- else if (content.type === "tool_use") {
238
- return {
239
- functionCall: {
240
- name: content.name,
241
- args: content.input,
242
- },
243
- };
244
- }
245
- else if (content.type?.includes("/") &&
246
- // Ensure it's a single slash.
247
- content.type.split("/").length === 2 &&
248
- "data" in content &&
249
- typeof content.data === "string") {
250
- return {
251
- inlineData: {
252
- mimeType: content.type,
253
- data: content.data,
254
- },
255
- };
256
- }
257
- else if ("functionCall" in content) {
258
- // No action needed here — function calls will be added later from message.tool_calls
259
- return undefined;
260
- }
261
- else {
262
- if ("type" in content) {
263
- throw new Error(`Unknown content type ${content.type}`);
264
- }
265
- else {
266
- throw new Error(`Unknown content ${JSON.stringify(content)}`);
267
- }
268
- }
120
+ if (isDataContentBlock(content)) return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel));
121
+ if (content.type === "text") return { text: content.text };
122
+ else if (content.type === "executableCode") return { executableCode: content.executableCode };
123
+ else if (content.type === "codeExecutionResult") return { codeExecutionResult: content.codeExecutionResult };
124
+ else if (content.type === "image_url") {
125
+ if (!isMultimodalModel) throw new Error(`This model does not support images`);
126
+ let source;
127
+ if (typeof content.image_url === "string") source = content.image_url;
128
+ else if (typeof content.image_url === "object" && "url" in content.image_url) source = content.image_url.url;
129
+ else throw new Error("Please provide image as base64 encoded data URL");
130
+ const [dm, data] = source.split(",");
131
+ if (!dm.startsWith("data:")) throw new Error("Please provide image as base64 encoded data URL");
132
+ const [mimeType, encoding] = dm.replace(/^data:/, "").split(";");
133
+ if (encoding !== "base64") throw new Error("Please provide image as base64 encoded data URL");
134
+ return { inlineData: {
135
+ data,
136
+ mimeType
137
+ } };
138
+ } else if (content.type === "media") return messageContentMedia(content);
139
+ else if (content.type === "tool_use") return { functionCall: {
140
+ name: content.name,
141
+ args: content.input
142
+ } };
143
+ else if (content.type?.includes("/") && content.type.split("/").length === 2 && "data" in content && typeof content.data === "string") return { inlineData: {
144
+ mimeType: content.type,
145
+ data: content.data
146
+ } };
147
+ else if ("functionCall" in content) return void 0;
148
+ else if ("type" in content) throw new Error(`Unknown content type ${content.type}`);
149
+ else throw new Error(`Unknown content ${JSON.stringify(content)}`);
269
150
  }
270
- export function convertMessageContentToParts(message, isMultimodalModel, previousMessages) {
271
- if (isToolMessage(message)) {
272
- const messageName = message.name ??
273
- inferToolNameFromPreviousMessages(message, previousMessages);
274
- if (messageName === undefined) {
275
- 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.`);
276
- }
277
- const result = Array.isArray(message.content)
278
- ? message.content
279
- .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))
280
- .filter((p) => p !== undefined)
281
- : message.content;
282
- if (message.status === "error") {
283
- return [
284
- {
285
- functionResponse: {
286
- name: messageName,
287
- // The API expects an object with an `error` field if the function call fails.
288
- // `error` must be a valid object (not a string or array), so we wrap `message.content` here
289
- response: { error: { details: result } },
290
- },
291
- },
292
- ];
293
- }
294
- return [
295
- {
296
- functionResponse: {
297
- name: messageName,
298
- // again, can't have a string or array value for `response`, so we wrap it as an object here
299
- response: { result },
300
- },
301
- },
302
- ];
303
- }
304
- let functionCalls = [];
305
- const messageParts = [];
306
- if (typeof message.content === "string" && message.content) {
307
- messageParts.push({ text: message.content });
308
- }
309
- if (Array.isArray(message.content)) {
310
- messageParts.push(...message.content
311
- .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))
312
- .filter((p) => p !== undefined));
313
- }
314
- if (isAIMessage(message) && message.tool_calls?.length) {
315
- functionCalls = message.tool_calls.map((tc) => {
316
- return {
317
- functionCall: {
318
- name: tc.name,
319
- args: tc.args,
320
- },
321
- };
322
- });
323
- }
324
- return [...messageParts, ...functionCalls];
151
+ function convertMessageContentToParts(message, isMultimodalModel, previousMessages) {
152
+ if (isToolMessage(message)) {
153
+ const messageName = message.name ?? inferToolNameFromPreviousMessages(message, previousMessages);
154
+ 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.`);
155
+ const result = Array.isArray(message.content) ? message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0) : message.content;
156
+ if (message.status === "error") return [{ functionResponse: {
157
+ name: messageName,
158
+ response: { error: { details: result } }
159
+ } }];
160
+ return [{ functionResponse: {
161
+ name: messageName,
162
+ response: { result }
163
+ } }];
164
+ }
165
+ let functionCalls = [];
166
+ const messageParts = [];
167
+ if (typeof message.content === "string" && message.content) messageParts.push({ text: message.content });
168
+ if (Array.isArray(message.content)) messageParts.push(...message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0));
169
+ if (isAIMessage(message) && message.tool_calls?.length) functionCalls = message.tool_calls.map((tc) => {
170
+ return { functionCall: {
171
+ name: tc.name,
172
+ args: tc.args
173
+ } };
174
+ });
175
+ return [...messageParts, ...functionCalls];
325
176
  }
326
- export function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false) {
327
- return messages.reduce((acc, message, index) => {
328
- if (!isBaseMessage(message)) {
329
- throw new Error("Unsupported message input");
330
- }
331
- const author = getMessageAuthor(message);
332
- if (author === "system" && index !== 0) {
333
- throw new Error("System message should be the first one");
334
- }
335
- const role = convertAuthorToRole(author);
336
- const prevContent = acc.content[acc.content.length];
337
- if (!acc.mergeWithPreviousContent &&
338
- prevContent &&
339
- prevContent.role === role) {
340
- throw new Error("Google Generative AI requires alternate messages between authors");
341
- }
342
- const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index));
343
- if (acc.mergeWithPreviousContent) {
344
- const prevContent = acc.content[acc.content.length - 1];
345
- if (!prevContent) {
346
- throw new Error("There was a problem parsing your system message. Please try a prompt without one.");
347
- }
348
- prevContent.parts.push(...parts);
349
- return {
350
- mergeWithPreviousContent: false,
351
- content: acc.content,
352
- };
353
- }
354
- let actualRole = role;
355
- if (actualRole === "function" ||
356
- (actualRole === "system" && !convertSystemMessageToHumanContent)) {
357
- // GenerativeAI API will throw an error if the role is not "user" or "model."
358
- actualRole = "user";
359
- }
360
- const content = {
361
- role: actualRole,
362
- parts,
363
- };
364
- return {
365
- mergeWithPreviousContent: author === "system" && !convertSystemMessageToHumanContent,
366
- content: [...acc.content, content],
367
- };
368
- }, { content: [], mergeWithPreviousContent: false }).content;
177
+ function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false) {
178
+ return messages.reduce((acc, message, index) => {
179
+ if (!isBaseMessage(message)) throw new Error("Unsupported message input");
180
+ const author = getMessageAuthor(message);
181
+ if (author === "system" && index !== 0) throw new Error("System message should be the first one");
182
+ const role = convertAuthorToRole(author);
183
+ const prevContent = acc.content[acc.content.length];
184
+ if (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) throw new Error("Google Generative AI requires alternate messages between authors");
185
+ const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index));
186
+ if (acc.mergeWithPreviousContent) {
187
+ const prevContent$1 = acc.content[acc.content.length - 1];
188
+ if (!prevContent$1) throw new Error("There was a problem parsing your system message. Please try a prompt without one.");
189
+ prevContent$1.parts.push(...parts);
190
+ return {
191
+ mergeWithPreviousContent: false,
192
+ content: acc.content
193
+ };
194
+ }
195
+ let actualRole = role;
196
+ if (actualRole === "function" || actualRole === "system" && !convertSystemMessageToHumanContent) actualRole = "user";
197
+ const content = {
198
+ role: actualRole,
199
+ parts
200
+ };
201
+ return {
202
+ mergeWithPreviousContent: author === "system" && !convertSystemMessageToHumanContent,
203
+ content: [...acc.content, content]
204
+ };
205
+ }, {
206
+ content: [],
207
+ mergeWithPreviousContent: false
208
+ }).content;
369
209
  }
370
- export function mapGenerateContentResultToChatResult(response, extra) {
371
- // if rejected or error, return empty generations with reason in filters
372
- if (!response.candidates ||
373
- response.candidates.length === 0 ||
374
- !response.candidates[0]) {
375
- return {
376
- generations: [],
377
- llmOutput: {
378
- filters: response.promptFeedback,
379
- },
380
- };
381
- }
382
- const functionCalls = response.functionCalls();
383
- const [candidate] = response.candidates;
384
- const { content: candidateContent, ...generationInfo } = candidate;
385
- let content;
386
- if (Array.isArray(candidateContent?.parts) &&
387
- candidateContent.parts.length === 1 &&
388
- candidateContent.parts[0].text) {
389
- content = candidateContent.parts[0].text;
390
- }
391
- else if (Array.isArray(candidateContent?.parts) &&
392
- candidateContent.parts.length > 0) {
393
- content = candidateContent.parts.map((p) => {
394
- if ("text" in p) {
395
- return {
396
- type: "text",
397
- text: p.text,
398
- };
399
- }
400
- else if ("executableCode" in p) {
401
- return {
402
- type: "executableCode",
403
- executableCode: p.executableCode,
404
- };
405
- }
406
- else if ("codeExecutionResult" in p) {
407
- return {
408
- type: "codeExecutionResult",
409
- codeExecutionResult: p.codeExecutionResult,
410
- };
411
- }
412
- return p;
413
- });
414
- }
415
- else {
416
- // no content returned - likely due to abnormal stop reason, e.g. malformed function call
417
- content = [];
418
- }
419
- let text = "";
420
- if (typeof content === "string") {
421
- text = content;
422
- }
423
- else if (Array.isArray(content) && content.length > 0) {
424
- const block = content.find((b) => "text" in b);
425
- text = block?.text ?? text;
426
- }
427
- const generation = {
428
- text,
429
- message: new AIMessage({
430
- content: content ?? "",
431
- tool_calls: functionCalls?.map((fc) => {
432
- return {
433
- ...fc,
434
- type: "tool_call",
435
- id: "id" in fc && typeof fc.id === "string" ? fc.id : uuidv4(),
436
- };
437
- }),
438
- additional_kwargs: {
439
- ...generationInfo,
440
- },
441
- usage_metadata: extra?.usageMetadata,
442
- }),
443
- generationInfo,
444
- };
445
- return {
446
- generations: [generation],
447
- llmOutput: {
448
- tokenUsage: {
449
- promptTokens: extra?.usageMetadata?.input_tokens,
450
- completionTokens: extra?.usageMetadata?.output_tokens,
451
- totalTokens: extra?.usageMetadata?.total_tokens,
452
- },
453
- },
454
- };
210
+ function mapGenerateContentResultToChatResult(response, extra) {
211
+ if (!response.candidates || response.candidates.length === 0 || !response.candidates[0]) return {
212
+ generations: [],
213
+ llmOutput: { filters: response.promptFeedback }
214
+ };
215
+ const functionCalls = response.functionCalls();
216
+ const [candidate] = response.candidates;
217
+ const { content: candidateContent,...generationInfo } = candidate;
218
+ let content;
219
+ if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length === 1 && candidateContent.parts[0].text) content = candidateContent.parts[0].text;
220
+ else if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length > 0) content = candidateContent.parts.map((p) => {
221
+ if ("text" in p) return {
222
+ type: "text",
223
+ text: p.text
224
+ };
225
+ else if ("inlineData" in p) return {
226
+ type: "inlineData",
227
+ inlineData: p.inlineData
228
+ };
229
+ else if ("functionCall" in p) return {
230
+ type: "functionCall",
231
+ functionCall: p.functionCall
232
+ };
233
+ else if ("functionResponse" in p) return {
234
+ type: "functionResponse",
235
+ functionResponse: p.functionResponse
236
+ };
237
+ else if ("fileData" in p) return {
238
+ type: "fileData",
239
+ fileData: p.fileData
240
+ };
241
+ else if ("executableCode" in p) return {
242
+ type: "executableCode",
243
+ executableCode: p.executableCode
244
+ };
245
+ else if ("codeExecutionResult" in p) return {
246
+ type: "codeExecutionResult",
247
+ codeExecutionResult: p.codeExecutionResult
248
+ };
249
+ return p;
250
+ });
251
+ else content = [];
252
+ let text = "";
253
+ if (typeof content === "string") text = content;
254
+ else if (Array.isArray(content) && content.length > 0) {
255
+ const block = content.find((b) => "text" in b);
256
+ text = block?.text ?? text;
257
+ }
258
+ const generation = {
259
+ text,
260
+ message: new AIMessage({
261
+ content: content ?? "",
262
+ tool_calls: functionCalls?.map((fc) => {
263
+ return {
264
+ ...fc,
265
+ type: "tool_call",
266
+ id: "id" in fc && typeof fc.id === "string" ? fc.id : v4()
267
+ };
268
+ }),
269
+ additional_kwargs: { ...generationInfo },
270
+ usage_metadata: extra?.usageMetadata
271
+ }),
272
+ generationInfo
273
+ };
274
+ return {
275
+ generations: [generation],
276
+ llmOutput: { tokenUsage: {
277
+ promptTokens: extra?.usageMetadata?.input_tokens,
278
+ completionTokens: extra?.usageMetadata?.output_tokens,
279
+ totalTokens: extra?.usageMetadata?.total_tokens
280
+ } }
281
+ };
455
282
  }
456
- export function convertResponseContentToChatGenerationChunk(response, extra) {
457
- if (!response.candidates || response.candidates.length === 0) {
458
- return null;
459
- }
460
- const functionCalls = response.functionCalls();
461
- const [candidate] = response.candidates;
462
- const { content: candidateContent, ...generationInfo } = candidate;
463
- let content;
464
- // Checks if some parts do not have text. If false, it means that the content is a string.
465
- if (Array.isArray(candidateContent?.parts) &&
466
- candidateContent.parts.every((p) => "text" in p)) {
467
- content = candidateContent.parts.map((p) => p.text).join("");
468
- }
469
- else if (Array.isArray(candidateContent?.parts)) {
470
- content = candidateContent.parts.map((p) => {
471
- if ("text" in p) {
472
- return {
473
- type: "text",
474
- text: p.text,
475
- };
476
- }
477
- else if ("executableCode" in p) {
478
- return {
479
- type: "executableCode",
480
- executableCode: p.executableCode,
481
- };
482
- }
483
- else if ("codeExecutionResult" in p) {
484
- return {
485
- type: "codeExecutionResult",
486
- codeExecutionResult: p.codeExecutionResult,
487
- };
488
- }
489
- return p;
490
- });
491
- }
492
- else {
493
- // no content returned - likely due to abnormal stop reason, e.g. malformed function call
494
- content = [];
495
- }
496
- let text = "";
497
- if (content && typeof content === "string") {
498
- text = content;
499
- }
500
- else if (Array.isArray(content)) {
501
- const block = content.find((b) => "text" in b);
502
- text = block?.text ?? "";
503
- }
504
- const toolCallChunks = [];
505
- if (functionCalls) {
506
- toolCallChunks.push(...functionCalls.map((fc) => ({
507
- ...fc,
508
- args: JSON.stringify(fc.args),
509
- index: extra.index,
510
- type: "tool_call_chunk",
511
- id: "id" in fc && typeof fc.id === "string" ? fc.id : uuidv4(),
512
- })));
513
- }
514
- return new ChatGenerationChunk({
515
- text,
516
- message: new AIMessageChunk({
517
- content: content || "",
518
- name: !candidateContent ? undefined : candidateContent.role,
519
- tool_call_chunks: toolCallChunks,
520
- // Each chunk can have unique "generationInfo", and merging strategy is unclear,
521
- // so leave blank for now.
522
- additional_kwargs: {},
523
- usage_metadata: extra.usageMetadata,
524
- }),
525
- generationInfo,
526
- });
283
+ function convertResponseContentToChatGenerationChunk(response, extra) {
284
+ if (!response.candidates || response.candidates.length === 0) return null;
285
+ const functionCalls = response.functionCalls();
286
+ const [candidate] = response.candidates;
287
+ const { content: candidateContent,...generationInfo } = candidate;
288
+ let content;
289
+ if (Array.isArray(candidateContent?.parts) && candidateContent.parts.every((p) => "text" in p)) content = candidateContent.parts.map((p) => p.text).join("");
290
+ else if (Array.isArray(candidateContent?.parts)) content = candidateContent.parts.map((p) => {
291
+ if ("text" in p) return {
292
+ type: "text",
293
+ text: p.text
294
+ };
295
+ else if ("inlineData" in p) return {
296
+ type: "inlineData",
297
+ inlineData: p.inlineData
298
+ };
299
+ else if ("functionCall" in p) return {
300
+ type: "functionCall",
301
+ functionCall: p.functionCall
302
+ };
303
+ else if ("functionResponse" in p) return {
304
+ type: "functionResponse",
305
+ functionResponse: p.functionResponse
306
+ };
307
+ else if ("fileData" in p) return {
308
+ type: "fileData",
309
+ fileData: p.fileData
310
+ };
311
+ else if ("executableCode" in p) return {
312
+ type: "executableCode",
313
+ executableCode: p.executableCode
314
+ };
315
+ else if ("codeExecutionResult" in p) return {
316
+ type: "codeExecutionResult",
317
+ codeExecutionResult: p.codeExecutionResult
318
+ };
319
+ return p;
320
+ });
321
+ else content = [];
322
+ let text = "";
323
+ if (content && typeof content === "string") text = content;
324
+ else if (Array.isArray(content)) {
325
+ const block = content.find((b) => "text" in b);
326
+ text = block?.text ?? "";
327
+ }
328
+ const toolCallChunks = [];
329
+ if (functionCalls) toolCallChunks.push(...functionCalls.map((fc) => ({
330
+ ...fc,
331
+ args: JSON.stringify(fc.args),
332
+ index: extra.index,
333
+ type: "tool_call_chunk",
334
+ id: "id" in fc && typeof fc.id === "string" ? fc.id : v4()
335
+ })));
336
+ return new ChatGenerationChunk({
337
+ text,
338
+ message: new AIMessageChunk({
339
+ content: content || "",
340
+ name: !candidateContent ? void 0 : candidateContent.role,
341
+ tool_call_chunks: toolCallChunks,
342
+ additional_kwargs: {},
343
+ response_metadata: { model_provider: "google-genai" },
344
+ usage_metadata: extra.usageMetadata
345
+ }),
346
+ generationInfo
347
+ });
527
348
  }
528
- export function convertToGenerativeAITools(tools) {
529
- if (tools.every((tool) => "functionDeclarations" in tool &&
530
- Array.isArray(tool.functionDeclarations))) {
531
- return tools;
532
- }
533
- return [
534
- {
535
- functionDeclarations: tools.map((tool) => {
536
- if (isLangChainTool(tool)) {
537
- const jsonSchema = schemaToGenerativeAIParameters(tool.schema);
538
- if (jsonSchema.type === "object" &&
539
- "properties" in jsonSchema &&
540
- Object.keys(jsonSchema.properties).length === 0) {
541
- return {
542
- name: tool.name,
543
- description: tool.description,
544
- };
545
- }
546
- return {
547
- name: tool.name,
548
- description: tool.description,
549
- parameters: jsonSchema,
550
- };
551
- }
552
- if (isOpenAITool(tool)) {
553
- return {
554
- name: tool.function.name,
555
- description: tool.function.description ?? `A function available to call.`,
556
- parameters: jsonSchemaToGeminiParameters(tool.function.parameters),
557
- };
558
- }
559
- return tool;
560
- }),
561
- },
562
- ];
349
+ function convertToGenerativeAITools(tools) {
350
+ if (tools.every((tool) => "functionDeclarations" in tool && Array.isArray(tool.functionDeclarations))) return tools;
351
+ return [{ functionDeclarations: tools.map((tool) => {
352
+ if (isLangChainTool(tool)) {
353
+ const jsonSchema = schemaToGenerativeAIParameters(tool.schema);
354
+ if (jsonSchema.type === "object" && "properties" in jsonSchema && Object.keys(jsonSchema.properties).length === 0) return {
355
+ name: tool.name,
356
+ description: tool.description
357
+ };
358
+ return {
359
+ name: tool.name,
360
+ description: tool.description,
361
+ parameters: jsonSchema
362
+ };
363
+ }
364
+ if (isOpenAITool(tool)) return {
365
+ name: tool.function.name,
366
+ description: tool.function.description ?? `A function available to call.`,
367
+ parameters: jsonSchemaToGeminiParameters(tool.function.parameters)
368
+ };
369
+ return tool;
370
+ }) }];
563
371
  }
372
+
373
+ //#endregion
374
+ export { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, convertToGenerativeAITools, mapGenerateContentResultToChatResult };
375
+ //# sourceMappingURL=common.js.map