@langchain/google-genai 0.2.18 → 1.0.1

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 (59) hide show
  1. package/CHANGELOG.md +17 -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 +688 -847
  6. package/dist/chat_models.cjs.map +1 -0
  7. package/dist/chat_models.d.cts +575 -0
  8. package/dist/chat_models.d.cts.map +1 -0
  9. package/dist/chat_models.d.ts +190 -157
  10. package/dist/chat_models.d.ts.map +1 -0
  11. package/dist/chat_models.js +686 -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/profiles.cjs +345 -0
  30. package/dist/profiles.cjs.map +1 -0
  31. package/dist/profiles.js +344 -0
  32. package/dist/profiles.js.map +1 -0
  33. package/dist/types.d.cts +8 -0
  34. package/dist/types.d.cts.map +1 -0
  35. package/dist/types.d.ts +7 -2
  36. package/dist/types.d.ts.map +1 -0
  37. package/dist/utils/common.cjs +356 -549
  38. package/dist/utils/common.cjs.map +1 -0
  39. package/dist/utils/common.js +357 -545
  40. package/dist/utils/common.js.map +1 -0
  41. package/dist/utils/tools.cjs +65 -102
  42. package/dist/utils/tools.cjs.map +1 -0
  43. package/dist/utils/tools.js +64 -99
  44. package/dist/utils/tools.js.map +1 -0
  45. package/dist/utils/zod_to_genai_parameters.cjs +31 -49
  46. package/dist/utils/zod_to_genai_parameters.cjs.map +1 -0
  47. package/dist/utils/zod_to_genai_parameters.js +29 -45
  48. package/dist/utils/zod_to_genai_parameters.js.map +1 -0
  49. package/package.json +45 -51
  50. package/dist/output_parsers.d.ts +0 -20
  51. package/dist/types.cjs +0 -2
  52. package/dist/types.js +0 -1
  53. package/dist/utils/common.d.ts +0 -22
  54. package/dist/utils/tools.d.ts +0 -10
  55. package/dist/utils/zod_to_genai_parameters.d.ts +0 -14
  56. package/index.cjs +0 -1
  57. package/index.d.cts +0 -1
  58. package/index.d.ts +0 -1
  59. package/index.js +0 -1
@@ -1,849 +1,690 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ChatGoogleGenerativeAI = void 0;
4
- const generative_ai_1 = require("@google/generative-ai");
5
- const env_1 = require("@langchain/core/utils/env");
6
- const chat_models_1 = require("@langchain/core/language_models/chat_models");
7
- const runnables_1 = require("@langchain/core/runnables");
8
- const types_1 = require("@langchain/core/utils/types");
9
- const output_parsers_1 = require("@langchain/core/output_parsers");
10
- const zod_to_genai_parameters_js_1 = require("./utils/zod_to_genai_parameters.cjs");
11
- const common_js_1 = require("./utils/common.cjs");
12
- const output_parsers_js_1 = require("./output_parsers.cjs");
13
- const tools_js_1 = require("./utils/tools.cjs");
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_zod_to_genai_parameters = require('./utils/zod_to_genai_parameters.cjs');
3
+ const require_common = require('./utils/common.cjs');
4
+ const require_output_parsers = require('./output_parsers.cjs');
5
+ const require_tools = require('./utils/tools.cjs');
6
+ const require_profiles = require('./profiles.cjs');
7
+ const __google_generative_ai = require_rolldown_runtime.__toESM(require("@google/generative-ai"));
8
+ const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
9
+ const __langchain_core_language_models_chat_models = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/chat_models"));
10
+ const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
11
+ const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
12
+ const __langchain_core_output_parsers = require_rolldown_runtime.__toESM(require("@langchain/core/output_parsers"));
13
+
14
+ //#region src/chat_models.ts
14
15
  /**
15
- * Google Generative AI chat model integration.
16
- *
17
- * Setup:
18
- * Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`.
19
- *
20
- * ```bash
21
- * npm install @langchain/google-genai
22
- * export GOOGLE_API_KEY="your-api-key"
23
- * ```
24
- *
25
- * ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor)
26
- *
27
- * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html)
28
- *
29
- * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
30
- * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:
31
- *
32
- * ```typescript
33
- * // When calling `.withConfig`, call options should be passed via the first argument
34
- * const llmWithArgsBound = llm.withConfig({
35
- * stop: ["\n"],
36
- * });
37
- *
38
- * // When calling `.bindTools`, call options should be passed via the second argument
39
- * const llmWithTools = llm.bindTools(
40
- * [...],
41
- * {
42
- * stop: ["\n"],
43
- * }
44
- * );
45
- * ```
46
- *
47
- * ## Examples
48
- *
49
- * <details open>
50
- * <summary><strong>Instantiate</strong></summary>
51
- *
52
- * ```typescript
53
- * import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
54
- *
55
- * const llm = new ChatGoogleGenerativeAI({
56
- * model: "gemini-1.5-flash",
57
- * temperature: 0,
58
- * maxRetries: 2,
59
- * // apiKey: "...",
60
- * // other params...
61
- * });
62
- * ```
63
- * </details>
64
- *
65
- * <br />
66
- *
67
- * <details>
68
- * <summary><strong>Invoking</strong></summary>
69
- *
70
- * ```typescript
71
- * const input = `Translate "I love programming" into French.`;
72
- *
73
- * // Models also accept a list of chat messages or a formatted prompt
74
- * const result = await llm.invoke(input);
75
- * console.log(result);
76
- * ```
77
- *
78
- * ```txt
79
- * AIMessage {
80
- * "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n",
81
- * "response_metadata": {
82
- * "finishReason": "STOP",
83
- * "index": 0,
84
- * "safetyRatings": [
85
- * {
86
- * "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
87
- * "probability": "NEGLIGIBLE"
88
- * },
89
- * {
90
- * "category": "HARM_CATEGORY_HATE_SPEECH",
91
- * "probability": "NEGLIGIBLE"
92
- * },
93
- * {
94
- * "category": "HARM_CATEGORY_HARASSMENT",
95
- * "probability": "NEGLIGIBLE"
96
- * },
97
- * {
98
- * "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
99
- * "probability": "NEGLIGIBLE"
100
- * }
101
- * ]
102
- * },
103
- * "usage_metadata": {
104
- * "input_tokens": 10,
105
- * "output_tokens": 149,
106
- * "total_tokens": 159
107
- * }
108
- * }
109
- * ```
110
- * </details>
111
- *
112
- * <br />
113
- *
114
- * <details>
115
- * <summary><strong>Streaming Chunks</strong></summary>
116
- *
117
- * ```typescript
118
- * for await (const chunk of await llm.stream(input)) {
119
- * console.log(chunk);
120
- * }
121
- * ```
122
- *
123
- * ```txt
124
- * AIMessageChunk {
125
- * "content": "There",
126
- * "response_metadata": {
127
- * "index": 0
128
- * }
129
- * "usage_metadata": {
130
- * "input_tokens": 10,
131
- * "output_tokens": 1,
132
- * "total_tokens": 11
133
- * }
134
- * }
135
- * AIMessageChunk {
136
- * "content": " are a few ways to translate \"I love programming\" into French, depending on",
137
- * }
138
- * AIMessageChunk {
139
- * "content": " the level of formality and nuance you want to convey:\n\n**Formal:**\n\n",
140
- * }
141
- * AIMessageChunk {
142
- * "content": "* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This",
143
- * }
144
- * AIMessageChunk {
145
- * "content": " is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More",
146
- * }
147
- * AIMessageChunk {
148
- * "content": " specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and",
149
- * }
150
- * AIMessageChunk {
151
- * "content": " your intended audience. \n",
152
- * }
153
- * ```
154
- * </details>
155
- *
156
- * <br />
157
- *
158
- * <details>
159
- * <summary><strong>Aggregate Streamed Chunks</strong></summary>
160
- *
161
- * ```typescript
162
- * import { AIMessageChunk } from '@langchain/core/messages';
163
- * import { concat } from '@langchain/core/utils/stream';
164
- *
165
- * const stream = await llm.stream(input);
166
- * let full: AIMessageChunk | undefined;
167
- * for await (const chunk of stream) {
168
- * full = !full ? chunk : concat(full, chunk);
169
- * }
170
- * console.log(full);
171
- * ```
172
- *
173
- * ```txt
174
- * AIMessageChunk {
175
- * "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n",
176
- * "usage_metadata": {
177
- * "input_tokens": 10,
178
- * "output_tokens": 277,
179
- * "total_tokens": 287
180
- * }
181
- * }
182
- * ```
183
- * </details>
184
- *
185
- * <br />
186
- *
187
- * <details>
188
- * <summary><strong>Bind tools</strong></summary>
189
- *
190
- * ```typescript
191
- * import { z } from 'zod';
192
- *
193
- * const GetWeather = {
194
- * name: "GetWeather",
195
- * description: "Get the current weather in a given location",
196
- * schema: z.object({
197
- * location: z.string().describe("The city and state, e.g. San Francisco, CA")
198
- * }),
199
- * }
200
- *
201
- * const GetPopulation = {
202
- * name: "GetPopulation",
203
- * description: "Get the current population in a given location",
204
- * schema: z.object({
205
- * location: z.string().describe("The city and state, e.g. San Francisco, CA")
206
- * }),
207
- * }
208
- *
209
- * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
210
- * const aiMsg = await llmWithTools.invoke(
211
- * "Which city is hotter today and which is bigger: LA or NY?"
212
- * );
213
- * console.log(aiMsg.tool_calls);
214
- * ```
215
- *
216
- * ```txt
217
- * [
218
- * {
219
- * name: 'GetWeather',
220
- * args: { location: 'Los Angeles, CA' },
221
- * type: 'tool_call'
222
- * },
223
- * {
224
- * name: 'GetWeather',
225
- * args: { location: 'New York, NY' },
226
- * type: 'tool_call'
227
- * },
228
- * {
229
- * name: 'GetPopulation',
230
- * args: { location: 'Los Angeles, CA' },
231
- * type: 'tool_call'
232
- * },
233
- * {
234
- * name: 'GetPopulation',
235
- * args: { location: 'New York, NY' },
236
- * type: 'tool_call'
237
- * }
238
- * ]
239
- * ```
240
- * </details>
241
- *
242
- * <br />
243
- *
244
- * <details>
245
- * <summary><strong>Structured Output</strong></summary>
246
- *
247
- * ```typescript
248
- * const Joke = z.object({
249
- * setup: z.string().describe("The setup of the joke"),
250
- * punchline: z.string().describe("The punchline to the joke"),
251
- * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
252
- * }).describe('Joke to tell user.');
253
- *
254
- * const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
255
- * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
256
- * console.log(jokeResult);
257
- * ```
258
- *
259
- * ```txt
260
- * {
261
- * setup: "Why don\\'t cats play poker?",
262
- * punchline: "Why don\\'t cats play poker? Because they always have an ace up their sleeve!"
263
- * }
264
- * ```
265
- * </details>
266
- *
267
- * <br />
268
- *
269
- * <details>
270
- * <summary><strong>Multimodal</strong></summary>
271
- *
272
- * ```typescript
273
- * import { HumanMessage } from '@langchain/core/messages';
274
- *
275
- * const imageUrl = "https://example.com/image.jpg";
276
- * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
277
- * const base64Image = Buffer.from(imageData).toString('base64');
278
- *
279
- * const message = new HumanMessage({
280
- * content: [
281
- * { type: "text", text: "describe the weather in this image" },
282
- * {
283
- * type: "image_url",
284
- * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
285
- * },
286
- * ]
287
- * });
288
- *
289
- * const imageDescriptionAiMsg = await llm.invoke([message]);
290
- * console.log(imageDescriptionAiMsg.content);
291
- * ```
292
- *
293
- * ```txt
294
- * The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.
295
- * ```
296
- * </details>
297
- *
298
- * <br />
299
- *
300
- * <details>
301
- * <summary><strong>Usage Metadata</strong></summary>
302
- *
303
- * ```typescript
304
- * const aiMsgForMetadata = await llm.invoke(input);
305
- * console.log(aiMsgForMetadata.usage_metadata);
306
- * ```
307
- *
308
- * ```txt
309
- * { input_tokens: 10, output_tokens: 149, total_tokens: 159 }
310
- * ```
311
- * </details>
312
- *
313
- * <br />
314
- *
315
- * <details>
316
- * <summary><strong>Response Metadata</strong></summary>
317
- *
318
- * ```typescript
319
- * const aiMsgForResponseMetadata = await llm.invoke(input);
320
- * console.log(aiMsgForResponseMetadata.response_metadata);
321
- * ```
322
- *
323
- * ```txt
324
- * {
325
- * finishReason: 'STOP',
326
- * index: 0,
327
- * safetyRatings: [
328
- * {
329
- * category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
330
- * probability: 'NEGLIGIBLE'
331
- * },
332
- * {
333
- * category: 'HARM_CATEGORY_HATE_SPEECH',
334
- * probability: 'NEGLIGIBLE'
335
- * },
336
- * { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },
337
- * {
338
- * category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
339
- * probability: 'NEGLIGIBLE'
340
- * }
341
- * ]
342
- * }
343
- * ```
344
- * </details>
345
- *
346
- * <br />
347
- *
348
- * <details>
349
- * <summary><strong>Document Messages</strong></summary>
350
- *
351
- * This example will show you how to pass documents such as PDFs to Google
352
- * Generative AI through messages.
353
- *
354
- * ```typescript
355
- * const pdfPath = "/Users/my_user/Downloads/invoice.pdf";
356
- * const pdfBase64 = await fs.readFile(pdfPath, "base64");
357
- *
358
- * const response = await llm.invoke([
359
- * ["system", "Use the provided documents to answer the question"],
360
- * [
361
- * "user",
362
- * [
363
- * {
364
- * type: "application/pdf", // If the `type` field includes a single slash (`/`), it will be treated as inline data.
365
- * data: pdfBase64,
366
- * },
367
- * {
368
- * type: "text",
369
- * text: "Summarize the contents of this PDF",
370
- * },
371
- * ],
372
- * ],
373
- * ]);
374
- *
375
- * console.log(response.content);
376
- * ```
377
- *
378
- * ```txt
379
- * This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025,
380
- * and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC).
381
- * The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022,
382
- * expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is
383
- * X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply.
384
- * ```
385
- * </details>
386
- *
387
- * <br />
388
- */
389
- class ChatGoogleGenerativeAI extends chat_models_1.BaseChatModel {
390
- static lc_name() {
391
- return "ChatGoogleGenerativeAI";
392
- }
393
- get lc_secrets() {
394
- return {
395
- apiKey: "GOOGLE_API_KEY",
396
- };
397
- }
398
- get lc_aliases() {
399
- return {
400
- apiKey: "google_api_key",
401
- };
402
- }
403
- get _isMultimodalModel() {
404
- return (this.model.includes("vision") ||
405
- this.model.startsWith("gemini-1.5") ||
406
- this.model.startsWith("gemini-2") ||
407
- (this.model.startsWith("gemma-3-") &&
408
- !this.model.startsWith("gemma-3-1b")) // gemma-3 models are multimodal(but gemma-3n-* and gemma-3-1b are not)
409
- );
410
- }
411
- constructor(fields) {
412
- super(fields);
413
- Object.defineProperty(this, "lc_serializable", {
414
- enumerable: true,
415
- configurable: true,
416
- writable: true,
417
- value: true
418
- });
419
- Object.defineProperty(this, "lc_namespace", {
420
- enumerable: true,
421
- configurable: true,
422
- writable: true,
423
- value: ["langchain", "chat_models", "google_genai"]
424
- });
425
- Object.defineProperty(this, "model", {
426
- enumerable: true,
427
- configurable: true,
428
- writable: true,
429
- value: void 0
430
- });
431
- Object.defineProperty(this, "temperature", {
432
- enumerable: true,
433
- configurable: true,
434
- writable: true,
435
- value: void 0
436
- }); // default value chosen based on model
437
- Object.defineProperty(this, "maxOutputTokens", {
438
- enumerable: true,
439
- configurable: true,
440
- writable: true,
441
- value: void 0
442
- });
443
- Object.defineProperty(this, "topP", {
444
- enumerable: true,
445
- configurable: true,
446
- writable: true,
447
- value: void 0
448
- }); // default value chosen based on model
449
- Object.defineProperty(this, "topK", {
450
- enumerable: true,
451
- configurable: true,
452
- writable: true,
453
- value: void 0
454
- }); // default value chosen based on model
455
- Object.defineProperty(this, "stopSequences", {
456
- enumerable: true,
457
- configurable: true,
458
- writable: true,
459
- value: []
460
- });
461
- Object.defineProperty(this, "safetySettings", {
462
- enumerable: true,
463
- configurable: true,
464
- writable: true,
465
- value: void 0
466
- });
467
- Object.defineProperty(this, "apiKey", {
468
- enumerable: true,
469
- configurable: true,
470
- writable: true,
471
- value: void 0
472
- });
473
- Object.defineProperty(this, "streaming", {
474
- enumerable: true,
475
- configurable: true,
476
- writable: true,
477
- value: false
478
- });
479
- Object.defineProperty(this, "json", {
480
- enumerable: true,
481
- configurable: true,
482
- writable: true,
483
- value: void 0
484
- });
485
- Object.defineProperty(this, "streamUsage", {
486
- enumerable: true,
487
- configurable: true,
488
- writable: true,
489
- value: true
490
- });
491
- Object.defineProperty(this, "convertSystemMessageToHumanContent", {
492
- enumerable: true,
493
- configurable: true,
494
- writable: true,
495
- value: void 0
496
- });
497
- Object.defineProperty(this, "client", {
498
- enumerable: true,
499
- configurable: true,
500
- writable: true,
501
- value: void 0
502
- });
503
- this.model = fields.model.replace(/^models\//, "");
504
- this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens;
505
- if (this.maxOutputTokens && this.maxOutputTokens < 0) {
506
- throw new Error("`maxOutputTokens` must be a positive integer");
507
- }
508
- this.temperature = fields.temperature ?? this.temperature;
509
- if (this.temperature && (this.temperature < 0 || this.temperature > 2)) {
510
- throw new Error("`temperature` must be in the range of [0.0,2.0]");
511
- }
512
- this.topP = fields.topP ?? this.topP;
513
- if (this.topP && this.topP < 0) {
514
- throw new Error("`topP` must be a positive integer");
515
- }
516
- if (this.topP && this.topP > 1) {
517
- throw new Error("`topP` must be below 1.");
518
- }
519
- this.topK = fields.topK ?? this.topK;
520
- if (this.topK && this.topK < 0) {
521
- throw new Error("`topK` must be a positive integer");
522
- }
523
- this.stopSequences = fields.stopSequences ?? this.stopSequences;
524
- this.apiKey = fields.apiKey ?? (0, env_1.getEnvironmentVariable)("GOOGLE_API_KEY");
525
- if (!this.apiKey) {
526
- throw new Error("Please set an API key for Google GenerativeAI " +
527
- "in the environment variable GOOGLE_API_KEY " +
528
- "or in the `apiKey` field of the " +
529
- "ChatGoogleGenerativeAI constructor");
530
- }
531
- this.safetySettings = fields.safetySettings ?? this.safetySettings;
532
- if (this.safetySettings && this.safetySettings.length > 0) {
533
- const safetySettingsSet = new Set(this.safetySettings.map((s) => s.category));
534
- if (safetySettingsSet.size !== this.safetySettings.length) {
535
- throw new Error("The categories in `safetySettings` array must be unique");
536
- }
537
- }
538
- this.streaming = fields.streaming ?? this.streaming;
539
- this.json = fields.json;
540
- this.client = new generative_ai_1.GoogleGenerativeAI(this.apiKey).getGenerativeModel({
541
- model: this.model,
542
- safetySettings: this.safetySettings,
543
- generationConfig: {
544
- stopSequences: this.stopSequences,
545
- maxOutputTokens: this.maxOutputTokens,
546
- temperature: this.temperature,
547
- topP: this.topP,
548
- topK: this.topK,
549
- ...(this.json ? { responseMimeType: "application/json" } : {}),
550
- },
551
- }, {
552
- apiVersion: fields.apiVersion,
553
- baseUrl: fields.baseUrl,
554
- });
555
- this.streamUsage = fields.streamUsage ?? this.streamUsage;
556
- }
557
- useCachedContent(cachedContent, modelParams, requestOptions) {
558
- if (!this.apiKey)
559
- return;
560
- this.client = new generative_ai_1.GoogleGenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions);
561
- }
562
- get useSystemInstruction() {
563
- return typeof this.convertSystemMessageToHumanContent === "boolean"
564
- ? !this.convertSystemMessageToHumanContent
565
- : this.computeUseSystemInstruction;
566
- }
567
- get computeUseSystemInstruction() {
568
- // This works on models from April 2024 and later
569
- // Vertex AI: gemini-1.5-pro and gemini-1.0-002 and later
570
- // AI Studio: gemini-1.5-pro-latest
571
- if (this.model === "gemini-1.0-pro-001") {
572
- return false;
573
- }
574
- else if (this.model.startsWith("gemini-pro-vision")) {
575
- return false;
576
- }
577
- else if (this.model.startsWith("gemini-1.0-pro-vision")) {
578
- return false;
579
- }
580
- else if (this.model === "gemini-pro") {
581
- // on AI Studio gemini-pro is still pointing at gemini-1.0-pro-001
582
- return false;
583
- }
584
- return true;
585
- }
586
- getLsParams(options) {
587
- return {
588
- ls_provider: "google_genai",
589
- ls_model_name: this.model,
590
- ls_model_type: "chat",
591
- ls_temperature: this.client.generationConfig.temperature,
592
- ls_max_tokens: this.client.generationConfig.maxOutputTokens,
593
- ls_stop: options.stop,
594
- };
595
- }
596
- _combineLLMOutput() {
597
- return [];
598
- }
599
- _llmType() {
600
- return "googlegenerativeai";
601
- }
602
- bindTools(tools, kwargs) {
603
- return this.withConfig({
604
- tools: (0, tools_js_1.convertToolsToGenAI)(tools)?.tools,
605
- ...kwargs,
606
- });
607
- }
608
- invocationParams(options) {
609
- const toolsAndConfig = options?.tools?.length
610
- ? (0, tools_js_1.convertToolsToGenAI)(options.tools, {
611
- toolChoice: options.tool_choice,
612
- allowedFunctionNames: options.allowedFunctionNames,
613
- })
614
- : undefined;
615
- if (options?.responseSchema) {
616
- this.client.generationConfig.responseSchema = options.responseSchema;
617
- this.client.generationConfig.responseMimeType = "application/json";
618
- }
619
- else {
620
- this.client.generationConfig.responseSchema = undefined;
621
- this.client.generationConfig.responseMimeType = this.json
622
- ? "application/json"
623
- : undefined;
624
- }
625
- return {
626
- ...(toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {}),
627
- ...(toolsAndConfig?.toolConfig
628
- ? { toolConfig: toolsAndConfig.toolConfig }
629
- : {}),
630
- };
631
- }
632
- async _generate(messages, options, runManager) {
633
- const prompt = (0, common_js_1.convertBaseMessagesToContent)(messages, this._isMultimodalModel, this.useSystemInstruction);
634
- let actualPrompt = prompt;
635
- if (prompt[0].role === "system") {
636
- const [systemInstruction] = prompt;
637
- this.client.systemInstruction = systemInstruction;
638
- actualPrompt = prompt.slice(1);
639
- }
640
- const parameters = this.invocationParams(options);
641
- // Handle streaming
642
- if (this.streaming) {
643
- const tokenUsage = {};
644
- const stream = this._streamResponseChunks(messages, options, runManager);
645
- const finalChunks = {};
646
- for await (const chunk of stream) {
647
- const index = chunk.generationInfo?.completion ?? 0;
648
- if (finalChunks[index] === undefined) {
649
- finalChunks[index] = chunk;
650
- }
651
- else {
652
- finalChunks[index] = finalChunks[index].concat(chunk);
653
- }
654
- }
655
- const generations = Object.entries(finalChunks)
656
- .sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10))
657
- .map(([_, value]) => value);
658
- return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
659
- }
660
- const res = await this.completionWithRetry({
661
- ...parameters,
662
- contents: actualPrompt,
663
- });
664
- let usageMetadata;
665
- if ("usageMetadata" in res.response) {
666
- const genAIUsageMetadata = res.response.usageMetadata;
667
- usageMetadata = {
668
- input_tokens: genAIUsageMetadata.promptTokenCount ?? 0,
669
- output_tokens: genAIUsageMetadata.candidatesTokenCount ?? 0,
670
- total_tokens: genAIUsageMetadata.totalTokenCount ?? 0,
671
- };
672
- }
673
- const generationResult = (0, common_js_1.mapGenerateContentResultToChatResult)(res.response, {
674
- usageMetadata,
675
- });
676
- // may not have generations in output if there was a refusal for safety reasons, malformed function call, etc.
677
- if (generationResult.generations?.length > 0) {
678
- await runManager?.handleLLMNewToken(generationResult.generations[0]?.text ?? "");
679
- }
680
- return generationResult;
681
- }
682
- async *_streamResponseChunks(messages, options, runManager) {
683
- const prompt = (0, common_js_1.convertBaseMessagesToContent)(messages, this._isMultimodalModel, this.useSystemInstruction);
684
- let actualPrompt = prompt;
685
- if (prompt[0].role === "system") {
686
- const [systemInstruction] = prompt;
687
- this.client.systemInstruction = systemInstruction;
688
- actualPrompt = prompt.slice(1);
689
- }
690
- const parameters = this.invocationParams(options);
691
- const request = {
692
- ...parameters,
693
- contents: actualPrompt,
694
- };
695
- const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => {
696
- const { stream } = await this.client.generateContentStream(request);
697
- return stream;
698
- });
699
- let usageMetadata;
700
- // Keep prior cumulative counts for calculating token deltas while streaming
701
- let prevPromptTokenCount = 0;
702
- let prevCandidatesTokenCount = 0;
703
- let prevTotalTokenCount = 0;
704
- let index = 0;
705
- for await (const response of stream) {
706
- if ("usageMetadata" in response &&
707
- response.usageMetadata !== undefined &&
708
- this.streamUsage !== false &&
709
- options.streamUsage !== false) {
710
- usageMetadata = {
711
- input_tokens: response.usageMetadata.promptTokenCount ?? 0,
712
- output_tokens: response.usageMetadata.candidatesTokenCount ?? 0,
713
- total_tokens: response.usageMetadata.totalTokenCount ?? 0,
714
- };
715
- // Under the hood, LangChain combines the prompt tokens. Google returns the updated
716
- // total each time, so we need to find the difference between the tokens.
717
- const newPromptTokenCount = response.usageMetadata.promptTokenCount ?? 0;
718
- usageMetadata.input_tokens = Math.max(0, newPromptTokenCount - prevPromptTokenCount);
719
- prevPromptTokenCount = newPromptTokenCount;
720
- const newCandidatesTokenCount = response.usageMetadata.candidatesTokenCount ?? 0;
721
- usageMetadata.output_tokens = Math.max(0, newCandidatesTokenCount - prevCandidatesTokenCount);
722
- prevCandidatesTokenCount = newCandidatesTokenCount;
723
- const newTotalTokenCount = response.usageMetadata.totalTokenCount ?? 0;
724
- usageMetadata.total_tokens = Math.max(0, newTotalTokenCount - prevTotalTokenCount);
725
- prevTotalTokenCount = newTotalTokenCount;
726
- }
727
- const chunk = (0, common_js_1.convertResponseContentToChatGenerationChunk)(response, {
728
- usageMetadata,
729
- index,
730
- });
731
- index += 1;
732
- if (!chunk) {
733
- continue;
734
- }
735
- yield chunk;
736
- await runManager?.handleLLMNewToken(chunk.text ?? "");
737
- }
738
- }
739
- async completionWithRetry(request, options) {
740
- return this.caller.callWithOptions({ signal: options?.signal }, async () => {
741
- try {
742
- return await this.client.generateContent(request);
743
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
744
- }
745
- catch (e) {
746
- // TODO: Improve error handling
747
- if (e.message?.includes("400 Bad Request")) {
748
- e.status = 400;
749
- }
750
- throw e;
751
- }
752
- });
753
- }
754
- withStructuredOutput(outputSchema, config) {
755
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
756
- const schema = outputSchema;
757
- const name = config?.name;
758
- const method = config?.method;
759
- const includeRaw = config?.includeRaw;
760
- if (method === "jsonMode") {
761
- throw new Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);
762
- }
763
- let llm;
764
- let outputParser;
765
- if (method === "functionCalling") {
766
- let functionName = name ?? "extract";
767
- let tools;
768
- if ((0, types_1.isInteropZodSchema)(schema)) {
769
- const jsonSchema = (0, zod_to_genai_parameters_js_1.schemaToGenerativeAIParameters)(schema);
770
- tools = [
771
- {
772
- functionDeclarations: [
773
- {
774
- name: functionName,
775
- description: jsonSchema.description ?? "A function available to call.",
776
- parameters: jsonSchema,
777
- },
778
- ],
779
- },
780
- ];
781
- outputParser = new output_parsers_js_1.GoogleGenerativeAIToolsOutputParser({
782
- returnSingle: true,
783
- keyName: functionName,
784
- zodSchema: schema,
785
- });
786
- }
787
- else {
788
- let geminiFunctionDefinition;
789
- if (typeof schema.name === "string" &&
790
- typeof schema.parameters === "object" &&
791
- schema.parameters != null) {
792
- geminiFunctionDefinition = schema;
793
- geminiFunctionDefinition.parameters = (0, zod_to_genai_parameters_js_1.removeAdditionalProperties)(schema.parameters);
794
- functionName = schema.name;
795
- }
796
- else {
797
- geminiFunctionDefinition = {
798
- name: functionName,
799
- description: schema.description ?? "",
800
- parameters: (0, zod_to_genai_parameters_js_1.removeAdditionalProperties)(schema),
801
- };
802
- }
803
- tools = [
804
- {
805
- functionDeclarations: [geminiFunctionDefinition],
806
- },
807
- ];
808
- outputParser = new output_parsers_js_1.GoogleGenerativeAIToolsOutputParser({
809
- returnSingle: true,
810
- keyName: functionName,
811
- });
812
- }
813
- llm = this.bindTools(tools).withConfig({
814
- allowedFunctionNames: [functionName],
815
- });
816
- }
817
- else {
818
- const jsonSchema = (0, zod_to_genai_parameters_js_1.schemaToGenerativeAIParameters)(schema);
819
- llm = this.withConfig({
820
- responseSchema: jsonSchema,
821
- });
822
- outputParser = new output_parsers_1.JsonOutputParser();
823
- }
824
- if (!includeRaw) {
825
- return llm.pipe(outputParser).withConfig({
826
- runName: "ChatGoogleGenerativeAIStructuredOutput",
827
- });
828
- }
829
- const parserAssign = runnables_1.RunnablePassthrough.assign({
830
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
831
- parsed: (input, config) => outputParser.invoke(input.raw, config),
832
- });
833
- const parserNone = runnables_1.RunnablePassthrough.assign({
834
- parsed: () => null,
835
- });
836
- const parsedWithFallback = parserAssign.withFallbacks({
837
- fallbacks: [parserNone],
838
- });
839
- return runnables_1.RunnableSequence.from([
840
- {
841
- raw: llm,
842
- },
843
- parsedWithFallback,
844
- ]).withConfig({
845
- runName: "StructuredOutputRunnable",
846
- });
847
- }
848
- }
16
+ * Google Generative AI chat model integration.
17
+ *
18
+ * Setup:
19
+ * Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`.
20
+ *
21
+ * ```bash
22
+ * npm install @langchain/google-genai
23
+ * export GOOGLE_API_KEY="your-api-key"
24
+ * ```
25
+ *
26
+ * ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor)
27
+ *
28
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html)
29
+ *
30
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
31
+ * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:
32
+ *
33
+ * ```typescript
34
+ * // When calling `.withConfig`, call options should be passed via the first argument
35
+ * const llmWithArgsBound = llm.withConfig({
36
+ * stop: ["\n"],
37
+ * });
38
+ *
39
+ * // When calling `.bindTools`, call options should be passed via the second argument
40
+ * const llmWithTools = llm.bindTools(
41
+ * [...],
42
+ * {
43
+ * stop: ["\n"],
44
+ * }
45
+ * );
46
+ * ```
47
+ *
48
+ * ## Examples
49
+ *
50
+ * <details open>
51
+ * <summary><strong>Instantiate</strong></summary>
52
+ *
53
+ * ```typescript
54
+ * import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
55
+ *
56
+ * const llm = new ChatGoogleGenerativeAI({
57
+ * model: "gemini-1.5-flash",
58
+ * temperature: 0,
59
+ * maxRetries: 2,
60
+ * // apiKey: "...",
61
+ * // other params...
62
+ * });
63
+ * ```
64
+ * </details>
65
+ *
66
+ * <br />
67
+ *
68
+ * <details>
69
+ * <summary><strong>Invoking</strong></summary>
70
+ *
71
+ * ```typescript
72
+ * const input = `Translate "I love programming" into French.`;
73
+ *
74
+ * // Models also accept a list of chat messages or a formatted prompt
75
+ * const result = await llm.invoke(input);
76
+ * console.log(result);
77
+ * ```
78
+ *
79
+ * ```txt
80
+ * AIMessage {
81
+ * "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n",
82
+ * "response_metadata": {
83
+ * "finishReason": "STOP",
84
+ * "index": 0,
85
+ * "safetyRatings": [
86
+ * {
87
+ * "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
88
+ * "probability": "NEGLIGIBLE"
89
+ * },
90
+ * {
91
+ * "category": "HARM_CATEGORY_HATE_SPEECH",
92
+ * "probability": "NEGLIGIBLE"
93
+ * },
94
+ * {
95
+ * "category": "HARM_CATEGORY_HARASSMENT",
96
+ * "probability": "NEGLIGIBLE"
97
+ * },
98
+ * {
99
+ * "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
100
+ * "probability": "NEGLIGIBLE"
101
+ * }
102
+ * ]
103
+ * },
104
+ * "usage_metadata": {
105
+ * "input_tokens": 10,
106
+ * "output_tokens": 149,
107
+ * "total_tokens": 159
108
+ * }
109
+ * }
110
+ * ```
111
+ * </details>
112
+ *
113
+ * <br />
114
+ *
115
+ * <details>
116
+ * <summary><strong>Streaming Chunks</strong></summary>
117
+ *
118
+ * ```typescript
119
+ * for await (const chunk of await llm.stream(input)) {
120
+ * console.log(chunk);
121
+ * }
122
+ * ```
123
+ *
124
+ * ```txt
125
+ * AIMessageChunk {
126
+ * "content": "There",
127
+ * "response_metadata": {
128
+ * "index": 0
129
+ * }
130
+ * "usage_metadata": {
131
+ * "input_tokens": 10,
132
+ * "output_tokens": 1,
133
+ * "total_tokens": 11
134
+ * }
135
+ * }
136
+ * AIMessageChunk {
137
+ * "content": " are a few ways to translate \"I love programming\" into French, depending on",
138
+ * }
139
+ * AIMessageChunk {
140
+ * "content": " the level of formality and nuance you want to convey:\n\n**Formal:**\n\n",
141
+ * }
142
+ * AIMessageChunk {
143
+ * "content": "* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This",
144
+ * }
145
+ * AIMessageChunk {
146
+ * "content": " is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More",
147
+ * }
148
+ * AIMessageChunk {
149
+ * "content": " specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and",
150
+ * }
151
+ * AIMessageChunk {
152
+ * "content": " your intended audience. \n",
153
+ * }
154
+ * ```
155
+ * </details>
156
+ *
157
+ * <br />
158
+ *
159
+ * <details>
160
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
161
+ *
162
+ * ```typescript
163
+ * import { AIMessageChunk } from '@langchain/core/messages';
164
+ * import { concat } from '@langchain/core/utils/stream';
165
+ *
166
+ * const stream = await llm.stream(input);
167
+ * let full: AIMessageChunk | undefined;
168
+ * for await (const chunk of stream) {
169
+ * full = !full ? chunk : concat(full, chunk);
170
+ * }
171
+ * console.log(full);
172
+ * ```
173
+ *
174
+ * ```txt
175
+ * AIMessageChunk {
176
+ * "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n",
177
+ * "usage_metadata": {
178
+ * "input_tokens": 10,
179
+ * "output_tokens": 277,
180
+ * "total_tokens": 287
181
+ * }
182
+ * }
183
+ * ```
184
+ * </details>
185
+ *
186
+ * <br />
187
+ *
188
+ * <details>
189
+ * <summary><strong>Bind tools</strong></summary>
190
+ *
191
+ * ```typescript
192
+ * import { z } from 'zod';
193
+ *
194
+ * const GetWeather = {
195
+ * name: "GetWeather",
196
+ * description: "Get the current weather in a given location",
197
+ * schema: z.object({
198
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
199
+ * }),
200
+ * }
201
+ *
202
+ * const GetPopulation = {
203
+ * name: "GetPopulation",
204
+ * description: "Get the current population in a given location",
205
+ * schema: z.object({
206
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
207
+ * }),
208
+ * }
209
+ *
210
+ * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
211
+ * const aiMsg = await llmWithTools.invoke(
212
+ * "Which city is hotter today and which is bigger: LA or NY?"
213
+ * );
214
+ * console.log(aiMsg.tool_calls);
215
+ * ```
216
+ *
217
+ * ```txt
218
+ * [
219
+ * {
220
+ * name: 'GetWeather',
221
+ * args: { location: 'Los Angeles, CA' },
222
+ * type: 'tool_call'
223
+ * },
224
+ * {
225
+ * name: 'GetWeather',
226
+ * args: { location: 'New York, NY' },
227
+ * type: 'tool_call'
228
+ * },
229
+ * {
230
+ * name: 'GetPopulation',
231
+ * args: { location: 'Los Angeles, CA' },
232
+ * type: 'tool_call'
233
+ * },
234
+ * {
235
+ * name: 'GetPopulation',
236
+ * args: { location: 'New York, NY' },
237
+ * type: 'tool_call'
238
+ * }
239
+ * ]
240
+ * ```
241
+ * </details>
242
+ *
243
+ * <br />
244
+ *
245
+ * <details>
246
+ * <summary><strong>Structured Output</strong></summary>
247
+ *
248
+ * ```typescript
249
+ * const Joke = z.object({
250
+ * setup: z.string().describe("The setup of the joke"),
251
+ * punchline: z.string().describe("The punchline to the joke"),
252
+ * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
253
+ * }).describe('Joke to tell user.');
254
+ *
255
+ * const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
256
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
257
+ * console.log(jokeResult);
258
+ * ```
259
+ *
260
+ * ```txt
261
+ * {
262
+ * setup: "Why don\\'t cats play poker?",
263
+ * punchline: "Why don\\'t cats play poker? Because they always have an ace up their sleeve!"
264
+ * }
265
+ * ```
266
+ * </details>
267
+ *
268
+ * <br />
269
+ *
270
+ * <details>
271
+ * <summary><strong>Multimodal</strong></summary>
272
+ *
273
+ * ```typescript
274
+ * import { HumanMessage } from '@langchain/core/messages';
275
+ *
276
+ * const imageUrl = "https://example.com/image.jpg";
277
+ * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
278
+ * const base64Image = Buffer.from(imageData).toString('base64');
279
+ *
280
+ * const message = new HumanMessage({
281
+ * content: [
282
+ * { type: "text", text: "describe the weather in this image" },
283
+ * {
284
+ * type: "image_url",
285
+ * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
286
+ * },
287
+ * ]
288
+ * });
289
+ *
290
+ * const imageDescriptionAiMsg = await llm.invoke([message]);
291
+ * console.log(imageDescriptionAiMsg.content);
292
+ * ```
293
+ *
294
+ * ```txt
295
+ * The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.
296
+ * ```
297
+ * </details>
298
+ *
299
+ * <br />
300
+ *
301
+ * <details>
302
+ * <summary><strong>Usage Metadata</strong></summary>
303
+ *
304
+ * ```typescript
305
+ * const aiMsgForMetadata = await llm.invoke(input);
306
+ * console.log(aiMsgForMetadata.usage_metadata);
307
+ * ```
308
+ *
309
+ * ```txt
310
+ * { input_tokens: 10, output_tokens: 149, total_tokens: 159 }
311
+ * ```
312
+ * </details>
313
+ *
314
+ * <br />
315
+ *
316
+ * <details>
317
+ * <summary><strong>Response Metadata</strong></summary>
318
+ *
319
+ * ```typescript
320
+ * const aiMsgForResponseMetadata = await llm.invoke(input);
321
+ * console.log(aiMsgForResponseMetadata.response_metadata);
322
+ * ```
323
+ *
324
+ * ```txt
325
+ * {
326
+ * finishReason: 'STOP',
327
+ * index: 0,
328
+ * safetyRatings: [
329
+ * {
330
+ * category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
331
+ * probability: 'NEGLIGIBLE'
332
+ * },
333
+ * {
334
+ * category: 'HARM_CATEGORY_HATE_SPEECH',
335
+ * probability: 'NEGLIGIBLE'
336
+ * },
337
+ * { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },
338
+ * {
339
+ * category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
340
+ * probability: 'NEGLIGIBLE'
341
+ * }
342
+ * ]
343
+ * }
344
+ * ```
345
+ * </details>
346
+ *
347
+ * <br />
348
+ *
349
+ * <details>
350
+ * <summary><strong>Document Messages</strong></summary>
351
+ *
352
+ * This example will show you how to pass documents such as PDFs to Google
353
+ * Generative AI through messages.
354
+ *
355
+ * ```typescript
356
+ * const pdfPath = "/Users/my_user/Downloads/invoice.pdf";
357
+ * const pdfBase64 = await fs.readFile(pdfPath, "base64");
358
+ *
359
+ * const response = await llm.invoke([
360
+ * ["system", "Use the provided documents to answer the question"],
361
+ * [
362
+ * "user",
363
+ * [
364
+ * {
365
+ * type: "application/pdf", // If the `type` field includes a single slash (`/`), it will be treated as inline data.
366
+ * data: pdfBase64,
367
+ * },
368
+ * {
369
+ * type: "text",
370
+ * text: "Summarize the contents of this PDF",
371
+ * },
372
+ * ],
373
+ * ],
374
+ * ]);
375
+ *
376
+ * console.log(response.content);
377
+ * ```
378
+ *
379
+ * ```txt
380
+ * This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025,
381
+ * and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC).
382
+ * The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022,
383
+ * expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is
384
+ * X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply.
385
+ * ```
386
+ * </details>
387
+ *
388
+ * <br />
389
+ */
390
+ var ChatGoogleGenerativeAI = class extends __langchain_core_language_models_chat_models.BaseChatModel {
391
+ static lc_name() {
392
+ return "ChatGoogleGenerativeAI";
393
+ }
394
+ lc_serializable = true;
395
+ get lc_secrets() {
396
+ return { apiKey: "GOOGLE_API_KEY" };
397
+ }
398
+ lc_namespace = [
399
+ "langchain",
400
+ "chat_models",
401
+ "google_genai"
402
+ ];
403
+ get lc_aliases() {
404
+ return { apiKey: "google_api_key" };
405
+ }
406
+ model;
407
+ temperature;
408
+ maxOutputTokens;
409
+ topP;
410
+ topK;
411
+ stopSequences = [];
412
+ safetySettings;
413
+ apiKey;
414
+ streaming = false;
415
+ json;
416
+ streamUsage = true;
417
+ convertSystemMessageToHumanContent;
418
+ client;
419
+ get _isMultimodalModel() {
420
+ return this.model.includes("vision") || this.model.startsWith("gemini-1.5") || this.model.startsWith("gemini-2") || this.model.startsWith("gemma-3-") && !this.model.startsWith("gemma-3-1b");
421
+ }
422
+ constructor(fields) {
423
+ super(fields);
424
+ this.model = fields.model.replace(/^models\//, "");
425
+ this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens;
426
+ if (this.maxOutputTokens && this.maxOutputTokens < 0) throw new Error("`maxOutputTokens` must be a positive integer");
427
+ this.temperature = fields.temperature ?? this.temperature;
428
+ if (this.temperature && (this.temperature < 0 || this.temperature > 2)) throw new Error("`temperature` must be in the range of [0.0,2.0]");
429
+ this.topP = fields.topP ?? this.topP;
430
+ if (this.topP && this.topP < 0) throw new Error("`topP` must be a positive integer");
431
+ if (this.topP && this.topP > 1) throw new Error("`topP` must be below 1.");
432
+ this.topK = fields.topK ?? this.topK;
433
+ if (this.topK && this.topK < 0) throw new Error("`topK` must be a positive integer");
434
+ this.stopSequences = fields.stopSequences ?? this.stopSequences;
435
+ this.apiKey = fields.apiKey ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("GOOGLE_API_KEY");
436
+ if (!this.apiKey) throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");
437
+ this.safetySettings = fields.safetySettings ?? this.safetySettings;
438
+ if (this.safetySettings && this.safetySettings.length > 0) {
439
+ const safetySettingsSet = new Set(this.safetySettings.map((s) => s.category));
440
+ if (safetySettingsSet.size !== this.safetySettings.length) throw new Error("The categories in `safetySettings` array must be unique");
441
+ }
442
+ this.streaming = fields.streaming ?? this.streaming;
443
+ this.json = fields.json;
444
+ this.client = new __google_generative_ai.GoogleGenerativeAI(this.apiKey).getGenerativeModel({
445
+ model: this.model,
446
+ safetySettings: this.safetySettings,
447
+ generationConfig: {
448
+ stopSequences: this.stopSequences,
449
+ maxOutputTokens: this.maxOutputTokens,
450
+ temperature: this.temperature,
451
+ topP: this.topP,
452
+ topK: this.topK,
453
+ ...this.json ? { responseMimeType: "application/json" } : {}
454
+ }
455
+ }, {
456
+ apiVersion: fields.apiVersion,
457
+ baseUrl: fields.baseUrl
458
+ });
459
+ this.streamUsage = fields.streamUsage ?? this.streamUsage;
460
+ }
461
+ useCachedContent(cachedContent, modelParams, requestOptions) {
462
+ if (!this.apiKey) return;
463
+ this.client = new __google_generative_ai.GoogleGenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions);
464
+ }
465
+ get useSystemInstruction() {
466
+ return typeof this.convertSystemMessageToHumanContent === "boolean" ? !this.convertSystemMessageToHumanContent : this.computeUseSystemInstruction;
467
+ }
468
+ get computeUseSystemInstruction() {
469
+ if (this.model === "gemini-1.0-pro-001") return false;
470
+ else if (this.model.startsWith("gemini-pro-vision")) return false;
471
+ else if (this.model.startsWith("gemini-1.0-pro-vision")) return false;
472
+ else if (this.model === "gemini-pro") return false;
473
+ return true;
474
+ }
475
+ getLsParams(options) {
476
+ return {
477
+ ls_provider: "google_genai",
478
+ ls_model_name: this.model,
479
+ ls_model_type: "chat",
480
+ ls_temperature: this.client.generationConfig.temperature,
481
+ ls_max_tokens: this.client.generationConfig.maxOutputTokens,
482
+ ls_stop: options.stop
483
+ };
484
+ }
485
+ _combineLLMOutput() {
486
+ return [];
487
+ }
488
+ _llmType() {
489
+ return "googlegenerativeai";
490
+ }
491
+ bindTools(tools, kwargs) {
492
+ return this.withConfig({
493
+ tools: require_tools.convertToolsToGenAI(tools)?.tools,
494
+ ...kwargs
495
+ });
496
+ }
497
+ invocationParams(options) {
498
+ const toolsAndConfig = options?.tools?.length ? require_tools.convertToolsToGenAI(options.tools, {
499
+ toolChoice: options.tool_choice,
500
+ allowedFunctionNames: options.allowedFunctionNames
501
+ }) : void 0;
502
+ if (options?.responseSchema) {
503
+ this.client.generationConfig.responseSchema = options.responseSchema;
504
+ this.client.generationConfig.responseMimeType = "application/json";
505
+ } else {
506
+ this.client.generationConfig.responseSchema = void 0;
507
+ this.client.generationConfig.responseMimeType = this.json ? "application/json" : void 0;
508
+ }
509
+ return {
510
+ ...toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {},
511
+ ...toolsAndConfig?.toolConfig ? { toolConfig: toolsAndConfig.toolConfig } : {}
512
+ };
513
+ }
514
+ async _generate(messages, options, runManager) {
515
+ const prompt = require_common.convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);
516
+ let actualPrompt = prompt;
517
+ if (prompt[0].role === "system") {
518
+ const [systemInstruction] = prompt;
519
+ this.client.systemInstruction = systemInstruction;
520
+ actualPrompt = prompt.slice(1);
521
+ }
522
+ const parameters = this.invocationParams(options);
523
+ if (this.streaming) {
524
+ const tokenUsage = {};
525
+ const stream = this._streamResponseChunks(messages, options, runManager);
526
+ const finalChunks = {};
527
+ for await (const chunk of stream) {
528
+ const index = chunk.generationInfo?.completion ?? 0;
529
+ if (finalChunks[index] === void 0) finalChunks[index] = chunk;
530
+ else finalChunks[index] = finalChunks[index].concat(chunk);
531
+ }
532
+ const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value);
533
+ return {
534
+ generations,
535
+ llmOutput: { estimatedTokenUsage: tokenUsage }
536
+ };
537
+ }
538
+ const res = await this.completionWithRetry({
539
+ ...parameters,
540
+ contents: actualPrompt
541
+ });
542
+ let usageMetadata;
543
+ if ("usageMetadata" in res.response) {
544
+ const genAIUsageMetadata = res.response.usageMetadata;
545
+ usageMetadata = {
546
+ input_tokens: genAIUsageMetadata.promptTokenCount ?? 0,
547
+ output_tokens: genAIUsageMetadata.candidatesTokenCount ?? 0,
548
+ total_tokens: genAIUsageMetadata.totalTokenCount ?? 0
549
+ };
550
+ }
551
+ const generationResult = require_common.mapGenerateContentResultToChatResult(res.response, { usageMetadata });
552
+ if (generationResult.generations?.length > 0) await runManager?.handleLLMNewToken(generationResult.generations[0]?.text ?? "");
553
+ return generationResult;
554
+ }
555
+ async *_streamResponseChunks(messages, options, runManager) {
556
+ const prompt = require_common.convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);
557
+ let actualPrompt = prompt;
558
+ if (prompt[0].role === "system") {
559
+ const [systemInstruction] = prompt;
560
+ this.client.systemInstruction = systemInstruction;
561
+ actualPrompt = prompt.slice(1);
562
+ }
563
+ const parameters = this.invocationParams(options);
564
+ const request = {
565
+ ...parameters,
566
+ contents: actualPrompt
567
+ };
568
+ const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => {
569
+ const { stream: stream$1 } = await this.client.generateContentStream(request);
570
+ return stream$1;
571
+ });
572
+ let usageMetadata;
573
+ let prevPromptTokenCount = 0;
574
+ let prevCandidatesTokenCount = 0;
575
+ let prevTotalTokenCount = 0;
576
+ let index = 0;
577
+ for await (const response of stream) {
578
+ if ("usageMetadata" in response && response.usageMetadata !== void 0 && this.streamUsage !== false && options.streamUsage !== false) {
579
+ usageMetadata = {
580
+ input_tokens: response.usageMetadata.promptTokenCount ?? 0,
581
+ output_tokens: response.usageMetadata.candidatesTokenCount ?? 0,
582
+ total_tokens: response.usageMetadata.totalTokenCount ?? 0
583
+ };
584
+ const newPromptTokenCount = response.usageMetadata.promptTokenCount ?? 0;
585
+ usageMetadata.input_tokens = Math.max(0, newPromptTokenCount - prevPromptTokenCount);
586
+ prevPromptTokenCount = newPromptTokenCount;
587
+ const newCandidatesTokenCount = response.usageMetadata.candidatesTokenCount ?? 0;
588
+ usageMetadata.output_tokens = Math.max(0, newCandidatesTokenCount - prevCandidatesTokenCount);
589
+ prevCandidatesTokenCount = newCandidatesTokenCount;
590
+ const newTotalTokenCount = response.usageMetadata.totalTokenCount ?? 0;
591
+ usageMetadata.total_tokens = Math.max(0, newTotalTokenCount - prevTotalTokenCount);
592
+ prevTotalTokenCount = newTotalTokenCount;
593
+ }
594
+ const chunk = require_common.convertResponseContentToChatGenerationChunk(response, {
595
+ usageMetadata,
596
+ index
597
+ });
598
+ index += 1;
599
+ if (!chunk) continue;
600
+ yield chunk;
601
+ await runManager?.handleLLMNewToken(chunk.text ?? "");
602
+ }
603
+ }
604
+ async completionWithRetry(request, options) {
605
+ return this.caller.callWithOptions({ signal: options?.signal }, async () => {
606
+ try {
607
+ return await this.client.generateContent(request);
608
+ } catch (e) {
609
+ if (e.message?.includes("400 Bad Request")) e.status = 400;
610
+ throw e;
611
+ }
612
+ });
613
+ }
614
+ /**
615
+ * Return profiling information for the model.
616
+ *
617
+ * Provides information about the model's capabilities and constraints,
618
+ * including token limits, multimodal support, and advanced features like
619
+ * tool calling and structured output.
620
+ *
621
+ * @returns {ModelProfile} An object describing the model's capabilities and constraints
622
+ *
623
+ * @example
624
+ * ```typescript
625
+ * const model = new ChatGoogleGenerativeAI({ model: "gemini-1.5-flash" });
626
+ * const profile = model.profile;
627
+ * console.log(profile.maxInputTokens); // 2000000
628
+ * console.log(profile.imageInputs); // true
629
+ * ```
630
+ */
631
+ get profile() {
632
+ return require_profiles.default[this.model] ?? {};
633
+ }
634
+ withStructuredOutput(outputSchema, config) {
635
+ const schema = outputSchema;
636
+ const name = config?.name;
637
+ const method = config?.method;
638
+ const includeRaw = config?.includeRaw;
639
+ if (method === "jsonMode") throw new Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);
640
+ let llm;
641
+ let outputParser;
642
+ if (method === "functionCalling") {
643
+ let functionName = name ?? "extract";
644
+ let tools;
645
+ if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) {
646
+ const jsonSchema = require_zod_to_genai_parameters.schemaToGenerativeAIParameters(schema);
647
+ tools = [{ functionDeclarations: [{
648
+ name: functionName,
649
+ description: jsonSchema.description ?? "A function available to call.",
650
+ parameters: jsonSchema
651
+ }] }];
652
+ outputParser = new require_output_parsers.GoogleGenerativeAIToolsOutputParser({
653
+ returnSingle: true,
654
+ keyName: functionName,
655
+ zodSchema: schema
656
+ });
657
+ } else {
658
+ let geminiFunctionDefinition;
659
+ if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
660
+ geminiFunctionDefinition = schema;
661
+ geminiFunctionDefinition.parameters = require_zod_to_genai_parameters.removeAdditionalProperties(schema.parameters);
662
+ functionName = schema.name;
663
+ } else geminiFunctionDefinition = {
664
+ name: functionName,
665
+ description: schema.description ?? "",
666
+ parameters: require_zod_to_genai_parameters.removeAdditionalProperties(schema)
667
+ };
668
+ tools = [{ functionDeclarations: [geminiFunctionDefinition] }];
669
+ outputParser = new require_output_parsers.GoogleGenerativeAIToolsOutputParser({
670
+ returnSingle: true,
671
+ keyName: functionName
672
+ });
673
+ }
674
+ llm = this.bindTools(tools).withConfig({ allowedFunctionNames: [functionName] });
675
+ } else {
676
+ const jsonSchema = require_zod_to_genai_parameters.schemaToGenerativeAIParameters(schema);
677
+ llm = this.withConfig({ responseSchema: jsonSchema });
678
+ outputParser = new __langchain_core_output_parsers.JsonOutputParser();
679
+ }
680
+ if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatGoogleGenerativeAIStructuredOutput" });
681
+ const parserAssign = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });
682
+ const parserNone = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: () => null });
683
+ const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });
684
+ return __langchain_core_runnables.RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" });
685
+ }
686
+ };
687
+
688
+ //#endregion
849
689
  exports.ChatGoogleGenerativeAI = ChatGoogleGenerativeAI;
690
+ //# sourceMappingURL=chat_models.cjs.map