@blaxel/langgraph 0.2.50-dev.215 → 0.2.50-preview.115

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 (35) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/.tsbuildinfo +1 -1
  3. package/dist/cjs/model/cohere.js +74 -0
  4. package/dist/cjs/model/google-genai.js +75 -12
  5. package/dist/cjs/model.js +1 -1
  6. package/dist/cjs/types/model/google-genai.d.ts +20 -3
  7. package/dist/esm/.tsbuildinfo +1 -1
  8. package/dist/esm/model/cohere.js +74 -0
  9. package/dist/esm/model/google-genai.js +74 -11
  10. package/dist/esm/model.js +1 -1
  11. package/package.json +3 -2
  12. package/dist/cjs/model/google-genai/chat_models.js +0 -766
  13. package/dist/cjs/model/google-genai/embeddings.js +0 -111
  14. package/dist/cjs/model/google-genai/index.js +0 -18
  15. package/dist/cjs/model/google-genai/output_parsers.js +0 -51
  16. package/dist/cjs/model/google-genai/types.js +0 -2
  17. package/dist/cjs/model/google-genai/utils/common.js +0 -390
  18. package/dist/cjs/model/google-genai/utils/tools.js +0 -110
  19. package/dist/cjs/model/google-genai/utils/zod_to_genai_parameters.js +0 -46
  20. package/dist/cjs/types/model/google-genai/chat_models.d.ts +0 -557
  21. package/dist/cjs/types/model/google-genai/embeddings.d.ts +0 -94
  22. package/dist/cjs/types/model/google-genai/index.d.ts +0 -2
  23. package/dist/cjs/types/model/google-genai/output_parsers.d.ts +0 -20
  24. package/dist/cjs/types/model/google-genai/types.d.ts +0 -3
  25. package/dist/cjs/types/model/google-genai/utils/common.d.ts +0 -22
  26. package/dist/cjs/types/model/google-genai/utils/tools.d.ts +0 -10
  27. package/dist/cjs/types/model/google-genai/utils/zod_to_genai_parameters.d.ts +0 -13
  28. package/dist/esm/model/google-genai/chat_models.js +0 -762
  29. package/dist/esm/model/google-genai/embeddings.js +0 -107
  30. package/dist/esm/model/google-genai/index.js +0 -2
  31. package/dist/esm/model/google-genai/output_parsers.js +0 -47
  32. package/dist/esm/model/google-genai/types.js +0 -1
  33. package/dist/esm/model/google-genai/utils/common.js +0 -381
  34. package/dist/esm/model/google-genai/utils/tools.js +0 -107
  35. package/dist/esm/model/google-genai/utils/zod_to_genai_parameters.js +0 -41
@@ -1,762 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unsafe-member-access */
2
- /* eslint-disable @typescript-eslint/no-unsafe-call */
3
- /* eslint-disable @typescript-eslint/no-unsafe-assignment */
4
- import { GoogleGenerativeAI as GenerativeAI, } from "@google/generative-ai";
5
- import { BaseChatModel, } from "@langchain/core/language_models/chat_models";
6
- import { RunnablePassthrough, RunnableSequence, } from "@langchain/core/runnables";
7
- import { getEnvironmentVariable } from "@langchain/core/utils/env";
8
- import { isZodSchema } from "@langchain/core/utils/types";
9
- import { GoogleGenerativeAIToolsOutputParser } from "./output_parsers.js";
10
- import { convertBaseMessagesToContent, convertResponseContentToChatGenerationChunk, mapGenerateContentResultToChatResult, } from "./utils/common.js";
11
- import { convertToolsToGenAI } from "./utils/tools.js";
12
- import { zodToGenerativeAIParameters } from "./utils/zod_to_genai_parameters.js";
13
- /**
14
- * Google Generative AI chat model integration.
15
- *
16
- * Setup:
17
- * Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`.
18
- *
19
- * ```bash
20
- * pnpm install @langchain/google-genai
21
- * export GOOGLE_API_KEY="your-api-key"
22
- * ```
23
- *
24
- * ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor)
25
- *
26
- * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html)
27
- *
28
- * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
29
- * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
30
- *
31
- * ```typescript
32
- * // When calling `.bind`, call options should be passed via the first argument
33
- * const llmWithArgsBound = llm.bind({
34
- * stop: ["\n"],
35
- * tools: [...],
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
- // @ts-ignore - Type instantiation depth issue with complex generics
390
- export class ChatGoogleGenerativeAI extends BaseChatModel {
391
- static lc_name() {
392
- return "ChatGoogleGenerativeAI";
393
- }
394
- lc_serializable = true;
395
- get lc_secrets() {
396
- return {
397
- apiKey: "GOOGLE_API_KEY",
398
- };
399
- }
400
- lc_namespace = ["langchain", "chat_models", "google_genai"];
401
- get lc_aliases() {
402
- return {
403
- apiKey: "google_api_key",
404
- };
405
- }
406
- modelName = "gemini-pro";
407
- model = "gemini-pro";
408
- customHeaders;
409
- temperature; // default value chosen based on model
410
- maxOutputTokens;
411
- topP; // default value chosen based on model
412
- topK; // default value chosen based on model
413
- stopSequences = [];
414
- safetySettings;
415
- apiKey;
416
- streaming = false;
417
- streamUsage = true;
418
- convertSystemMessageToHumanContent;
419
- baseUrl;
420
- apiVersion;
421
- client;
422
- get _isMultimodalModel() {
423
- return (this.model.includes("vision") ||
424
- this.model.startsWith("gemini-1.5") ||
425
- this.model.startsWith("gemini-2"));
426
- }
427
- constructor(fields) {
428
- super(fields ?? {});
429
- this.modelName =
430
- fields?.model?.replace(/^models\//, "") ??
431
- fields?.modelName?.replace(/^models\//, "") ??
432
- this.model;
433
- this.model = this.modelName;
434
- this.maxOutputTokens = fields?.maxOutputTokens ?? this.maxOutputTokens;
435
- if (this.maxOutputTokens && this.maxOutputTokens < 0) {
436
- throw new Error("`maxOutputTokens` must be a positive integer");
437
- }
438
- this.temperature = fields?.temperature ?? this.temperature;
439
- if (this.temperature && (this.temperature < 0 || this.temperature > 1)) {
440
- throw new Error("`temperature` must be in the range of [0.0,1.0]");
441
- }
442
- this.topP = fields?.topP ?? this.topP;
443
- if (this.topP && this.topP < 0) {
444
- throw new Error("`topP` must be a positive integer");
445
- }
446
- if (this.topP && this.topP > 1) {
447
- throw new Error("`topP` must be below 1.");
448
- }
449
- this.topK = fields?.topK ?? this.topK;
450
- if (this.topK && this.topK < 0) {
451
- throw new Error("`topK` must be a positive integer");
452
- }
453
- this.stopSequences = fields?.stopSequences ?? this.stopSequences;
454
- this.apiKey = fields?.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY");
455
- this.apiVersion = fields?.apiVersion ?? this.apiVersion;
456
- this.baseUrl = fields?.baseUrl ?? this.baseUrl;
457
- this.safetySettings = fields?.safetySettings ?? this.safetySettings;
458
- if (this.safetySettings && this.safetySettings.length > 0) {
459
- const safetySettingsSet = new Set(this.safetySettings.map((s) => s.category));
460
- if (safetySettingsSet.size !== this.safetySettings.length) {
461
- throw new Error("The categories in `safetySettings` array must be unique");
462
- }
463
- }
464
- this.streaming = fields?.streaming ?? this.streaming;
465
- this.client = this.initClient(fields);
466
- this.streamUsage = fields?.streamUsage ?? this.streamUsage;
467
- }
468
- initClient(fields) {
469
- const apiKey = this.apiKey ? this.apiKey : "replaced";
470
- const apiVersion = this.apiVersion ?? fields?.apiVersion;
471
- const baseUrl = this.baseUrl ?? fields?.baseUrl;
472
- const customHeaders = this.customHeaders ?? fields?.customHeaders;
473
- return new GenerativeAI(apiKey).getGenerativeModel({
474
- model: this.model,
475
- safetySettings: this.safetySettings,
476
- generationConfig: {
477
- candidateCount: 1,
478
- stopSequences: this.stopSequences,
479
- maxOutputTokens: this.maxOutputTokens,
480
- temperature: this.temperature,
481
- topP: this.topP,
482
- topK: this.topK,
483
- ...(fields?.json ? { responseMimeType: "application/json" } : {}),
484
- },
485
- }, {
486
- apiVersion,
487
- baseUrl: baseUrl,
488
- customHeaders: customHeaders,
489
- });
490
- }
491
- useCachedContent(cachedContent, modelParams, requestOptions) {
492
- if (!this.apiKey)
493
- return;
494
- this.client = new GenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions);
495
- }
496
- get useSystemInstruction() {
497
- return typeof this.convertSystemMessageToHumanContent === "boolean"
498
- ? !this.convertSystemMessageToHumanContent
499
- : this.computeUseSystemInstruction;
500
- }
501
- get computeUseSystemInstruction() {
502
- // This works on models from April 2024 and later
503
- // Vertex AI: gemini-1.5-pro and gemini-1.0-002 and later
504
- // AI Studio: gemini-1.5-pro-latest
505
- if (this.modelName === "gemini-1.0-pro-001") {
506
- return false;
507
- }
508
- else if (this.modelName.startsWith("gemini-pro-vision")) {
509
- return false;
510
- }
511
- else if (this.modelName.startsWith("gemini-1.0-pro-vision")) {
512
- return false;
513
- }
514
- else if (this.modelName === "gemini-pro") {
515
- // on AI Studio gemini-pro is still pointing at gemini-1.0-pro-001
516
- return false;
517
- }
518
- return true;
519
- }
520
- getLsParams(options) {
521
- return {
522
- ls_provider: "google_genai",
523
- ls_model_name: this.model,
524
- ls_model_type: "chat",
525
- ls_temperature: this.client.generationConfig.temperature,
526
- ls_max_tokens: this.client.generationConfig.maxOutputTokens,
527
- ls_stop: options.stop,
528
- };
529
- }
530
- _combineLLMOutput() {
531
- return [];
532
- }
533
- _llmType() {
534
- return "googlegenerativeai";
535
- }
536
- bindTools(tools, kwargs) {
537
- const convertedTools = convertToolsToGenAI(tools);
538
- const bindOptions = { tools: convertedTools?.tools, ...kwargs };
539
- // BaseChatModel extends Runnable which has a bind method
540
- // Access bind through unknown to satisfy TypeScript's type checking
541
- const baseModel = this;
542
- return baseModel.bind(bindOptions);
543
- }
544
- invocationParams(options) {
545
- const toolsAndConfig = options?.tools?.length
546
- ? convertToolsToGenAI(options.tools, {
547
- toolChoice: options.tool_choice,
548
- allowedFunctionNames: options.allowedFunctionNames,
549
- })
550
- : undefined;
551
- return {
552
- ...(toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {}),
553
- ...(toolsAndConfig?.toolConfig
554
- ? { toolConfig: toolsAndConfig.toolConfig }
555
- : {}),
556
- };
557
- }
558
- async _generate(messages, options, runManager) {
559
- const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);
560
- let actualPrompt = prompt;
561
- if (prompt[0].role === "system") {
562
- const [systemInstruction] = prompt;
563
- this.client.systemInstruction = systemInstruction;
564
- actualPrompt = prompt.slice(1);
565
- }
566
- const parameters = this.invocationParams(options);
567
- // Handle streaming
568
- if (this.streaming) {
569
- const tokenUsage = {};
570
- const stream = this._streamResponseChunks(messages, options, runManager);
571
- const finalChunks = {};
572
- for await (const chunk of stream) {
573
- const index = chunk.generationInfo?.completion ?? 0;
574
- if (finalChunks[index] === undefined) {
575
- finalChunks[index] = chunk;
576
- }
577
- else {
578
- finalChunks[index] = finalChunks[index].concat(chunk);
579
- }
580
- }
581
- const generations = Object.entries(finalChunks)
582
- .sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10))
583
- .map(([, value]) => value);
584
- return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
585
- }
586
- const res = await this.completionWithRetry({
587
- ...parameters,
588
- contents: actualPrompt,
589
- });
590
- let usageMetadata;
591
- if ("usageMetadata" in res.response) {
592
- const genAIUsageMetadata = res.response.usageMetadata;
593
- usageMetadata = {
594
- input_tokens: genAIUsageMetadata.promptTokenCount ?? 0,
595
- output_tokens: genAIUsageMetadata.candidatesTokenCount ?? 0,
596
- total_tokens: genAIUsageMetadata.totalTokenCount ?? 0,
597
- };
598
- }
599
- const generationResult = mapGenerateContentResultToChatResult(res.response, {
600
- usageMetadata,
601
- });
602
- await runManager?.handleLLMNewToken(generationResult.generations[0].text ?? "");
603
- return generationResult;
604
- }
605
- async *_streamResponseChunks(messages, options, runManager) {
606
- const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);
607
- let actualPrompt = prompt;
608
- if (prompt[0].role === "system") {
609
- const [systemInstruction] = prompt;
610
- this.client.systemInstruction = systemInstruction;
611
- actualPrompt = prompt.slice(1);
612
- }
613
- const parameters = this.invocationParams(options);
614
- const request = {
615
- ...parameters,
616
- contents: actualPrompt,
617
- };
618
- const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => {
619
- const { stream } = await this.client.generateContentStream(request);
620
- return stream;
621
- });
622
- let usageMetadata;
623
- let index = 0;
624
- for await (const response of stream) {
625
- if ("usageMetadata" in response &&
626
- this.streamUsage !== false &&
627
- options.streamUsage !== false) {
628
- const genAIUsageMetadata = response.usageMetadata;
629
- if (!usageMetadata) {
630
- usageMetadata = {
631
- input_tokens: genAIUsageMetadata.promptTokenCount,
632
- output_tokens: genAIUsageMetadata.candidatesTokenCount,
633
- total_tokens: genAIUsageMetadata.totalTokenCount,
634
- };
635
- }
636
- else {
637
- // Under the hood, LangChain combines the prompt tokens. Google returns the updated
638
- // total each time, so we need to find the difference between the tokens.
639
- const outputTokenDiff = genAIUsageMetadata.candidatesTokenCount -
640
- usageMetadata.output_tokens;
641
- usageMetadata = {
642
- input_tokens: 0,
643
- output_tokens: outputTokenDiff,
644
- total_tokens: outputTokenDiff,
645
- };
646
- }
647
- }
648
- const chunk = convertResponseContentToChatGenerationChunk(response, {
649
- usageMetadata,
650
- index,
651
- });
652
- index += 1;
653
- if (!chunk) {
654
- continue;
655
- }
656
- yield chunk;
657
- await runManager?.handleLLMNewToken(chunk.text ?? "");
658
- }
659
- }
660
- async completionWithRetry(request, options) {
661
- return this.caller.callWithOptions({ signal: options?.signal }, async () => {
662
- try {
663
- return await this.client.generateContent(request);
664
- }
665
- catch (e) {
666
- // TODO: Improve error handling
667
- if (e.message?.includes("400 Bad Request")) {
668
- e.status = 400;
669
- }
670
- throw e;
671
- }
672
- });
673
- }
674
- withStructuredOutput(outputSchema, config) {
675
- const schema = outputSchema;
676
- const name = config?.name;
677
- const method = config?.method;
678
- const includeRaw = config?.includeRaw;
679
- if (method === "jsonMode") {
680
- throw new Error(`ChatGoogleGenerativeAI only supports "functionCalling" as a method.`);
681
- }
682
- let functionName = name ?? "extract";
683
- let outputParser;
684
- // @ts-ignore - Type instantiation depth issue with Zod schemas
685
- let tools;
686
- // @ts-ignore - Type instantiation depth issue with Zod schemas
687
- if (isZodSchema(schema)) {
688
- // @ts-ignore - Type instantiation depth issue with Zod schemas
689
- const jsonSchema = zodToGenerativeAIParameters(schema);
690
- tools = [
691
- {
692
- functionDeclarations: [
693
- {
694
- name: functionName,
695
- description: jsonSchema.description ?? "A function available to call.",
696
- parameters: jsonSchema,
697
- },
698
- ],
699
- },
700
- ];
701
- outputParser = new GoogleGenerativeAIToolsOutputParser({
702
- returnSingle: true,
703
- keyName: functionName,
704
- zodSchema: schema, // Type assertion to avoid deep instantiation issues
705
- });
706
- }
707
- else {
708
- let geminiFunctionDefinition;
709
- const schemaAsAny = schema; // Type assertion to handle union type
710
- if (typeof schemaAsAny.name === "string" &&
711
- typeof schemaAsAny.parameters === "object" &&
712
- schemaAsAny.parameters != null) {
713
- geminiFunctionDefinition = schemaAsAny;
714
- functionName = schemaAsAny.name;
715
- }
716
- else {
717
- geminiFunctionDefinition = {
718
- name: functionName,
719
- description: schemaAsAny.description ?? "",
720
- parameters: schemaAsAny,
721
- };
722
- }
723
- tools = [
724
- {
725
- functionDeclarations: [geminiFunctionDefinition],
726
- },
727
- ];
728
- outputParser = new GoogleGenerativeAIToolsOutputParser({
729
- returnSingle: true,
730
- keyName: functionName,
731
- });
732
- }
733
- // @ts-ignore - bind method exists on BaseChatModel but TypeScript can't infer it
734
- const llm = super.bind({
735
- tools,
736
- tool_choice: functionName,
737
- });
738
- if (!includeRaw) {
739
- return llm.pipe(outputParser).withConfig({
740
- runName: "ChatGoogleGenerativeAIStructuredOutput",
741
- });
742
- }
743
- const parserAssign = RunnablePassthrough.assign({
744
- parsed: (input, config) => outputParser.invoke(input.raw, config),
745
- });
746
- const parserNone = RunnablePassthrough.assign({
747
- raw: (input) => input.raw,
748
- parsed: () => ({}),
749
- });
750
- const parsedWithFallback = parserAssign.withFallbacks({
751
- fallbacks: [parserNone],
752
- });
753
- return RunnableSequence.from([
754
- {
755
- raw: llm,
756
- },
757
- parsedWithFallback,
758
- ]).withConfig({
759
- runName: "StructuredOutputRunnable",
760
- });
761
- }
762
- }