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