illuma-agents 1.0.6 → 1.0.8

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 (41) hide show
  1. package/dist/cjs/events.cjs +34 -10
  2. package/dist/cjs/events.cjs.map +1 -1
  3. package/dist/cjs/llm/google/index.cjs +78 -9
  4. package/dist/cjs/llm/google/index.cjs.map +1 -1
  5. package/dist/cjs/llm/google/utils/common.cjs +185 -28
  6. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  7. package/dist/cjs/messages/format.cjs +9 -1
  8. package/dist/cjs/messages/format.cjs.map +1 -1
  9. package/dist/cjs/tools/ToolNode.cjs +154 -55
  10. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  11. package/dist/esm/events.mjs +34 -10
  12. package/dist/esm/events.mjs.map +1 -1
  13. package/dist/esm/llm/google/index.mjs +79 -10
  14. package/dist/esm/llm/google/index.mjs.map +1 -1
  15. package/dist/esm/llm/google/utils/common.mjs +184 -30
  16. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  17. package/dist/esm/messages/format.mjs +9 -1
  18. package/dist/esm/messages/format.mjs.map +1 -1
  19. package/dist/esm/tools/ToolNode.mjs +155 -56
  20. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  21. package/dist/types/events.d.ts +3 -1
  22. package/dist/types/llm/google/index.d.ts +10 -0
  23. package/dist/types/llm/google/types.d.ts +11 -1
  24. package/dist/types/llm/google/utils/common.d.ts +17 -2
  25. package/dist/types/messages/format.d.ts +7 -1
  26. package/dist/types/tools/ToolNode.d.ts +9 -1
  27. package/dist/types/types/stream.d.ts +1 -1
  28. package/dist/types/types/tools.d.ts +1 -1
  29. package/package.json +3 -3
  30. package/src/events.ts +37 -15
  31. package/src/llm/google/data/gettysburg10.wav +0 -0
  32. package/src/llm/google/data/hotdog.jpg +0 -0
  33. package/src/llm/google/index.ts +129 -14
  34. package/src/llm/google/llm.spec.ts +932 -0
  35. package/src/llm/google/types.ts +56 -43
  36. package/src/llm/google/utils/common.ts +873 -660
  37. package/src/messages/ensureThinkingBlock.test.ts +75 -0
  38. package/src/messages/format.ts +9 -1
  39. package/src/tools/ToolNode.ts +195 -64
  40. package/src/types/stream.ts +1 -1
  41. package/src/types/tools.ts +80 -80
@@ -1,4 +1,4 @@
1
- import { isBaseMessage, AIMessageChunk, ChatMessage, isToolMessage, isAIMessage, isDataContentBlock, convertToProviderContentBlock, parseBase64DataUrl } from '@langchain/core/messages';
1
+ import { isBaseMessage, AIMessage, AIMessageChunk, ChatMessage, isToolMessage, isAIMessage, isDataContentBlock, convertToProviderContentBlock, parseBase64DataUrl } from '@langchain/core/messages';
2
2
  import { ChatGenerationChunk } from '@langchain/core/outputs';
3
3
  import '@langchain/core/utils/function_calling';
4
4
  import '@langchain/core/language_models/base';
@@ -6,6 +6,15 @@ import { v4 } from 'uuid';
6
6
  import '@langchain/core/utils/types';
7
7
  import '@langchain/core/utils/json_schema';
8
8
 
9
+ const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = '__gemini_function_call_thought_signatures__';
10
+ const DUMMY_SIGNATURE = 'ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==';
11
+ /**
12
+ * Executes a function immediately and returns its result.
13
+ * Functional utility similar to an Immediately Invoked Function Expression (IIFE).
14
+ * @param fn The function to execute.
15
+ * @returns The result of invoking fn.
16
+ */
17
+ const iife = (fn) => fn();
9
18
  function getMessageAuthor(message) {
10
19
  const type = message._getType();
11
20
  if (ChatMessage.isInstance(message)) {
@@ -233,19 +242,6 @@ function _convertLangChainContentToPart(content, isMultimodalModel) {
233
242
  },
234
243
  };
235
244
  }
236
- else if (content.type === 'document' ||
237
- content.type === 'audio' ||
238
- content.type === 'video') {
239
- if (!isMultimodalModel) {
240
- throw new Error(`This model does not support ${content.type}s`);
241
- }
242
- return {
243
- inlineData: {
244
- data: content.data,
245
- mimeType: content.mimeType,
246
- },
247
- };
248
- }
249
245
  else if (content.type === 'media') {
250
246
  return messageContentMedia(content);
251
247
  }
@@ -282,7 +278,7 @@ function _convertLangChainContentToPart(content, isMultimodalModel) {
282
278
  }
283
279
  }
284
280
  }
285
- function convertMessageContentToParts(message, isMultimodalModel, previousMessages) {
281
+ function convertMessageContentToParts(message, isMultimodalModel, previousMessages, model) {
286
282
  if (isToolMessage(message)) {
287
283
  const messageName = message.name ??
288
284
  inferToolNameFromPreviousMessages(message, previousMessages);
@@ -326,19 +322,33 @@ function convertMessageContentToParts(message, isMultimodalModel, previousMessag
326
322
  .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))
327
323
  .filter((p) => p !== undefined));
328
324
  }
329
- if (isAIMessage(message) && message.tool_calls?.length != null) {
330
- functionCalls = message.tool_calls.map((tc) => {
325
+ const functionThoughtSignatures = message.additional_kwargs?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY];
326
+ if (isAIMessage(message) && (message.tool_calls?.length ?? 0) > 0) {
327
+ functionCalls = (message.tool_calls ?? []).map((tc) => {
328
+ const thoughtSignature = iife(() => {
329
+ if (tc.id != null && tc.id !== '') {
330
+ const signature = functionThoughtSignatures?.[tc.id];
331
+ if (signature != null && signature !== '') {
332
+ return signature;
333
+ }
334
+ }
335
+ if (model?.includes('gemini-3') === true) {
336
+ return DUMMY_SIGNATURE;
337
+ }
338
+ return '';
339
+ });
331
340
  return {
332
341
  functionCall: {
333
342
  name: tc.name,
334
343
  args: tc.args,
335
344
  },
345
+ ...(thoughtSignature ? { thoughtSignature } : {}),
336
346
  };
337
347
  });
338
348
  }
339
349
  return [...messageParts, ...functionCalls];
340
350
  }
341
- function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false) {
351
+ function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false, model) {
342
352
  return messages.reduce((acc, message, index) => {
343
353
  if (!isBaseMessage(message)) {
344
354
  throw new Error('Unsupported message input');
@@ -354,7 +364,7 @@ function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystem
354
364
  prevContent.role === role) {
355
365
  throw new Error('Google Generative AI requires alternate messages between authors');
356
366
  }
357
- const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index));
367
+ const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index), model);
358
368
  if (acc.mergeWithPreviousContent) {
359
369
  const prevContent = acc.content?.[acc.content.length - 1];
360
370
  if (!prevContent) {
@@ -386,9 +396,20 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
386
396
  if (!response.candidates || response.candidates.length === 0) {
387
397
  return null;
388
398
  }
389
- const functionCalls = response.functionCalls();
390
399
  const [candidate] = response.candidates;
391
400
  const { content: candidateContent, ...generationInfo } = candidate ?? {};
401
+ // Extract function calls directly from parts to preserve thoughtSignature
402
+ const functionCalls = candidateContent?.parts?.reduce((acc, p) => {
403
+ if ('functionCall' in p && p.functionCall) {
404
+ acc.push({
405
+ ...p,
406
+ id: 'id' in p.functionCall && typeof p.functionCall.id === 'string'
407
+ ? p.functionCall.id
408
+ : v4(),
409
+ });
410
+ }
411
+ return acc;
412
+ }, []) ?? [];
392
413
  let content;
393
414
  // Checks if some parts do not have text. If false, it means that the content is a string.
394
415
  const reasoningParts = [];
@@ -407,9 +428,11 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
407
428
  content = textParts.join('');
408
429
  }
409
430
  else if (candidateContent && Array.isArray(candidateContent.parts)) {
410
- content = candidateContent.parts.map((p) => {
431
+ content = candidateContent.parts
432
+ .map((p) => {
411
433
  if ('text' in p && 'thought' in p && p.thought === true) {
412
434
  reasoningParts.push(p.text ?? '');
435
+ return undefined;
413
436
  }
414
437
  else if ('text' in p) {
415
438
  return {
@@ -430,7 +453,8 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
430
453
  };
431
454
  }
432
455
  return p;
433
- });
456
+ })
457
+ .filter((p) => p !== undefined);
434
458
  }
435
459
  else {
436
460
  // no content returned - likely due to abnormal stop reason, e.g. malformed function call
@@ -445,17 +469,26 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
445
469
  text = block?.text ?? '';
446
470
  }
447
471
  const toolCallChunks = [];
448
- if (functionCalls) {
472
+ if (functionCalls.length > 0) {
449
473
  toolCallChunks.push(...functionCalls.map((fc) => ({
450
- ...fc,
451
- args: JSON.stringify(fc.args),
452
- // Un-commenting this causes LangChain to incorrectly merge tool calls together
453
- // index: extra.index,
454
474
  type: 'tool_call_chunk',
455
- id: 'id' in fc && typeof fc.id === 'string' ? fc.id : v4(),
475
+ id: fc?.id,
476
+ name: fc?.functionCall.name,
477
+ args: JSON.stringify(fc?.functionCall.args),
456
478
  })));
457
479
  }
458
- const additional_kwargs = {};
480
+ // Extract thought signatures from function calls for Gemini 3+
481
+ const functionThoughtSignatures = functionCalls.reduce((acc, fc) => {
482
+ if (fc &&
483
+ 'thoughtSignature' in fc &&
484
+ typeof fc.thoughtSignature === 'string') {
485
+ acc[fc.id] = fc.thoughtSignature;
486
+ }
487
+ return acc;
488
+ }, {});
489
+ const additional_kwargs = {
490
+ [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,
491
+ };
459
492
  if (reasoningParts.length > 0) {
460
493
  additional_kwargs.reasoning = reasoningParts.join('');
461
494
  }
@@ -479,6 +512,127 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
479
512
  generationInfo,
480
513
  });
481
514
  }
515
+ /**
516
+ * Maps a Google GenerateContentResult to a LangChain ChatResult
517
+ */
518
+ function mapGenerateContentResultToChatResult(response, extra) {
519
+ if (!response.candidates ||
520
+ response.candidates.length === 0 ||
521
+ !response.candidates[0]) {
522
+ return {
523
+ generations: [],
524
+ llmOutput: {
525
+ filters: response.promptFeedback,
526
+ },
527
+ };
528
+ }
529
+ const [candidate] = response.candidates;
530
+ const { content: candidateContent, ...generationInfo } = candidate ?? {};
531
+ // Extract function calls directly from parts to preserve thoughtSignature
532
+ const functionCalls = candidateContent?.parts.reduce((acc, p) => {
533
+ if ('functionCall' in p && p.functionCall) {
534
+ acc.push({
535
+ ...p,
536
+ id: 'id' in p.functionCall && typeof p.functionCall.id === 'string'
537
+ ? p.functionCall.id
538
+ : v4(),
539
+ });
540
+ }
541
+ return acc;
542
+ }, []) ?? [];
543
+ let content;
544
+ const reasoningParts = [];
545
+ if (Array.isArray(candidateContent?.parts) &&
546
+ candidateContent.parts.length === 1 &&
547
+ candidateContent.parts[0].text &&
548
+ !('thought' in candidateContent.parts[0] &&
549
+ candidateContent.parts[0].thought === true)) {
550
+ content = candidateContent.parts[0].text;
551
+ }
552
+ else if (Array.isArray(candidateContent?.parts) &&
553
+ candidateContent.parts.length > 0) {
554
+ content = candidateContent.parts
555
+ .map((p) => {
556
+ if ('text' in p && 'thought' in p && p.thought === true) {
557
+ reasoningParts.push(p.text ?? '');
558
+ return undefined;
559
+ }
560
+ else if ('text' in p) {
561
+ return {
562
+ type: 'text',
563
+ text: p.text,
564
+ };
565
+ }
566
+ else if ('executableCode' in p) {
567
+ return {
568
+ type: 'executableCode',
569
+ executableCode: p.executableCode,
570
+ };
571
+ }
572
+ else if ('codeExecutionResult' in p) {
573
+ return {
574
+ type: 'codeExecutionResult',
575
+ codeExecutionResult: p.codeExecutionResult,
576
+ };
577
+ }
578
+ return p;
579
+ })
580
+ .filter((p) => p !== undefined);
581
+ }
582
+ else {
583
+ content = [];
584
+ }
585
+ let text = '';
586
+ if (typeof content === 'string') {
587
+ text = content;
588
+ }
589
+ else if (Array.isArray(content) && content.length > 0) {
590
+ const block = content.find((b) => 'text' in b);
591
+ text = block?.text ?? text;
592
+ }
593
+ const additional_kwargs = {
594
+ ...generationInfo,
595
+ };
596
+ if (reasoningParts.length > 0) {
597
+ additional_kwargs.reasoning = reasoningParts.join('');
598
+ }
599
+ // Extract thought signatures from function calls for Gemini 3+
600
+ const functionThoughtSignatures = functionCalls.reduce((acc, fc) => {
601
+ if ('thoughtSignature' in fc && typeof fc.thoughtSignature === 'string') {
602
+ acc[fc.id] = fc.thoughtSignature;
603
+ }
604
+ return acc;
605
+ }, {});
606
+ const tool_calls = functionCalls.map((fc) => ({
607
+ type: 'tool_call',
608
+ id: fc.id,
609
+ name: fc.functionCall.name,
610
+ args: fc.functionCall.args,
611
+ }));
612
+ // Store thought signatures map for later retrieval
613
+ additional_kwargs[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] =
614
+ functionThoughtSignatures;
615
+ const generation = {
616
+ text,
617
+ message: new AIMessage({
618
+ content: content ?? '',
619
+ tool_calls,
620
+ additional_kwargs,
621
+ usage_metadata: extra?.usageMetadata,
622
+ }),
623
+ generationInfo,
624
+ };
625
+ return {
626
+ generations: [generation],
627
+ llmOutput: {
628
+ tokenUsage: {
629
+ promptTokens: extra?.usageMetadata?.input_tokens,
630
+ completionTokens: extra?.usageMetadata?.output_tokens,
631
+ totalTokens: extra?.usageMetadata?.total_tokens,
632
+ },
633
+ },
634
+ };
635
+ }
482
636
 
483
- export { convertAuthorToRole, convertBaseMessagesToContent, convertMessageContentToParts, convertResponseContentToChatGenerationChunk, getMessageAuthor };
637
+ export { _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY, convertAuthorToRole, convertBaseMessagesToContent, convertMessageContentToParts, convertResponseContentToChatGenerationChunk, getMessageAuthor, iife, mapGenerateContentResultToChatResult };
484
638
  //# sourceMappingURL=common.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"common.mjs","sources":["../../../../../src/llm/google/utils/common.ts"],"sourcesContent":["import {\r\n POSSIBLE_ROLES,\r\n type Part,\r\n type Content,\r\n type TextPart,\r\n type FileDataPart,\r\n type InlineDataPart,\r\n type FunctionCallPart,\r\n type GenerateContentCandidate,\r\n type EnhancedGenerateContentResponse,\r\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\r\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\r\n} from '@google/generative-ai';\r\nimport {\r\n AIMessageChunk,\r\n BaseMessage,\r\n ChatMessage,\r\n ToolMessage,\r\n ToolMessageChunk,\r\n MessageContent,\r\n MessageContentComplex,\r\n UsageMetadata,\r\n isAIMessage,\r\n isBaseMessage,\r\n isToolMessage,\r\n StandardContentBlockConverter,\r\n parseBase64DataUrl,\r\n convertToProviderContentBlock,\r\n isDataContentBlock,\r\n} from '@langchain/core/messages';\r\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\r\nimport type { ChatGeneration } from '@langchain/core/outputs';\r\nimport { isLangChainTool } from '@langchain/core/utils/function_calling';\r\nimport { isOpenAITool } from '@langchain/core/language_models/base';\r\nimport { ToolCallChunk } from '@langchain/core/messages/tool';\r\nimport { v4 as uuidv4 } from 'uuid';\r\nimport {\r\n jsonSchemaToGeminiParameters,\r\n schemaToGenerativeAIParameters,\r\n} from './zod_to_genai_parameters';\r\nimport { GoogleGenerativeAIToolType } from '../types';\r\n\r\nexport function getMessageAuthor(message: BaseMessage): string {\r\n const type = message._getType();\r\n if (ChatMessage.isInstance(message)) {\r\n return message.role;\r\n }\r\n if (type === 'tool') {\r\n return type;\r\n }\r\n return message.name ?? type;\r\n}\r\n\r\n/**\r\n * Maps a message type to a Google Generative AI chat author.\r\n * @param message The message to map.\r\n * @param model The model to use for mapping.\r\n * @returns The message type mapped to a Google Generative AI chat author.\r\n */\r\nexport function convertAuthorToRole(\r\n author: string\r\n): (typeof POSSIBLE_ROLES)[number] {\r\n switch (author) {\r\n /**\r\n * Note: Gemini currently is not supporting system messages\r\n * we will convert them to human messages and merge with following\r\n * */\r\n case 'supervisor':\r\n case 'ai':\r\n case 'model': // getMessageAuthor returns message.name. code ex.: return message.name ?? type;\r\n return 'model';\r\n case 'system':\r\n return 'system';\r\n case 'human':\r\n return 'user';\r\n case 'tool':\r\n case 'function':\r\n return 'function';\r\n default:\r\n throw new Error(`Unknown / unsupported author: ${author}`);\r\n }\r\n}\r\n\r\nfunction messageContentMedia(content: MessageContentComplex): Part {\r\n if ('mimeType' in content && 'data' in content) {\r\n return {\r\n inlineData: {\r\n mimeType: content.mimeType,\r\n data: content.data,\r\n },\r\n };\r\n }\r\n if ('mimeType' in content && 'fileUri' in content) {\r\n return {\r\n fileData: {\r\n mimeType: content.mimeType,\r\n fileUri: content.fileUri,\r\n },\r\n };\r\n }\r\n\r\n throw new Error('Invalid media content');\r\n}\r\n\r\nfunction inferToolNameFromPreviousMessages(\r\n message: ToolMessage | ToolMessageChunk,\r\n previousMessages: BaseMessage[]\r\n): string | undefined {\r\n return previousMessages\r\n .map((msg) => {\r\n if (isAIMessage(msg)) {\r\n return msg.tool_calls ?? [];\r\n }\r\n return [];\r\n })\r\n .flat()\r\n .find((toolCall) => {\r\n return toolCall.id === message.tool_call_id;\r\n })?.name;\r\n}\r\n\r\nfunction _getStandardContentBlockConverter(\r\n isMultimodalModel: boolean\r\n): StandardContentBlockConverter<{\r\n text: TextPart;\r\n image: FileDataPart | InlineDataPart;\r\n audio: FileDataPart | InlineDataPart;\r\n file: FileDataPart | InlineDataPart | TextPart;\r\n}> {\r\n const standardContentBlockConverter: StandardContentBlockConverter<{\r\n text: TextPart;\r\n image: FileDataPart | InlineDataPart;\r\n audio: FileDataPart | InlineDataPart;\r\n file: FileDataPart | InlineDataPart | TextPart;\r\n }> = {\r\n providerName: 'Google Gemini',\r\n\r\n fromStandardTextBlock(block) {\r\n return {\r\n text: block.text,\r\n };\r\n },\r\n\r\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\r\n if (!isMultimodalModel) {\r\n throw new Error('This model does not support images');\r\n }\r\n if (block.source_type === 'url') {\r\n const data = parseBase64DataUrl({ dataUrl: block.url });\r\n if (data) {\r\n return {\r\n inlineData: {\r\n mimeType: data.mime_type,\r\n data: data.data,\r\n },\r\n };\r\n } else {\r\n return {\r\n fileData: {\r\n mimeType: block.mime_type ?? '',\r\n fileUri: block.url,\r\n },\r\n };\r\n }\r\n }\r\n\r\n if (block.source_type === 'base64') {\r\n return {\r\n inlineData: {\r\n mimeType: block.mime_type ?? '',\r\n data: block.data,\r\n },\r\n };\r\n }\r\n\r\n throw new Error(`Unsupported source type: ${block.source_type}`);\r\n },\r\n\r\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\r\n if (!isMultimodalModel) {\r\n throw new Error('This model does not support audio');\r\n }\r\n if (block.source_type === 'url') {\r\n const data = parseBase64DataUrl({ dataUrl: block.url });\r\n if (data) {\r\n return {\r\n inlineData: {\r\n mimeType: data.mime_type,\r\n data: data.data,\r\n },\r\n };\r\n } else {\r\n return {\r\n fileData: {\r\n mimeType: block.mime_type ?? '',\r\n fileUri: block.url,\r\n },\r\n };\r\n }\r\n }\r\n\r\n if (block.source_type === 'base64') {\r\n return {\r\n inlineData: {\r\n mimeType: block.mime_type ?? '',\r\n data: block.data,\r\n },\r\n };\r\n }\r\n\r\n throw new Error(`Unsupported source type: ${block.source_type}`);\r\n },\r\n\r\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\r\n if (!isMultimodalModel) {\r\n throw new Error('This model does not support files');\r\n }\r\n if (block.source_type === 'text') {\r\n return {\r\n text: block.text,\r\n };\r\n }\r\n if (block.source_type === 'url') {\r\n const data = parseBase64DataUrl({ dataUrl: block.url });\r\n if (data) {\r\n return {\r\n inlineData: {\r\n mimeType: data.mime_type,\r\n data: data.data,\r\n },\r\n };\r\n } else {\r\n return {\r\n fileData: {\r\n mimeType: block.mime_type ?? '',\r\n fileUri: block.url,\r\n },\r\n };\r\n }\r\n }\r\n\r\n if (block.source_type === 'base64') {\r\n return {\r\n inlineData: {\r\n mimeType: block.mime_type ?? '',\r\n data: block.data,\r\n },\r\n };\r\n }\r\n throw new Error(`Unsupported source type: ${block.source_type}`);\r\n },\r\n };\r\n return standardContentBlockConverter;\r\n}\r\n\r\nfunction _convertLangChainContentToPart(\r\n content: MessageContentComplex,\r\n isMultimodalModel: boolean\r\n): Part | undefined {\r\n if (isDataContentBlock(content)) {\r\n return convertToProviderContentBlock(\r\n content,\r\n _getStandardContentBlockConverter(isMultimodalModel)\r\n );\r\n }\r\n\r\n if (content.type === 'text') {\r\n return { text: content.text };\r\n } else if (content.type === 'executableCode') {\r\n return { executableCode: content.executableCode };\r\n } else if (content.type === 'codeExecutionResult') {\r\n return { codeExecutionResult: content.codeExecutionResult };\r\n } else if (content.type === 'image_url') {\r\n if (!isMultimodalModel) {\r\n throw new Error('This model does not support images');\r\n }\r\n let source: string;\r\n if (typeof content.image_url === 'string') {\r\n source = content.image_url;\r\n } else if (\r\n typeof content.image_url === 'object' &&\r\n 'url' in content.image_url\r\n ) {\r\n source = content.image_url.url;\r\n } else {\r\n throw new Error('Please provide image as base64 encoded data URL');\r\n }\r\n const [dm, data] = source.split(',');\r\n if (!dm.startsWith('data:')) {\r\n throw new Error('Please provide image as base64 encoded data URL');\r\n }\r\n\r\n const [mimeType, encoding] = dm.replace(/^data:/, '').split(';');\r\n if (encoding !== 'base64') {\r\n throw new Error('Please provide image as base64 encoded data URL');\r\n }\r\n\r\n return {\r\n inlineData: {\r\n data,\r\n mimeType,\r\n },\r\n };\r\n } else if (\r\n content.type === 'document' ||\r\n content.type === 'audio' ||\r\n content.type === 'video'\r\n ) {\r\n if (!isMultimodalModel) {\r\n throw new Error(`This model does not support ${content.type}s`);\r\n }\r\n return {\r\n inlineData: {\r\n data: content.data,\r\n mimeType: content.mimeType,\r\n },\r\n };\r\n } else if (content.type === 'media') {\r\n return messageContentMedia(content);\r\n } else if (content.type === 'tool_use') {\r\n return {\r\n functionCall: {\r\n name: content.name,\r\n args: content.input,\r\n },\r\n };\r\n } else if (\r\n content.type?.includes('/') === true &&\r\n // Ensure it's a single slash.\r\n content.type.split('/').length === 2 &&\r\n 'data' in content &&\r\n typeof content.data === 'string'\r\n ) {\r\n return {\r\n inlineData: {\r\n mimeType: content.type,\r\n data: content.data,\r\n },\r\n };\r\n } else if ('functionCall' in content) {\r\n // No action needed here — function calls will be added later from message.tool_calls\r\n return undefined;\r\n } else {\r\n if ('type' in content) {\r\n throw new Error(`Unknown content type ${content.type}`);\r\n } else {\r\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\r\n }\r\n }\r\n}\r\n\r\nexport function convertMessageContentToParts(\r\n message: BaseMessage,\r\n isMultimodalModel: boolean,\r\n previousMessages: BaseMessage[]\r\n): Part[] {\r\n if (isToolMessage(message)) {\r\n const messageName =\r\n message.name ??\r\n inferToolNameFromPreviousMessages(message, previousMessages);\r\n if (messageName === undefined) {\r\n throw new Error(\r\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\r\n );\r\n }\r\n\r\n const result = Array.isArray(message.content)\r\n ? (message.content\r\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\r\n .filter((p) => p !== undefined) as Part[])\r\n : message.content;\r\n\r\n if (message.status === 'error') {\r\n return [\r\n {\r\n functionResponse: {\r\n name: messageName,\r\n // The API expects an object with an `error` field if the function call fails.\r\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\r\n response: { error: { details: result } },\r\n },\r\n },\r\n ];\r\n }\r\n\r\n return [\r\n {\r\n functionResponse: {\r\n name: messageName,\r\n // again, can't have a string or array value for `response`, so we wrap it as an object here\r\n response: { result },\r\n },\r\n },\r\n ];\r\n }\r\n\r\n let functionCalls: FunctionCallPart[] = [];\r\n const messageParts: Part[] = [];\r\n\r\n if (typeof message.content === 'string' && message.content) {\r\n messageParts.push({ text: message.content });\r\n }\r\n\r\n if (Array.isArray(message.content)) {\r\n messageParts.push(\r\n ...(message.content\r\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\r\n .filter((p) => p !== undefined) as Part[])\r\n );\r\n }\r\n\r\n if (isAIMessage(message) && message.tool_calls?.length != null) {\r\n functionCalls = message.tool_calls.map((tc) => {\r\n return {\r\n functionCall: {\r\n name: tc.name,\r\n args: tc.args,\r\n },\r\n };\r\n });\r\n }\r\n\r\n return [...messageParts, ...functionCalls];\r\n}\r\n\r\nexport function convertBaseMessagesToContent(\r\n messages: BaseMessage[],\r\n isMultimodalModel: boolean,\r\n convertSystemMessageToHumanContent: boolean = false\r\n): Content[] | undefined {\r\n return messages.reduce<{\r\n content: Content[] | undefined;\r\n mergeWithPreviousContent: boolean;\r\n }>(\r\n (acc, message, index) => {\r\n if (!isBaseMessage(message)) {\r\n throw new Error('Unsupported message input');\r\n }\r\n const author = getMessageAuthor(message);\r\n if (author === 'system' && index !== 0) {\r\n throw new Error('System message should be the first one');\r\n }\r\n const role = convertAuthorToRole(author);\r\n\r\n const prevContent = acc.content?.[acc.content.length];\r\n if (\r\n !acc.mergeWithPreviousContent &&\r\n prevContent &&\r\n prevContent.role === role\r\n ) {\r\n throw new Error(\r\n 'Google Generative AI requires alternate messages between authors'\r\n );\r\n }\r\n\r\n const parts = convertMessageContentToParts(\r\n message,\r\n isMultimodalModel,\r\n messages.slice(0, index)\r\n );\r\n\r\n if (acc.mergeWithPreviousContent) {\r\n const prevContent = acc.content?.[acc.content.length - 1];\r\n if (!prevContent) {\r\n throw new Error(\r\n 'There was a problem parsing your system message. Please try a prompt without one.'\r\n );\r\n }\r\n prevContent.parts.push(...parts);\r\n\r\n return {\r\n mergeWithPreviousContent: false,\r\n content: acc.content,\r\n };\r\n }\r\n let actualRole = role;\r\n if (\r\n actualRole === 'function' ||\r\n (actualRole === 'system' && !convertSystemMessageToHumanContent)\r\n ) {\r\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\r\n actualRole = 'user';\r\n }\r\n const content: Content = {\r\n role: actualRole,\r\n parts,\r\n };\r\n return {\r\n mergeWithPreviousContent:\r\n author === 'system' && !convertSystemMessageToHumanContent,\r\n content: [...(acc.content ?? []), content],\r\n };\r\n },\r\n { content: [], mergeWithPreviousContent: false }\r\n ).content;\r\n}\r\n\r\nexport function convertResponseContentToChatGenerationChunk(\r\n response: EnhancedGenerateContentResponse,\r\n extra: {\r\n usageMetadata?: UsageMetadata | undefined;\r\n index: number;\r\n }\r\n): ChatGenerationChunk | null {\r\n if (!response.candidates || response.candidates.length === 0) {\r\n return null;\r\n }\r\n const functionCalls = response.functionCalls();\r\n const [candidate] = response.candidates as [\r\n Partial<GenerateContentCandidate> | undefined,\r\n ];\r\n const { content: candidateContent, ...generationInfo } = candidate ?? {};\r\n let content: MessageContent | undefined;\r\n // Checks if some parts do not have text. If false, it means that the content is a string.\r\n const reasoningParts: string[] = [];\r\n if (\r\n candidateContent != null &&\r\n Array.isArray(candidateContent.parts) &&\r\n candidateContent.parts.every((p) => 'text' in p)\r\n ) {\r\n // content = candidateContent.parts.map((p) => p.text).join('');\r\n const textParts: string[] = [];\r\n for (const part of candidateContent.parts) {\r\n if ('thought' in part && part.thought === true) {\r\n reasoningParts.push(part.text ?? '');\r\n continue;\r\n }\r\n textParts.push(part.text ?? '');\r\n }\r\n content = textParts.join('');\r\n } else if (candidateContent && Array.isArray(candidateContent.parts)) {\r\n content = candidateContent.parts.map((p) => {\r\n if ('text' in p && 'thought' in p && p.thought === true) {\r\n reasoningParts.push(p.text ?? '');\r\n } else if ('text' in p) {\r\n return {\r\n type: 'text',\r\n text: p.text,\r\n };\r\n } else if ('executableCode' in p) {\r\n return {\r\n type: 'executableCode',\r\n executableCode: p.executableCode,\r\n };\r\n } else if ('codeExecutionResult' in p) {\r\n return {\r\n type: 'codeExecutionResult',\r\n codeExecutionResult: p.codeExecutionResult,\r\n };\r\n }\r\n return p;\r\n });\r\n } else {\r\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\r\n content = [];\r\n }\r\n\r\n let text = '';\r\n if (typeof content === 'string' && content) {\r\n text = content;\r\n } else if (Array.isArray(content)) {\r\n const block = content.find((b) => 'text' in b) as\r\n | { text: string }\r\n | undefined;\r\n text = block?.text ?? '';\r\n }\r\n\r\n const toolCallChunks: ToolCallChunk[] = [];\r\n if (functionCalls) {\r\n toolCallChunks.push(\r\n ...functionCalls.map((fc) => ({\r\n ...fc,\r\n args: JSON.stringify(fc.args),\r\n // Un-commenting this causes LangChain to incorrectly merge tool calls together\r\n // index: extra.index,\r\n type: 'tool_call_chunk' as const,\r\n id: 'id' in fc && typeof fc.id === 'string' ? fc.id : uuidv4(),\r\n }))\r\n );\r\n }\r\n\r\n const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {};\r\n if (reasoningParts.length > 0) {\r\n additional_kwargs.reasoning = reasoningParts.join('');\r\n }\r\n\r\n if (candidate?.groundingMetadata) {\r\n additional_kwargs.groundingMetadata = candidate.groundingMetadata;\r\n }\r\n\r\n const isFinalChunk =\r\n response.candidates[0]?.finishReason === 'STOP' ||\r\n response.candidates[0]?.finishReason === 'MAX_TOKENS' ||\r\n response.candidates[0]?.finishReason === 'SAFETY';\r\n\r\n return new ChatGenerationChunk({\r\n text,\r\n message: new AIMessageChunk({\r\n content: content,\r\n name: !candidateContent ? undefined : candidateContent.role,\r\n tool_call_chunks: toolCallChunks,\r\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\r\n // so leave blank for now.\r\n additional_kwargs,\r\n usage_metadata: isFinalChunk ? extra.usageMetadata : undefined,\r\n }),\r\n generationInfo,\r\n });\r\n}\r\n\r\nexport function convertToGenerativeAITools(\r\n tools: GoogleGenerativeAIToolType[]\r\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\r\n if (\r\n tools.every(\r\n (tool) =>\r\n 'functionDeclarations' in tool &&\r\n Array.isArray(tool.functionDeclarations)\r\n )\r\n ) {\r\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\r\n }\r\n return [\r\n {\r\n functionDeclarations: tools.map(\r\n (tool): GenerativeAIFunctionDeclaration => {\r\n if (isLangChainTool(tool)) {\r\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\r\n if (\r\n jsonSchema.type === 'object' &&\r\n 'properties' in jsonSchema &&\r\n Object.keys(jsonSchema.properties).length === 0\r\n ) {\r\n return {\r\n name: tool.name,\r\n description: tool.description,\r\n };\r\n }\r\n return {\r\n name: tool.name,\r\n description: tool.description,\r\n parameters: jsonSchema,\r\n };\r\n }\r\n if (isOpenAITool(tool)) {\r\n return {\r\n name: tool.function.name,\r\n description:\r\n tool.function.description ?? 'A function available to call.',\r\n parameters: jsonSchemaToGeminiParameters(\r\n tool.function.parameters\r\n ),\r\n };\r\n }\r\n return tool as unknown as GenerativeAIFunctionDeclaration;\r\n }\r\n ),\r\n },\r\n ];\r\n}\r\n"],"names":["uuidv4"],"mappings":";;;;;;;;AA0CM,SAAU,gBAAgB,CAAC,OAAoB,EAAA;AACnD,IAAA,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE;AAC/B,IAAA,IAAI,WAAW,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;QACnC,OAAO,OAAO,CAAC,IAAI;;AAErB,IAAA,IAAI,IAAI,KAAK,MAAM,EAAE;AACnB,QAAA,OAAO,IAAI;;AAEb,IAAA,OAAO,OAAO,CAAC,IAAI,IAAI,IAAI;AAC7B;AAEA;;;;;AAKG;AACG,SAAU,mBAAmB,CACjC,MAAc,EAAA;IAEd,QAAQ,MAAM;AACd;;;AAGO;AACP,QAAA,KAAK,YAAY;AACjB,QAAA,KAAK,IAAI;QACT,KAAK,OAAO;AACV,YAAA,OAAO,OAAO;AAChB,QAAA,KAAK,QAAQ;AACX,YAAA,OAAO,QAAQ;AACjB,QAAA,KAAK,OAAO;AACV,YAAA,OAAO,MAAM;AAC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AK,YAAY;QACrD,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,YAAY,KAAK,QAAQ;IAEnD,OAAO,IAAI,mBAAmB,CAAC;QAC7B,IAAI;QACJ,OAAO,EAAE,IAAI,cAAc,CAAC;AAC1B,YAAA,OAAO,EAAE,OAAO;AAChB,YAAA,IAAI,EAAE,CAAC,gBAAgB,GAAG,SAAS,GAAG,gBAAgB,CAAC,IAAI;AAC3D,YAAA,gBAAgB,EAAE,cAAc;;;YAGhC,iBAAiB;YACjB,cAAc,EAAE,YAAY,GAAG,KAAK,CAAC,aAAa,GAAG,SAAS;SAC/D,CAAC;QACF,cAAc;AACf,KAAA,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"common.mjs","sources":["../../../../../src/llm/google/utils/common.ts"],"sourcesContent":["import {\n POSSIBLE_ROLES,\n type Part,\n type Content,\n type TextPart,\n type FileDataPart,\n type InlineDataPart,\n type FunctionCallPart,\n type GenerateContentCandidate,\n type EnhancedGenerateContentResponse,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n} from '@google/generative-ai';\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { ChatGeneration, ChatResult } from '@langchain/core/outputs';\nimport { isLangChainTool } from '@langchain/core/utils/function_calling';\nimport { isOpenAITool } from '@langchain/core/language_models/base';\nimport { ToolCallChunk } from '@langchain/core/messages/tool';\nimport { v4 as uuidv4 } from 'uuid';\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from './zod_to_genai_parameters';\nimport { GoogleGenerativeAIToolType } from '../types';\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n '__gemini_function_call_thought_signatures__';\n\nconst DUMMY_SIGNATURE =\n 'ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==';\n\n/**\n * Executes a function immediately and returns its result.\n * Functional utility similar to an Immediately Invoked Function Expression (IIFE).\n * @param fn The function to execute.\n * @returns The result of invoking fn.\n */\nexport const iife = <T>(fn: () => T): T => fn();\n\nexport function getMessageAuthor(message: BaseMessage): string {\n const type = message._getType();\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n if (type === 'tool') {\n return type;\n }\n return message.name ?? type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case 'supervisor':\n case 'ai':\n case 'model': // getMessageAuthor returns message.name. code ex.: return message.name ?? type;\n return 'model';\n case 'system':\n return 'system';\n case 'human':\n return 'user';\n case 'tool':\n case 'function':\n return 'function';\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if ('mimeType' in content && 'data' in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if ('mimeType' in content && 'fileUri' in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error('Invalid media content');\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(\n isMultimodalModel: boolean\n): StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n}> {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: 'Google Gemini',\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support images');\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support audio');\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support files');\n }\n if (block.source_type === 'text') {\n return {\n text: block.text,\n };\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (content.type === 'text') {\n return { text: content.text };\n } else if (content.type === 'executableCode') {\n return { executableCode: content.executableCode };\n } else if (content.type === 'codeExecutionResult') {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === 'image_url') {\n if (!isMultimodalModel) {\n throw new Error('This model does not support images');\n }\n let source: string;\n if (typeof content.image_url === 'string') {\n source = content.image_url;\n } else if (\n typeof content.image_url === 'object' &&\n 'url' in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n const [dm, data] = source.split(',');\n if (!dm.startsWith('data:')) {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, '').split(';');\n if (encoding !== 'base64') {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === 'media') {\n return messageContentMedia(content);\n } else if (content.type === 'tool_use') {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (\n content.type?.includes('/') === true &&\n // Ensure it's a single slash.\n content.type.split('/').length === 2 &&\n 'data' in content &&\n typeof content.data === 'string'\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if ('functionCall' in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if ('type' in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === 'error') {\n return [\n {\n functionResponse: {\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n },\n },\n ];\n }\n\n return [\n {\n functionResponse: {\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n },\n },\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === 'string' && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = (\n message.additional_kwargs as BaseMessage['additional_kwargs'] | undefined\n )?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] as\n | Record<string, string>\n | undefined;\n\n if (isAIMessage(message) && (message.tool_calls?.length ?? 0) > 0) {\n functionCalls = (message.tool_calls ?? []).map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id != null && tc.id !== '') {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature != null && signature !== '') {\n return signature;\n }\n }\n if (model?.includes('gemini-3') === true) {\n return DUMMY_SIGNATURE;\n }\n return '';\n });\n\n return {\n functionCall: {\n name: tc.name,\n args: tc.args,\n },\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n\n model?: string\n): Content[] | undefined {\n return messages.reduce<{\n content: Content[] | undefined;\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error('Unsupported message input');\n }\n const author = getMessageAuthor(message);\n if (author === 'system' && index !== 0) {\n throw new Error('System message should be the first one');\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content?.[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n 'Google Generative AI requires alternate messages between authors'\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content?.[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n 'There was a problem parsing your system message. Please try a prompt without one.'\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === 'function' ||\n (actualRole === 'system' && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = 'user';\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === 'system' && !convertSystemMessageToHumanContent,\n content: [...(acc.content ?? []), content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates as [\n Partial<GenerateContentCandidate> | undefined,\n ];\n const { content: candidateContent, ...generationInfo } = candidate ?? {};\n\n // Extract function calls directly from parts to preserve thoughtSignature\n const functionCalls =\n (candidateContent?.parts as Part[] | undefined)?.reduce(\n (acc, p) => {\n if ('functionCall' in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n 'id' in p.functionCall && typeof p.functionCall.id === 'string'\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (\n | undefined\n | (FunctionCallPart & { id: string; thoughtSignature?: string })\n )[]\n ) ?? [];\n\n let content: MessageContent | undefined;\n // Checks if some parts do not have text. If false, it means that the content is a string.\n const reasoningParts: string[] = [];\n if (\n candidateContent != null &&\n Array.isArray(candidateContent.parts) &&\n candidateContent.parts.every((p) => 'text' in p)\n ) {\n // content = candidateContent.parts.map((p) => p.text).join('');\n const textParts: string[] = [];\n for (const part of candidateContent.parts) {\n if ('thought' in part && part.thought === true) {\n reasoningParts.push(part.text ?? '');\n continue;\n }\n textParts.push(part.text ?? '');\n }\n content = textParts.join('');\n } else if (candidateContent && Array.isArray(candidateContent.parts)) {\n content = candidateContent.parts\n .map((p) => {\n if ('text' in p && 'thought' in p && p.thought === true) {\n reasoningParts.push(p.text ?? '');\n return undefined;\n } else if ('text' in p) {\n return {\n type: 'text',\n text: p.text,\n };\n } else if ('executableCode' in p) {\n return {\n type: 'executableCode',\n executableCode: p.executableCode,\n };\n } else if ('codeExecutionResult' in p) {\n return {\n type: 'codeExecutionResult',\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n })\n .filter((p) => p !== undefined);\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = '';\n if (typeof content === 'string' && content) {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => 'text' in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? '';\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls.length > 0) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: 'tool_call_chunk' as const,\n id: fc?.id,\n name: fc?.functionCall.name,\n args: JSON.stringify(fc?.functionCall.args),\n }))\n );\n }\n\n // Extract thought signatures from function calls for Gemini 3+\n const functionThoughtSignatures = functionCalls.reduce(\n (acc, fc) => {\n if (\n fc &&\n 'thoughtSignature' in fc &&\n typeof fc.thoughtSignature === 'string'\n ) {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n };\n\n if (reasoningParts.length > 0) {\n additional_kwargs.reasoning = reasoningParts.join('');\n }\n\n if (candidate?.groundingMetadata) {\n additional_kwargs.groundingMetadata = candidate.groundingMetadata;\n }\n\n const isFinalChunk =\n response.candidates[0]?.finishReason === 'STOP' ||\n response.candidates[0]?.finishReason === 'MAX_TOKENS' ||\n response.candidates[0]?.finishReason === 'SAFETY';\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content,\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs,\n usage_metadata: isFinalChunk ? extra.usageMetadata : undefined,\n }),\n generationInfo,\n });\n}\n\n/**\n * Maps a Google GenerateContentResult to a LangChain ChatResult\n */\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n if (\n !response.candidates ||\n response.candidates.length === 0 ||\n !response.candidates[0]\n ) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates as [\n Partial<GenerateContentCandidate> | undefined,\n ];\n const { content: candidateContent, ...generationInfo } = candidate ?? {};\n\n // Extract function calls directly from parts to preserve thoughtSignature\n const functionCalls =\n candidateContent?.parts.reduce(\n (acc, p) => {\n if ('functionCall' in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n 'id' in p.functionCall && typeof p.functionCall.id === 'string'\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string; thoughtSignature?: string })[]\n ) ?? [];\n\n let content: MessageContent | undefined;\n const reasoningParts: string[] = [];\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length === 1 &&\n candidateContent.parts[0].text &&\n !(\n 'thought' in candidateContent.parts[0] &&\n candidateContent.parts[0].thought === true\n )\n ) {\n content = candidateContent.parts[0].text;\n } else if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length > 0\n ) {\n content = candidateContent.parts\n .map((p) => {\n if ('text' in p && 'thought' in p && p.thought === true) {\n reasoningParts.push(p.text ?? '');\n return undefined;\n } else if ('text' in p) {\n return {\n type: 'text',\n text: p.text,\n };\n } else if ('executableCode' in p) {\n return {\n type: 'executableCode',\n executableCode: p.executableCode,\n };\n } else if ('codeExecutionResult' in p) {\n return {\n type: 'codeExecutionResult',\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n })\n .filter((p) => p !== undefined);\n } else {\n content = [];\n }\n let text = '';\n if (typeof content === 'string') {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => 'text' in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {\n ...generationInfo,\n };\n if (reasoningParts.length > 0) {\n additional_kwargs.reasoning = reasoningParts.join('');\n }\n\n // Extract thought signatures from function calls for Gemini 3+\n const functionThoughtSignatures = functionCalls.reduce(\n (acc, fc) => {\n if ('thoughtSignature' in fc && typeof fc.thoughtSignature === 'string') {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n const tool_calls = functionCalls.map((fc) => ({\n type: 'tool_call' as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n }));\n\n // Store thought signatures map for later retrieval\n additional_kwargs[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] =\n functionThoughtSignatures;\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content: content ?? '',\n tool_calls,\n additional_kwargs,\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n 'functionDeclarations' in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === 'object' &&\n 'properties' in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? 'A function available to call.',\n parameters: jsonSchemaToGeminiParameters(\n tool.function.parameters\n ),\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n"],"names":["uuidv4"],"mappings":";;;;;;;;AA2CO,MAAM,yCAAyC,GACpD;AAEF,MAAM,eAAe,GACnB,saAAsa;AAExa;;;;;AAKG;AACU,MAAA,IAAI,GAAG,CAAI,EAAW,KAAQ,EAAE;AAEvC,SAAU,gBAAgB,CAAC,OAAoB,EAAA;AACnD,IAAA,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE;AAC/B,IAAA,IAAI,WAAW,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;QACnC,OAAO,OAAO,CAAC,IAAI;;AAErB,IAAA,IAAI,IAAI,KAAK,MAAM,EAAE;AACnB,QAAA,OAAO,IAAI;;AAEb,IAAA,OAAO,OAAO,CAAC,IAAI,IAAI,IAAI;AAC7B;AAEA;;;;;AAKG;AACG,SAAU,mBAAmB,CACjC,MAAc,EAAA;IAEd,QAAQ,MAAM;AACd;;;AAGO;AACP,QAAA,KAAK,YAAY;AACjB,QAAA,KAAK,IAAI;QACT,KAAK,OAAO;AACV,YAAA,OAAO,OAAO;AAChB,QAAA,KAAK,QAAQ;AACX,YAAA,OAAO,QAAQ;AACjB,QAAA,KAAK,OAAO;AACV,YAAA,OAAO,MAAM;AACf,QAAA,KAAK,MAAM;AACX,QAAA,KAAK,UAAU;AACb,YAAA,OAAO,UAAU;AACnB,QAAA;AACE,YAAA,M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AmB;QACjC,IAAI;QACJ,OAAO,EAAE,IAAI,SAAS,CAAC;YACrB,OAAO,EAAE,OAAO,IAAI,EAAE;YACtB,UAAU;YACV,iBAAiB;YACjB,cAAc,EAAE,KAAK,EAAE,aAAa;SACrC,CAAC;QACF,cAAc;KACf;IACD,OAAO;QACL,WAAW,EAAE,CAAC,UAAU,CAAC;AACzB,QAAA,SAAS,EAAE;AACT,YAAA,UAAU,EAAE;AACV,gBAAA,YAAY,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY;AAChD,gBAAA,gBAAgB,EAAE,KAAK,EAAE,aAAa,EAAE,aAAa;AACrD,gBAAA,WAAW,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY;AAChD,aAAA;AACF,SAAA;KACF;AACH;;;;"}
@@ -605,9 +605,15 @@ function shiftIndexTokenCountMap(indexTokenCountMap, instructionsTokenCount) {
605
605
  }
606
606
  /**
607
607
  * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.
608
- * Converts AI messages with tool calls (that lack thinking blocks) into buffer strings,
608
+ * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,
609
609
  * avoiding the thinking block signature requirement.
610
610
  *
611
+ * Recognizes the following as valid thinking/reasoning blocks:
612
+ * - ContentTypes.THINKING (Anthropic)
613
+ * - ContentTypes.REASONING_CONTENT (Bedrock)
614
+ * - ContentTypes.REASONING (VertexAI / Google)
615
+ * - 'redacted_thinking'
616
+ *
611
617
  * @param messages - Array of messages to process
612
618
  * @param provider - The provider being used (unused but kept for future compatibility)
613
619
  * @returns The messages array with tool sequences converted to buffer strings if necessary
@@ -639,6 +645,8 @@ function ensureThinkingBlockInMessages(messages, _provider) {
639
645
  // If message has tool use but no thinking block, convert to buffer string
640
646
  if (hasToolUse &&
641
647
  firstContentType !== ContentTypes.THINKING &&
648
+ firstContentType !== ContentTypes.REASONING_CONTENT &&
649
+ firstContentType !== ContentTypes.REASONING &&
642
650
  firstContentType !== 'redacted_thinking') {
643
651
  // Collect the AI message and any following tool messages
644
652
  const toolSequence = [msg];