@illuma-ai/agents 1.1.20 → 1.1.22

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 (246) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/llm/bedrock/index.cjs +14 -0
  6. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  7. package/dist/cjs/run.cjs +20 -9
  8. package/dist/cjs/run.cjs.map +1 -1
  9. package/dist/esm/graphs/Graph.mjs +12 -1
  10. package/dist/esm/graphs/Graph.mjs.map +1 -1
  11. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  12. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  13. package/dist/esm/llm/bedrock/index.mjs +14 -0
  14. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  15. package/dist/esm/run.mjs +20 -9
  16. package/dist/esm/run.mjs.map +1 -1
  17. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  18. package/package.json +1 -1
  19. package/src/graphs/Graph.ts +12 -1
  20. package/src/graphs/MultiAgentGraph.ts +105 -1
  21. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  22. package/src/llm/bedrock/index.ts +17 -0
  23. package/src/run.ts +20 -11
  24. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  25. package/src/agents/AgentContext.js +0 -782
  26. package/src/agents/AgentContext.test.js +0 -421
  27. package/src/agents/__tests__/AgentContext.test.js +0 -678
  28. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  29. package/src/common/enum.js +0 -192
  30. package/src/common/index.js +0 -3
  31. package/src/events.js +0 -166
  32. package/src/graphs/Graph.js +0 -1857
  33. package/src/graphs/MultiAgentGraph.js +0 -1092
  34. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  35. package/src/graphs/__tests__/structured-output.test.js +0 -144
  36. package/src/graphs/contextManagement.e2e.test.js +0 -718
  37. package/src/graphs/contextManagement.test.js +0 -485
  38. package/src/graphs/handoffValidation.test.js +0 -276
  39. package/src/graphs/index.js +0 -3
  40. package/src/index.js +0 -28
  41. package/src/instrumentation.js +0 -21
  42. package/src/llm/anthropic/index.js +0 -319
  43. package/src/llm/anthropic/types.js +0 -46
  44. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  45. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  46. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  47. package/src/llm/anthropic/utils/tools.js +0 -25
  48. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  49. package/src/llm/bedrock/index.js +0 -303
  50. package/src/llm/bedrock/types.js +0 -2
  51. package/src/llm/bedrock/utils/index.js +0 -6
  52. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  53. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  54. package/src/llm/fake.js +0 -92
  55. package/src/llm/google/index.js +0 -215
  56. package/src/llm/google/types.js +0 -12
  57. package/src/llm/google/utils/common.js +0 -670
  58. package/src/llm/google/utils/tools.js +0 -111
  59. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  60. package/src/llm/openai/index.js +0 -1033
  61. package/src/llm/openai/types.js +0 -2
  62. package/src/llm/openai/utils/index.js +0 -756
  63. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  64. package/src/llm/openrouter/index.js +0 -261
  65. package/src/llm/openrouter/reasoning.test.js +0 -181
  66. package/src/llm/providers.js +0 -36
  67. package/src/llm/text.js +0 -65
  68. package/src/llm/vertexai/index.js +0 -402
  69. package/src/messages/__tests__/tools.test.js +0 -392
  70. package/src/messages/cache.js +0 -404
  71. package/src/messages/cache.test.js +0 -1167
  72. package/src/messages/content.js +0 -48
  73. package/src/messages/content.test.js +0 -314
  74. package/src/messages/core.js +0 -359
  75. package/src/messages/ensureThinkingBlock.test.js +0 -997
  76. package/src/messages/format.js +0 -973
  77. package/src/messages/formatAgentMessages.test.js +0 -2278
  78. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  79. package/src/messages/formatMessage.test.js +0 -608
  80. package/src/messages/ids.js +0 -18
  81. package/src/messages/index.js +0 -9
  82. package/src/messages/labelContentByAgent.test.js +0 -725
  83. package/src/messages/prune.js +0 -438
  84. package/src/messages/reducer.js +0 -60
  85. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  86. package/src/messages/summarize.js +0 -146
  87. package/src/messages/summarize.test.js +0 -332
  88. package/src/messages/tools.js +0 -90
  89. package/src/mockStream.js +0 -81
  90. package/src/prompts/collab.js +0 -7
  91. package/src/prompts/index.js +0 -3
  92. package/src/prompts/taskmanager.js +0 -58
  93. package/src/run.js +0 -427
  94. package/src/schemas/index.js +0 -3
  95. package/src/schemas/schema-preparation.test.js +0 -370
  96. package/src/schemas/validate.js +0 -314
  97. package/src/schemas/validate.test.js +0 -264
  98. package/src/scripts/abort.js +0 -127
  99. package/src/scripts/ant_web_search.js +0 -130
  100. package/src/scripts/ant_web_search_edge_case.js +0 -133
  101. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  102. package/src/scripts/args.js +0 -41
  103. package/src/scripts/bedrock-cache-debug.js +0 -186
  104. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  105. package/src/scripts/bedrock-merge-test.js +0 -80
  106. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  107. package/src/scripts/caching.js +0 -106
  108. package/src/scripts/cli.js +0 -152
  109. package/src/scripts/cli2.js +0 -119
  110. package/src/scripts/cli3.js +0 -163
  111. package/src/scripts/cli4.js +0 -165
  112. package/src/scripts/cli5.js +0 -165
  113. package/src/scripts/code_exec.js +0 -171
  114. package/src/scripts/code_exec_files.js +0 -180
  115. package/src/scripts/code_exec_multi_session.js +0 -185
  116. package/src/scripts/code_exec_ptc.js +0 -265
  117. package/src/scripts/code_exec_session.js +0 -217
  118. package/src/scripts/code_exec_simple.js +0 -120
  119. package/src/scripts/content.js +0 -111
  120. package/src/scripts/empty_input.js +0 -125
  121. package/src/scripts/handoff-test.js +0 -96
  122. package/src/scripts/image.js +0 -138
  123. package/src/scripts/memory.js +0 -83
  124. package/src/scripts/multi-agent-chain.js +0 -271
  125. package/src/scripts/multi-agent-conditional.js +0 -185
  126. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  127. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  128. package/src/scripts/multi-agent-parallel-start.js +0 -214
  129. package/src/scripts/multi-agent-parallel.js +0 -346
  130. package/src/scripts/multi-agent-sequence.js +0 -184
  131. package/src/scripts/multi-agent-supervisor.js +0 -324
  132. package/src/scripts/multi-agent-test.js +0 -147
  133. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  134. package/src/scripts/parallel-full-metadata-test.js +0 -176
  135. package/src/scripts/parallel-tools-test.js +0 -256
  136. package/src/scripts/programmatic_exec.js +0 -277
  137. package/src/scripts/programmatic_exec_agent.js +0 -168
  138. package/src/scripts/search.js +0 -118
  139. package/src/scripts/sequential-full-metadata-test.js +0 -143
  140. package/src/scripts/simple.js +0 -174
  141. package/src/scripts/single-agent-metadata-test.js +0 -152
  142. package/src/scripts/stream.js +0 -113
  143. package/src/scripts/test-custom-prompt-key.js +0 -132
  144. package/src/scripts/test-handoff-input.js +0 -143
  145. package/src/scripts/test-handoff-preamble.js +0 -227
  146. package/src/scripts/test-handoff-steering.js +0 -353
  147. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  148. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  149. package/src/scripts/test-parallel-handoffs.js +0 -229
  150. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  151. package/src/scripts/test-thinking-handoff.js +0 -132
  152. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  153. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  154. package/src/scripts/test-tools-before-handoff.js +0 -187
  155. package/src/scripts/test_code_api.js +0 -263
  156. package/src/scripts/thinking-bedrock.js +0 -128
  157. package/src/scripts/thinking-vertexai.js +0 -130
  158. package/src/scripts/thinking.js +0 -134
  159. package/src/scripts/tool_search.js +0 -114
  160. package/src/scripts/tools.js +0 -125
  161. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  162. package/src/specs/agent-handoffs.test.js +0 -924
  163. package/src/specs/anthropic.simple.test.js +0 -287
  164. package/src/specs/azure.simple.test.js +0 -381
  165. package/src/specs/cache.simple.test.js +0 -282
  166. package/src/specs/custom-event-await.test.js +0 -148
  167. package/src/specs/deepseek.simple.test.js +0 -189
  168. package/src/specs/emergency-prune.test.js +0 -308
  169. package/src/specs/moonshot.simple.test.js +0 -237
  170. package/src/specs/observability.integration.test.js +0 -1337
  171. package/src/specs/openai.simple.test.js +0 -233
  172. package/src/specs/openrouter.simple.test.js +0 -202
  173. package/src/specs/prune.test.js +0 -733
  174. package/src/specs/reasoning.test.js +0 -144
  175. package/src/specs/spec.utils.js +0 -4
  176. package/src/specs/thinking-handoff.test.js +0 -486
  177. package/src/specs/thinking-prune.test.js +0 -600
  178. package/src/specs/token-distribution-edge-case.test.js +0 -246
  179. package/src/specs/token-memoization.test.js +0 -32
  180. package/src/specs/tokens.test.js +0 -49
  181. package/src/specs/tool-error.test.js +0 -139
  182. package/src/splitStream.js +0 -204
  183. package/src/splitStream.test.js +0 -504
  184. package/src/stream.js +0 -650
  185. package/src/stream.test.js +0 -225
  186. package/src/test/mockTools.js +0 -340
  187. package/src/tools/BrowserTools.js +0 -245
  188. package/src/tools/Calculator.js +0 -38
  189. package/src/tools/Calculator.test.js +0 -225
  190. package/src/tools/CodeExecutor.js +0 -233
  191. package/src/tools/ProgrammaticToolCalling.js +0 -602
  192. package/src/tools/StreamingToolCallBuffer.js +0 -179
  193. package/src/tools/ToolNode.js +0 -930
  194. package/src/tools/ToolSearch.js +0 -904
  195. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  196. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  197. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  198. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  199. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  200. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  201. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  202. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  203. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  204. package/src/tools/__tests__/handlers.test.js +0 -799
  205. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  206. package/src/tools/handlers.js +0 -306
  207. package/src/tools/schema.js +0 -25
  208. package/src/tools/search/anthropic.js +0 -34
  209. package/src/tools/search/content.js +0 -116
  210. package/src/tools/search/content.test.js +0 -133
  211. package/src/tools/search/firecrawl.js +0 -173
  212. package/src/tools/search/format.js +0 -198
  213. package/src/tools/search/highlights.js +0 -241
  214. package/src/tools/search/index.js +0 -3
  215. package/src/tools/search/jina-reranker.test.js +0 -106
  216. package/src/tools/search/rerankers.js +0 -165
  217. package/src/tools/search/schema.js +0 -102
  218. package/src/tools/search/search.js +0 -561
  219. package/src/tools/search/serper-scraper.js +0 -126
  220. package/src/tools/search/test.js +0 -129
  221. package/src/tools/search/tool.js +0 -453
  222. package/src/tools/search/types.js +0 -2
  223. package/src/tools/search/utils.js +0 -59
  224. package/src/types/graph.js +0 -24
  225. package/src/types/graph.test.js +0 -192
  226. package/src/types/index.js +0 -7
  227. package/src/types/llm.js +0 -2
  228. package/src/types/messages.js +0 -2
  229. package/src/types/run.js +0 -2
  230. package/src/types/stream.js +0 -2
  231. package/src/types/tools.js +0 -2
  232. package/src/utils/contextAnalytics.js +0 -79
  233. package/src/utils/contextAnalytics.test.js +0 -166
  234. package/src/utils/events.js +0 -26
  235. package/src/utils/graph.js +0 -11
  236. package/src/utils/handlers.js +0 -65
  237. package/src/utils/index.js +0 -10
  238. package/src/utils/llm.js +0 -21
  239. package/src/utils/llmConfig.js +0 -205
  240. package/src/utils/logging.js +0 -37
  241. package/src/utils/misc.js +0 -51
  242. package/src/utils/run.js +0 -69
  243. package/src/utils/schema.js +0 -21
  244. package/src/utils/title.js +0 -119
  245. package/src/utils/tokens.js +0 -92
  246. package/src/utils/toonFormat.js +0 -379
@@ -1,670 +0,0 @@
1
- import { AIMessage, AIMessageChunk, ChatMessage, isAIMessage, isBaseMessage, isToolMessage, parseBase64DataUrl, convertToProviderContentBlock, isDataContentBlock, } from '@langchain/core/messages';
2
- import { ChatGenerationChunk } from '@langchain/core/outputs';
3
- import { isLangChainTool } from '@langchain/core/utils/function_calling';
4
- import { isOpenAITool } from '@langchain/core/language_models/base';
5
- import { v4 as uuidv4 } from 'uuid';
6
- import { jsonSchemaToGeminiParameters, schemaToGenerativeAIParameters, } from './zod_to_genai_parameters';
7
- export const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = '__gemini_function_call_thought_signatures__';
8
- const DUMMY_SIGNATURE = 'ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==';
9
- /**
10
- * Executes a function immediately and returns its result.
11
- * Functional utility similar to an Immediately Invoked Function Expression (IIFE).
12
- * @param fn The function to execute.
13
- * @returns The result of invoking fn.
14
- */
15
- export const iife = (fn) => fn();
16
- export function getMessageAuthor(message) {
17
- const type = message._getType();
18
- if (ChatMessage.isInstance(message)) {
19
- return message.role;
20
- }
21
- if (type === 'tool') {
22
- return type;
23
- }
24
- return message.name ?? type;
25
- }
26
- /**
27
- * Maps a message type to a Google Generative AI chat author.
28
- * @param message The message to map.
29
- * @param model The model to use for mapping.
30
- * @returns The message type mapped to a Google Generative AI chat author.
31
- */
32
- export function convertAuthorToRole(author) {
33
- switch (author) {
34
- /**
35
- * Note: Gemini currently is not supporting system messages
36
- * we will convert them to human messages and merge with following
37
- * */
38
- case 'supervisor':
39
- case 'ai':
40
- case 'model': // getMessageAuthor returns message.name. code ex.: return message.name ?? type;
41
- return 'model';
42
- case 'system':
43
- return 'system';
44
- case 'human':
45
- return 'user';
46
- case 'tool':
47
- case 'function':
48
- return 'function';
49
- default:
50
- throw new Error(`Unknown / unsupported author: ${author}`);
51
- }
52
- }
53
- function messageContentMedia(content) {
54
- if ('mimeType' in content && 'data' in content) {
55
- return {
56
- inlineData: {
57
- mimeType: content.mimeType,
58
- data: content.data,
59
- },
60
- };
61
- }
62
- if ('mimeType' in content && 'fileUri' in content) {
63
- return {
64
- fileData: {
65
- mimeType: content.mimeType,
66
- fileUri: content.fileUri,
67
- },
68
- };
69
- }
70
- throw new Error('Invalid media content');
71
- }
72
- function inferToolNameFromPreviousMessages(message, previousMessages) {
73
- return previousMessages
74
- .map((msg) => {
75
- if (isAIMessage(msg)) {
76
- return msg.tool_calls ?? [];
77
- }
78
- return [];
79
- })
80
- .flat()
81
- .find((toolCall) => {
82
- return toolCall.id === message.tool_call_id;
83
- })?.name;
84
- }
85
- function _getStandardContentBlockConverter(isMultimodalModel) {
86
- const standardContentBlockConverter = {
87
- providerName: 'Google Gemini',
88
- fromStandardTextBlock(block) {
89
- return {
90
- text: block.text,
91
- };
92
- },
93
- fromStandardImageBlock(block) {
94
- if (!isMultimodalModel) {
95
- throw new Error('This model does not support images');
96
- }
97
- if (block.source_type === 'url') {
98
- const data = parseBase64DataUrl({ dataUrl: block.url });
99
- if (data) {
100
- return {
101
- inlineData: {
102
- mimeType: data.mime_type,
103
- data: data.data,
104
- },
105
- };
106
- }
107
- else {
108
- return {
109
- fileData: {
110
- mimeType: block.mime_type ?? '',
111
- fileUri: block.url,
112
- },
113
- };
114
- }
115
- }
116
- if (block.source_type === 'base64') {
117
- return {
118
- inlineData: {
119
- mimeType: block.mime_type ?? '',
120
- data: block.data,
121
- },
122
- };
123
- }
124
- throw new Error(`Unsupported source type: ${block.source_type}`);
125
- },
126
- fromStandardAudioBlock(block) {
127
- if (!isMultimodalModel) {
128
- throw new Error('This model does not support audio');
129
- }
130
- if (block.source_type === 'url') {
131
- const data = parseBase64DataUrl({ dataUrl: block.url });
132
- if (data) {
133
- return {
134
- inlineData: {
135
- mimeType: data.mime_type,
136
- data: data.data,
137
- },
138
- };
139
- }
140
- else {
141
- return {
142
- fileData: {
143
- mimeType: block.mime_type ?? '',
144
- fileUri: block.url,
145
- },
146
- };
147
- }
148
- }
149
- if (block.source_type === 'base64') {
150
- return {
151
- inlineData: {
152
- mimeType: block.mime_type ?? '',
153
- data: block.data,
154
- },
155
- };
156
- }
157
- throw new Error(`Unsupported source type: ${block.source_type}`);
158
- },
159
- fromStandardFileBlock(block) {
160
- if (!isMultimodalModel) {
161
- throw new Error('This model does not support files');
162
- }
163
- if (block.source_type === 'text') {
164
- return {
165
- text: block.text,
166
- };
167
- }
168
- if (block.source_type === 'url') {
169
- const data = parseBase64DataUrl({ dataUrl: block.url });
170
- if (data) {
171
- return {
172
- inlineData: {
173
- mimeType: data.mime_type,
174
- data: data.data,
175
- },
176
- };
177
- }
178
- else {
179
- return {
180
- fileData: {
181
- mimeType: block.mime_type ?? '',
182
- fileUri: block.url,
183
- },
184
- };
185
- }
186
- }
187
- if (block.source_type === 'base64') {
188
- return {
189
- inlineData: {
190
- mimeType: block.mime_type ?? '',
191
- data: block.data,
192
- },
193
- };
194
- }
195
- throw new Error(`Unsupported source type: ${block.source_type}`);
196
- },
197
- };
198
- return standardContentBlockConverter;
199
- }
200
- function _convertLangChainContentToPart(content, isMultimodalModel) {
201
- if (isDataContentBlock(content)) {
202
- return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel));
203
- }
204
- if (content.type === 'text') {
205
- return { text: content.text };
206
- }
207
- else if (content.type === 'executableCode') {
208
- return { executableCode: content.executableCode };
209
- }
210
- else if (content.type === 'codeExecutionResult') {
211
- return { codeExecutionResult: content.codeExecutionResult };
212
- }
213
- else if (content.type === 'image_url') {
214
- if (!isMultimodalModel) {
215
- throw new Error('This model does not support images');
216
- }
217
- let source;
218
- if (typeof content.image_url === 'string') {
219
- source = content.image_url;
220
- }
221
- else if (typeof content.image_url === 'object' &&
222
- 'url' in content.image_url) {
223
- source = content.image_url.url;
224
- }
225
- else {
226
- throw new Error('Please provide image as base64 encoded data URL');
227
- }
228
- const [dm, data] = source.split(',');
229
- if (!dm.startsWith('data:')) {
230
- throw new Error('Please provide image as base64 encoded data URL');
231
- }
232
- const [mimeType, encoding] = dm.replace(/^data:/, '').split(';');
233
- if (encoding !== 'base64') {
234
- throw new Error('Please provide image as base64 encoded data URL');
235
- }
236
- return {
237
- inlineData: {
238
- data,
239
- mimeType,
240
- },
241
- };
242
- }
243
- else if (content.type === 'media') {
244
- return messageContentMedia(content);
245
- }
246
- else if (content.type === 'tool_use') {
247
- return {
248
- functionCall: {
249
- name: content.name,
250
- args: content.input,
251
- },
252
- };
253
- }
254
- else if (content.type?.includes('/') === true &&
255
- // Ensure it's a single slash.
256
- content.type.split('/').length === 2 &&
257
- 'data' in content &&
258
- typeof content.data === 'string') {
259
- return {
260
- inlineData: {
261
- mimeType: content.type,
262
- data: content.data,
263
- },
264
- };
265
- }
266
- else if ('functionCall' in content) {
267
- // No action needed here — function calls will be added later from message.tool_calls
268
- return undefined;
269
- }
270
- else {
271
- if ('type' in content) {
272
- throw new Error(`Unknown content type ${content.type}`);
273
- }
274
- else {
275
- throw new Error(`Unknown content ${JSON.stringify(content)}`);
276
- }
277
- }
278
- }
279
- export function convertMessageContentToParts(message, isMultimodalModel, previousMessages, model) {
280
- if (isToolMessage(message)) {
281
- const messageName = message.name ??
282
- inferToolNameFromPreviousMessages(message, previousMessages);
283
- if (messageName === undefined) {
284
- throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${message.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);
285
- }
286
- const result = Array.isArray(message.content)
287
- ? message.content
288
- .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))
289
- .filter((p) => p !== undefined)
290
- : message.content;
291
- if (message.status === 'error') {
292
- return [
293
- {
294
- functionResponse: {
295
- name: messageName,
296
- // The API expects an object with an `error` field if the function call fails.
297
- // `error` must be a valid object (not a string or array), so we wrap `message.content` here
298
- response: { error: { details: result } },
299
- },
300
- },
301
- ];
302
- }
303
- return [
304
- {
305
- functionResponse: {
306
- name: messageName,
307
- // again, can't have a string or array value for `response`, so we wrap it as an object here
308
- response: { result },
309
- },
310
- },
311
- ];
312
- }
313
- let functionCalls = [];
314
- const messageParts = [];
315
- if (typeof message.content === 'string' && message.content) {
316
- messageParts.push({ text: message.content });
317
- }
318
- if (Array.isArray(message.content)) {
319
- messageParts.push(...message.content
320
- .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))
321
- .filter((p) => p !== undefined));
322
- }
323
- const functionThoughtSignatures = message.additional_kwargs?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY];
324
- if (isAIMessage(message) && (message.tool_calls?.length ?? 0) > 0) {
325
- functionCalls = (message.tool_calls ?? []).map((tc) => {
326
- const thoughtSignature = iife(() => {
327
- if (tc.id != null && tc.id !== '') {
328
- const signature = functionThoughtSignatures?.[tc.id];
329
- if (signature != null && signature !== '') {
330
- return signature;
331
- }
332
- }
333
- if (model?.includes('gemini-3') === true) {
334
- return DUMMY_SIGNATURE;
335
- }
336
- return '';
337
- });
338
- return {
339
- functionCall: {
340
- name: tc.name,
341
- args: tc.args,
342
- },
343
- ...(thoughtSignature ? { thoughtSignature } : {}),
344
- };
345
- });
346
- }
347
- return [...messageParts, ...functionCalls];
348
- }
349
- export function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false, model) {
350
- return messages.reduce((acc, message, index) => {
351
- if (!isBaseMessage(message)) {
352
- throw new Error('Unsupported message input');
353
- }
354
- const author = getMessageAuthor(message);
355
- if (author === 'system' && index !== 0) {
356
- throw new Error('System message should be the first one');
357
- }
358
- const role = convertAuthorToRole(author);
359
- const prevContent = acc.content?.[acc.content.length];
360
- if (!acc.mergeWithPreviousContent &&
361
- prevContent &&
362
- prevContent.role === role) {
363
- throw new Error('Google Generative AI requires alternate messages between authors');
364
- }
365
- const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index), model);
366
- if (acc.mergeWithPreviousContent) {
367
- const prevContent = acc.content?.[acc.content.length - 1];
368
- if (!prevContent) {
369
- throw new Error('There was a problem parsing your system message. Please try a prompt without one.');
370
- }
371
- prevContent.parts.push(...parts);
372
- return {
373
- mergeWithPreviousContent: false,
374
- content: acc.content,
375
- };
376
- }
377
- let actualRole = role;
378
- if (actualRole === 'function' ||
379
- (actualRole === 'system' && !convertSystemMessageToHumanContent)) {
380
- // GenerativeAI API will throw an error if the role is not "user" or "model."
381
- actualRole = 'user';
382
- }
383
- const content = {
384
- role: actualRole,
385
- parts,
386
- };
387
- return {
388
- mergeWithPreviousContent: author === 'system' && !convertSystemMessageToHumanContent,
389
- content: [...(acc.content ?? []), content],
390
- };
391
- }, { content: [], mergeWithPreviousContent: false }).content;
392
- }
393
- export function convertResponseContentToChatGenerationChunk(response, extra) {
394
- if (!response.candidates || response.candidates.length === 0) {
395
- return null;
396
- }
397
- const [candidate] = response.candidates;
398
- const { content: candidateContent, ...generationInfo } = candidate ?? {};
399
- // Extract function calls directly from parts to preserve thoughtSignature
400
- const functionCalls = candidateContent?.parts?.reduce((acc, p) => {
401
- if ('functionCall' in p && p.functionCall) {
402
- acc.push({
403
- ...p,
404
- id: 'id' in p.functionCall && typeof p.functionCall.id === 'string'
405
- ? p.functionCall.id
406
- : uuidv4(),
407
- });
408
- }
409
- return acc;
410
- }, []) ?? [];
411
- let content;
412
- // Checks if some parts do not have text. If false, it means that the content is a string.
413
- const reasoningParts = [];
414
- if (candidateContent != null &&
415
- Array.isArray(candidateContent.parts) &&
416
- candidateContent.parts.every((p) => 'text' in p)) {
417
- // content = candidateContent.parts.map((p) => p.text).join('');
418
- const textParts = [];
419
- for (const part of candidateContent.parts) {
420
- if ('thought' in part && part.thought === true) {
421
- reasoningParts.push(part.text ?? '');
422
- continue;
423
- }
424
- textParts.push(part.text ?? '');
425
- }
426
- content = textParts.join('');
427
- }
428
- else if (candidateContent && Array.isArray(candidateContent.parts)) {
429
- content = candidateContent.parts
430
- .map((p) => {
431
- if ('text' in p && 'thought' in p && p.thought === true) {
432
- reasoningParts.push(p.text ?? '');
433
- return undefined;
434
- }
435
- else if ('text' in p) {
436
- return {
437
- type: 'text',
438
- text: p.text,
439
- };
440
- }
441
- else if ('executableCode' in p) {
442
- return {
443
- type: 'executableCode',
444
- executableCode: p.executableCode,
445
- };
446
- }
447
- else if ('codeExecutionResult' in p) {
448
- return {
449
- type: 'codeExecutionResult',
450
- codeExecutionResult: p.codeExecutionResult,
451
- };
452
- }
453
- return p;
454
- })
455
- .filter((p) => p !== undefined);
456
- }
457
- else {
458
- // no content returned - likely due to abnormal stop reason, e.g. malformed function call
459
- content = [];
460
- }
461
- let text = '';
462
- if (typeof content === 'string' && content) {
463
- text = content;
464
- }
465
- else if (Array.isArray(content)) {
466
- const block = content.find((b) => 'text' in b);
467
- text = block?.text ?? '';
468
- }
469
- const toolCallChunks = [];
470
- if (functionCalls.length > 0) {
471
- toolCallChunks.push(...functionCalls.map((fc) => ({
472
- type: 'tool_call_chunk',
473
- id: fc?.id,
474
- name: fc?.functionCall.name,
475
- args: JSON.stringify(fc?.functionCall.args),
476
- })));
477
- }
478
- // Extract thought signatures from function calls for Gemini 3+
479
- const functionThoughtSignatures = functionCalls.reduce((acc, fc) => {
480
- if (fc &&
481
- 'thoughtSignature' in fc &&
482
- typeof fc.thoughtSignature === 'string') {
483
- acc[fc.id] = fc.thoughtSignature;
484
- }
485
- return acc;
486
- }, {});
487
- const additional_kwargs = {
488
- [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,
489
- };
490
- if (reasoningParts.length > 0) {
491
- additional_kwargs.reasoning = reasoningParts.join('');
492
- }
493
- if (candidate?.groundingMetadata) {
494
- additional_kwargs.groundingMetadata = candidate.groundingMetadata;
495
- }
496
- const isFinalChunk = response.candidates[0]?.finishReason === 'STOP' ||
497
- response.candidates[0]?.finishReason === 'MAX_TOKENS' ||
498
- response.candidates[0]?.finishReason === 'SAFETY';
499
- return new ChatGenerationChunk({
500
- text,
501
- message: new AIMessageChunk({
502
- content: content,
503
- name: !candidateContent ? undefined : candidateContent.role,
504
- tool_call_chunks: toolCallChunks,
505
- // Each chunk can have unique "generationInfo", and merging strategy is unclear,
506
- // so leave blank for now.
507
- additional_kwargs,
508
- usage_metadata: isFinalChunk ? extra.usageMetadata : undefined,
509
- }),
510
- generationInfo,
511
- });
512
- }
513
- /**
514
- * Maps a Google GenerateContentResult to a LangChain ChatResult
515
- */
516
- export function mapGenerateContentResultToChatResult(response, extra) {
517
- if (!response.candidates ||
518
- response.candidates.length === 0 ||
519
- !response.candidates[0]) {
520
- return {
521
- generations: [],
522
- llmOutput: {
523
- filters: response.promptFeedback,
524
- },
525
- };
526
- }
527
- const [candidate] = response.candidates;
528
- const { content: candidateContent, ...generationInfo } = candidate ?? {};
529
- // Extract function calls directly from parts to preserve thoughtSignature
530
- const functionCalls = candidateContent?.parts.reduce((acc, p) => {
531
- if ('functionCall' in p && p.functionCall) {
532
- acc.push({
533
- ...p,
534
- id: 'id' in p.functionCall && typeof p.functionCall.id === 'string'
535
- ? p.functionCall.id
536
- : uuidv4(),
537
- });
538
- }
539
- return acc;
540
- }, []) ?? [];
541
- let content;
542
- const reasoningParts = [];
543
- if (Array.isArray(candidateContent?.parts) &&
544
- candidateContent.parts.length === 1 &&
545
- candidateContent.parts[0].text &&
546
- !('thought' in candidateContent.parts[0] &&
547
- candidateContent.parts[0].thought === true)) {
548
- content = candidateContent.parts[0].text;
549
- }
550
- else if (Array.isArray(candidateContent?.parts) &&
551
- candidateContent.parts.length > 0) {
552
- content = candidateContent.parts
553
- .map((p) => {
554
- if ('text' in p && 'thought' in p && p.thought === true) {
555
- reasoningParts.push(p.text ?? '');
556
- return undefined;
557
- }
558
- else if ('text' in p) {
559
- return {
560
- type: 'text',
561
- text: p.text,
562
- };
563
- }
564
- else if ('executableCode' in p) {
565
- return {
566
- type: 'executableCode',
567
- executableCode: p.executableCode,
568
- };
569
- }
570
- else if ('codeExecutionResult' in p) {
571
- return {
572
- type: 'codeExecutionResult',
573
- codeExecutionResult: p.codeExecutionResult,
574
- };
575
- }
576
- return p;
577
- })
578
- .filter((p) => p !== undefined);
579
- }
580
- else {
581
- content = [];
582
- }
583
- let text = '';
584
- if (typeof content === 'string') {
585
- text = content;
586
- }
587
- else if (Array.isArray(content) && content.length > 0) {
588
- const block = content.find((b) => 'text' in b);
589
- text = block?.text ?? text;
590
- }
591
- const additional_kwargs = {
592
- ...generationInfo,
593
- };
594
- if (reasoningParts.length > 0) {
595
- additional_kwargs.reasoning = reasoningParts.join('');
596
- }
597
- // Extract thought signatures from function calls for Gemini 3+
598
- const functionThoughtSignatures = functionCalls.reduce((acc, fc) => {
599
- if ('thoughtSignature' in fc && typeof fc.thoughtSignature === 'string') {
600
- acc[fc.id] = fc.thoughtSignature;
601
- }
602
- return acc;
603
- }, {});
604
- const tool_calls = functionCalls.map((fc) => ({
605
- type: 'tool_call',
606
- id: fc.id,
607
- name: fc.functionCall.name,
608
- args: fc.functionCall.args,
609
- }));
610
- // Store thought signatures map for later retrieval
611
- additional_kwargs[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] =
612
- functionThoughtSignatures;
613
- const generation = {
614
- text,
615
- message: new AIMessage({
616
- content: content ?? '',
617
- tool_calls,
618
- additional_kwargs,
619
- usage_metadata: extra?.usageMetadata,
620
- }),
621
- generationInfo,
622
- };
623
- return {
624
- generations: [generation],
625
- llmOutput: {
626
- tokenUsage: {
627
- promptTokens: extra?.usageMetadata?.input_tokens,
628
- completionTokens: extra?.usageMetadata?.output_tokens,
629
- totalTokens: extra?.usageMetadata?.total_tokens,
630
- },
631
- },
632
- };
633
- }
634
- export function convertToGenerativeAITools(tools) {
635
- if (tools.every((tool) => 'functionDeclarations' in tool &&
636
- Array.isArray(tool.functionDeclarations))) {
637
- return tools;
638
- }
639
- return [
640
- {
641
- functionDeclarations: tools.map((tool) => {
642
- if (isLangChainTool(tool)) {
643
- const jsonSchema = schemaToGenerativeAIParameters(tool.schema);
644
- if (jsonSchema.type === 'object' &&
645
- 'properties' in jsonSchema &&
646
- Object.keys(jsonSchema.properties).length === 0) {
647
- return {
648
- name: tool.name,
649
- description: tool.description,
650
- };
651
- }
652
- return {
653
- name: tool.name,
654
- description: tool.description,
655
- parameters: jsonSchema,
656
- };
657
- }
658
- if (isOpenAITool(tool)) {
659
- return {
660
- name: tool.function.name,
661
- description: tool.function.description ?? 'A function available to call.',
662
- parameters: jsonSchemaToGeminiParameters(tool.function.parameters),
663
- };
664
- }
665
- return tool;
666
- }),
667
- },
668
- ];
669
- }
670
- //# sourceMappingURL=common.js.map