@illuma-ai/agents 1.1.21 → 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 (241) 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/run.cjs +20 -9
  6. package/dist/cjs/run.cjs.map +1 -1
  7. package/dist/esm/graphs/Graph.mjs +12 -1
  8. package/dist/esm/graphs/Graph.mjs.map +1 -1
  9. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  11. package/dist/esm/run.mjs +20 -9
  12. package/dist/esm/run.mjs.map +1 -1
  13. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  14. package/package.json +1 -1
  15. package/src/graphs/Graph.ts +12 -1
  16. package/src/graphs/MultiAgentGraph.ts +105 -1
  17. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  18. package/src/run.ts +20 -11
  19. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  20. package/src/agents/AgentContext.js +0 -782
  21. package/src/agents/AgentContext.test.js +0 -421
  22. package/src/agents/__tests__/AgentContext.test.js +0 -678
  23. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  24. package/src/common/enum.js +0 -192
  25. package/src/common/index.js +0 -3
  26. package/src/events.js +0 -166
  27. package/src/graphs/Graph.js +0 -1857
  28. package/src/graphs/MultiAgentGraph.js +0 -1092
  29. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  30. package/src/graphs/__tests__/structured-output.test.js +0 -144
  31. package/src/graphs/contextManagement.e2e.test.js +0 -718
  32. package/src/graphs/contextManagement.test.js +0 -485
  33. package/src/graphs/handoffValidation.test.js +0 -276
  34. package/src/graphs/index.js +0 -3
  35. package/src/index.js +0 -28
  36. package/src/instrumentation.js +0 -21
  37. package/src/llm/anthropic/index.js +0 -319
  38. package/src/llm/anthropic/types.js +0 -46
  39. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  40. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  41. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  42. package/src/llm/anthropic/utils/tools.js +0 -25
  43. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  44. package/src/llm/bedrock/index.js +0 -303
  45. package/src/llm/bedrock/types.js +0 -2
  46. package/src/llm/bedrock/utils/index.js +0 -6
  47. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  48. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  49. package/src/llm/fake.js +0 -92
  50. package/src/llm/google/index.js +0 -215
  51. package/src/llm/google/types.js +0 -12
  52. package/src/llm/google/utils/common.js +0 -670
  53. package/src/llm/google/utils/tools.js +0 -111
  54. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  55. package/src/llm/openai/index.js +0 -1033
  56. package/src/llm/openai/types.js +0 -2
  57. package/src/llm/openai/utils/index.js +0 -756
  58. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  59. package/src/llm/openrouter/index.js +0 -261
  60. package/src/llm/openrouter/reasoning.test.js +0 -181
  61. package/src/llm/providers.js +0 -36
  62. package/src/llm/text.js +0 -65
  63. package/src/llm/vertexai/index.js +0 -402
  64. package/src/messages/__tests__/tools.test.js +0 -392
  65. package/src/messages/cache.js +0 -404
  66. package/src/messages/cache.test.js +0 -1167
  67. package/src/messages/content.js +0 -48
  68. package/src/messages/content.test.js +0 -314
  69. package/src/messages/core.js +0 -359
  70. package/src/messages/ensureThinkingBlock.test.js +0 -997
  71. package/src/messages/format.js +0 -973
  72. package/src/messages/formatAgentMessages.test.js +0 -2278
  73. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  74. package/src/messages/formatMessage.test.js +0 -608
  75. package/src/messages/ids.js +0 -18
  76. package/src/messages/index.js +0 -9
  77. package/src/messages/labelContentByAgent.test.js +0 -725
  78. package/src/messages/prune.js +0 -438
  79. package/src/messages/reducer.js +0 -60
  80. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  81. package/src/messages/summarize.js +0 -146
  82. package/src/messages/summarize.test.js +0 -332
  83. package/src/messages/tools.js +0 -90
  84. package/src/mockStream.js +0 -81
  85. package/src/prompts/collab.js +0 -7
  86. package/src/prompts/index.js +0 -3
  87. package/src/prompts/taskmanager.js +0 -58
  88. package/src/run.js +0 -427
  89. package/src/schemas/index.js +0 -3
  90. package/src/schemas/schema-preparation.test.js +0 -370
  91. package/src/schemas/validate.js +0 -314
  92. package/src/schemas/validate.test.js +0 -264
  93. package/src/scripts/abort.js +0 -127
  94. package/src/scripts/ant_web_search.js +0 -130
  95. package/src/scripts/ant_web_search_edge_case.js +0 -133
  96. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  97. package/src/scripts/args.js +0 -41
  98. package/src/scripts/bedrock-cache-debug.js +0 -186
  99. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  100. package/src/scripts/bedrock-merge-test.js +0 -80
  101. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  102. package/src/scripts/caching.js +0 -106
  103. package/src/scripts/cli.js +0 -152
  104. package/src/scripts/cli2.js +0 -119
  105. package/src/scripts/cli3.js +0 -163
  106. package/src/scripts/cli4.js +0 -165
  107. package/src/scripts/cli5.js +0 -165
  108. package/src/scripts/code_exec.js +0 -171
  109. package/src/scripts/code_exec_files.js +0 -180
  110. package/src/scripts/code_exec_multi_session.js +0 -185
  111. package/src/scripts/code_exec_ptc.js +0 -265
  112. package/src/scripts/code_exec_session.js +0 -217
  113. package/src/scripts/code_exec_simple.js +0 -120
  114. package/src/scripts/content.js +0 -111
  115. package/src/scripts/empty_input.js +0 -125
  116. package/src/scripts/handoff-test.js +0 -96
  117. package/src/scripts/image.js +0 -138
  118. package/src/scripts/memory.js +0 -83
  119. package/src/scripts/multi-agent-chain.js +0 -271
  120. package/src/scripts/multi-agent-conditional.js +0 -185
  121. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  122. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  123. package/src/scripts/multi-agent-parallel-start.js +0 -214
  124. package/src/scripts/multi-agent-parallel.js +0 -346
  125. package/src/scripts/multi-agent-sequence.js +0 -184
  126. package/src/scripts/multi-agent-supervisor.js +0 -324
  127. package/src/scripts/multi-agent-test.js +0 -147
  128. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  129. package/src/scripts/parallel-full-metadata-test.js +0 -176
  130. package/src/scripts/parallel-tools-test.js +0 -256
  131. package/src/scripts/programmatic_exec.js +0 -277
  132. package/src/scripts/programmatic_exec_agent.js +0 -168
  133. package/src/scripts/search.js +0 -118
  134. package/src/scripts/sequential-full-metadata-test.js +0 -143
  135. package/src/scripts/simple.js +0 -174
  136. package/src/scripts/single-agent-metadata-test.js +0 -152
  137. package/src/scripts/stream.js +0 -113
  138. package/src/scripts/test-custom-prompt-key.js +0 -132
  139. package/src/scripts/test-handoff-input.js +0 -143
  140. package/src/scripts/test-handoff-preamble.js +0 -227
  141. package/src/scripts/test-handoff-steering.js +0 -353
  142. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  143. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  144. package/src/scripts/test-parallel-handoffs.js +0 -229
  145. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  146. package/src/scripts/test-thinking-handoff.js +0 -132
  147. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  148. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  149. package/src/scripts/test-tools-before-handoff.js +0 -187
  150. package/src/scripts/test_code_api.js +0 -263
  151. package/src/scripts/thinking-bedrock.js +0 -128
  152. package/src/scripts/thinking-vertexai.js +0 -130
  153. package/src/scripts/thinking.js +0 -134
  154. package/src/scripts/tool_search.js +0 -114
  155. package/src/scripts/tools.js +0 -125
  156. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  157. package/src/specs/agent-handoffs.test.js +0 -924
  158. package/src/specs/anthropic.simple.test.js +0 -287
  159. package/src/specs/azure.simple.test.js +0 -381
  160. package/src/specs/cache.simple.test.js +0 -282
  161. package/src/specs/custom-event-await.test.js +0 -148
  162. package/src/specs/deepseek.simple.test.js +0 -189
  163. package/src/specs/emergency-prune.test.js +0 -308
  164. package/src/specs/moonshot.simple.test.js +0 -237
  165. package/src/specs/observability.integration.test.js +0 -1337
  166. package/src/specs/openai.simple.test.js +0 -233
  167. package/src/specs/openrouter.simple.test.js +0 -202
  168. package/src/specs/prune.test.js +0 -733
  169. package/src/specs/reasoning.test.js +0 -144
  170. package/src/specs/spec.utils.js +0 -4
  171. package/src/specs/thinking-handoff.test.js +0 -486
  172. package/src/specs/thinking-prune.test.js +0 -600
  173. package/src/specs/token-distribution-edge-case.test.js +0 -246
  174. package/src/specs/token-memoization.test.js +0 -32
  175. package/src/specs/tokens.test.js +0 -49
  176. package/src/specs/tool-error.test.js +0 -139
  177. package/src/splitStream.js +0 -204
  178. package/src/splitStream.test.js +0 -504
  179. package/src/stream.js +0 -650
  180. package/src/stream.test.js +0 -225
  181. package/src/test/mockTools.js +0 -340
  182. package/src/tools/BrowserTools.js +0 -245
  183. package/src/tools/Calculator.js +0 -38
  184. package/src/tools/Calculator.test.js +0 -225
  185. package/src/tools/CodeExecutor.js +0 -233
  186. package/src/tools/ProgrammaticToolCalling.js +0 -602
  187. package/src/tools/StreamingToolCallBuffer.js +0 -179
  188. package/src/tools/ToolNode.js +0 -930
  189. package/src/tools/ToolSearch.js +0 -904
  190. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  191. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  192. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  193. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  194. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  195. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  196. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  197. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  198. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  199. package/src/tools/__tests__/handlers.test.js +0 -799
  200. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  201. package/src/tools/handlers.js +0 -306
  202. package/src/tools/schema.js +0 -25
  203. package/src/tools/search/anthropic.js +0 -34
  204. package/src/tools/search/content.js +0 -116
  205. package/src/tools/search/content.test.js +0 -133
  206. package/src/tools/search/firecrawl.js +0 -173
  207. package/src/tools/search/format.js +0 -198
  208. package/src/tools/search/highlights.js +0 -241
  209. package/src/tools/search/index.js +0 -3
  210. package/src/tools/search/jina-reranker.test.js +0 -106
  211. package/src/tools/search/rerankers.js +0 -165
  212. package/src/tools/search/schema.js +0 -102
  213. package/src/tools/search/search.js +0 -561
  214. package/src/tools/search/serper-scraper.js +0 -126
  215. package/src/tools/search/test.js +0 -129
  216. package/src/tools/search/tool.js +0 -453
  217. package/src/tools/search/types.js +0 -2
  218. package/src/tools/search/utils.js +0 -59
  219. package/src/types/graph.js +0 -24
  220. package/src/types/graph.test.js +0 -192
  221. package/src/types/index.js +0 -7
  222. package/src/types/llm.js +0 -2
  223. package/src/types/messages.js +0 -2
  224. package/src/types/run.js +0 -2
  225. package/src/types/stream.js +0 -2
  226. package/src/types/tools.js +0 -2
  227. package/src/utils/contextAnalytics.js +0 -79
  228. package/src/utils/contextAnalytics.test.js +0 -166
  229. package/src/utils/events.js +0 -26
  230. package/src/utils/graph.js +0 -11
  231. package/src/utils/handlers.js +0 -65
  232. package/src/utils/index.js +0 -10
  233. package/src/utils/llm.js +0 -21
  234. package/src/utils/llmConfig.js +0 -205
  235. package/src/utils/logging.js +0 -37
  236. package/src/utils/misc.js +0 -51
  237. package/src/utils/run.js +0 -69
  238. package/src/utils/schema.js +0 -21
  239. package/src/utils/title.js +0 -119
  240. package/src/utils/tokens.js +0 -92
  241. package/src/utils/toonFormat.js +0 -379
@@ -1,756 +0,0 @@
1
- import { AIMessage, AIMessageChunk, ChatMessage, isAIMessage, parseBase64DataUrl, parseMimeType, convertToProviderContentBlock, isDataContentBlock, } from '@langchain/core/messages';
2
- import { ChatGenerationChunk } from '@langchain/core/outputs';
3
- import { convertLangChainToolCallToOpenAI, makeInvalidToolCall, parseToolCall, } from '@langchain/core/output_parsers/openai_tools';
4
- function extractGenericMessageCustomRole(message) {
5
- if (message.role !== 'system' &&
6
- message.role !== 'developer' &&
7
- message.role !== 'assistant' &&
8
- message.role !== 'user' &&
9
- message.role !== 'function' &&
10
- message.role !== 'tool') {
11
- console.warn(`Unknown message role: ${message.role}`);
12
- }
13
- return message.role;
14
- }
15
- export function messageToOpenAIRole(message) {
16
- const type = message._getType();
17
- switch (type) {
18
- case 'system':
19
- return 'system';
20
- case 'ai':
21
- return 'assistant';
22
- case 'human':
23
- return 'user';
24
- case 'function':
25
- return 'function';
26
- case 'tool':
27
- return 'tool';
28
- case 'generic': {
29
- if (!ChatMessage.isInstance(message))
30
- throw new Error('Invalid generic chat message');
31
- return extractGenericMessageCustomRole(message);
32
- }
33
- default:
34
- throw new Error(`Unknown message type: ${type}`);
35
- }
36
- }
37
- const completionsApiContentBlockConverter = {
38
- providerName: 'ChatOpenAI',
39
- fromStandardTextBlock(block) {
40
- return { type: 'text', text: block.text };
41
- },
42
- fromStandardImageBlock(block) {
43
- if (block.source_type === 'url') {
44
- return {
45
- type: 'image_url',
46
- image_url: {
47
- url: block.url,
48
- ...(block.metadata?.detail
49
- ? { detail: block.metadata.detail }
50
- : {}),
51
- },
52
- };
53
- }
54
- if (block.source_type === 'base64') {
55
- const url = `data:${block.mime_type ?? ''};base64,${block.data}`;
56
- return {
57
- type: 'image_url',
58
- image_url: {
59
- url,
60
- ...(block.metadata?.detail
61
- ? { detail: block.metadata.detail }
62
- : {}),
63
- },
64
- };
65
- }
66
- throw new Error(`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);
67
- },
68
- fromStandardAudioBlock(block) {
69
- if (block.source_type === 'url') {
70
- const data = parseBase64DataUrl({ dataUrl: block.url });
71
- if (!data) {
72
- throw new Error(`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`);
73
- }
74
- const rawMimeType = data.mime_type || block.mime_type || '';
75
- let mimeType;
76
- try {
77
- mimeType = parseMimeType(rawMimeType);
78
- }
79
- catch {
80
- throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
81
- }
82
- if (mimeType.type !== 'audio' ||
83
- (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')) {
84
- throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
85
- }
86
- return {
87
- type: 'input_audio',
88
- input_audio: {
89
- format: mimeType.subtype,
90
- data: data.data,
91
- },
92
- };
93
- }
94
- if (block.source_type === 'base64') {
95
- let mimeType;
96
- try {
97
- mimeType = parseMimeType(block.mime_type ?? '');
98
- }
99
- catch {
100
- throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
101
- }
102
- if (mimeType.type !== 'audio' ||
103
- (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')) {
104
- throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
105
- }
106
- return {
107
- type: 'input_audio',
108
- input_audio: {
109
- format: mimeType.subtype,
110
- data: block.data,
111
- },
112
- };
113
- }
114
- throw new Error(`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);
115
- },
116
- fromStandardFileBlock(block) {
117
- if (block.source_type === 'url') {
118
- const data = parseBase64DataUrl({ dataUrl: block.url });
119
- if (!data) {
120
- throw new Error(`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`);
121
- }
122
- return {
123
- type: 'file',
124
- file: {
125
- file_data: block.url, // formatted as base64 data URL
126
- ...(block.metadata?.filename || block.metadata?.name
127
- ? {
128
- filename: (block.metadata.filename ||
129
- block.metadata.name),
130
- }
131
- : {}),
132
- },
133
- };
134
- }
135
- if (block.source_type === 'base64') {
136
- return {
137
- type: 'file',
138
- file: {
139
- file_data: `data:${block.mime_type ?? ''};base64,${block.data}`,
140
- ...(block.metadata?.filename ||
141
- block.metadata?.name ||
142
- block.metadata?.title
143
- ? {
144
- filename: (block.metadata.filename ||
145
- block.metadata.name ||
146
- block.metadata.title),
147
- }
148
- : {}),
149
- },
150
- };
151
- }
152
- if (block.source_type === 'id') {
153
- return {
154
- type: 'file',
155
- file: {
156
- file_id: block.id,
157
- },
158
- };
159
- }
160
- throw new Error(`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);
161
- },
162
- };
163
- // Used in LangSmith, export is important here
164
- export function _convertMessagesToOpenAIParams(messages, model, options) {
165
- // TODO: Function messages do not support array content, fix cast
166
- return messages.flatMap((message) => {
167
- let role = messageToOpenAIRole(message);
168
- if (role === 'system' && isReasoningModel(model)) {
169
- role = 'developer';
170
- }
171
- let hasAnthropicThinkingBlock = false;
172
- const content = typeof message.content === 'string'
173
- ? message.content
174
- : message.content.map((m) => {
175
- if ('type' in m && m.type === 'thinking') {
176
- hasAnthropicThinkingBlock = true;
177
- return m;
178
- }
179
- if (isDataContentBlock(m)) {
180
- return convertToProviderContentBlock(m, completionsApiContentBlockConverter);
181
- }
182
- return m;
183
- });
184
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
185
- const completionParam = {
186
- role,
187
- content,
188
- };
189
- if (message.name != null) {
190
- completionParam.name = message.name;
191
- }
192
- if (message.additional_kwargs.function_call != null) {
193
- completionParam.function_call = message.additional_kwargs.function_call;
194
- completionParam.content = '';
195
- }
196
- if (isAIMessage(message) && !!message.tool_calls?.length) {
197
- completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI);
198
- completionParam.content = hasAnthropicThinkingBlock ? content : '';
199
- if (options?.includeReasoningContent === true &&
200
- message.additional_kwargs.reasoning_content != null) {
201
- completionParam.reasoning_content =
202
- message.additional_kwargs.reasoning_content;
203
- }
204
- if (options?.includeReasoningDetails === true &&
205
- message.additional_kwargs.reasoning_details != null) {
206
- // For Claude via OpenRouter, convert reasoning_details to content blocks
207
- const isClaudeModel = model?.includes('claude') === true ||
208
- model?.includes('anthropic') === true;
209
- if (options.convertReasoningDetailsToContent === true &&
210
- isClaudeModel) {
211
- const reasoningDetails = message.additional_kwargs
212
- .reasoning_details;
213
- const contentBlocks = [];
214
- // Add thinking blocks from reasoning_details
215
- for (const detail of reasoningDetails) {
216
- if (detail.type === 'reasoning.text' && detail.text != null) {
217
- contentBlocks.push({
218
- type: 'thinking',
219
- thinking: detail.text,
220
- });
221
- }
222
- else if (detail.type === 'reasoning.encrypted' &&
223
- detail.data != null) {
224
- contentBlocks.push({
225
- type: 'redacted_thinking',
226
- data: detail.data,
227
- id: detail.id,
228
- });
229
- }
230
- }
231
- // Set content to array with thinking blocks
232
- if (contentBlocks.length > 0) {
233
- completionParam.content = contentBlocks;
234
- }
235
- }
236
- else {
237
- // For non-Claude models, pass as separate field
238
- completionParam.reasoning_details =
239
- message.additional_kwargs.reasoning_details;
240
- }
241
- }
242
- }
243
- else {
244
- if (message.additional_kwargs.tool_calls != null) {
245
- completionParam.tool_calls = message.additional_kwargs.tool_calls;
246
- if (options?.includeReasoningContent === true &&
247
- message.additional_kwargs.reasoning_content != null) {
248
- completionParam.reasoning_content =
249
- message.additional_kwargs.reasoning_content;
250
- }
251
- if (options?.includeReasoningDetails === true &&
252
- message.additional_kwargs.reasoning_details != null) {
253
- // For Claude via OpenRouter, convert reasoning_details to content blocks
254
- const isClaudeModel = model?.includes('claude') === true ||
255
- model?.includes('anthropic') === true;
256
- if (options.convertReasoningDetailsToContent === true &&
257
- isClaudeModel) {
258
- const reasoningDetails = message.additional_kwargs
259
- .reasoning_details;
260
- const contentBlocks = [];
261
- // Add thinking blocks from reasoning_details
262
- for (const detail of reasoningDetails) {
263
- if (detail.type === 'reasoning.text' && detail.text != null) {
264
- contentBlocks.push({
265
- type: 'thinking',
266
- thinking: detail.text,
267
- });
268
- }
269
- else if (detail.type === 'reasoning.encrypted' &&
270
- detail.data != null) {
271
- contentBlocks.push({
272
- type: 'redacted_thinking',
273
- data: detail.data,
274
- id: detail.id,
275
- });
276
- }
277
- }
278
- // Set content to array with thinking blocks
279
- if (contentBlocks.length > 0) {
280
- completionParam.content = contentBlocks;
281
- }
282
- }
283
- else {
284
- // For non-Claude models, pass as separate field
285
- completionParam.reasoning_details =
286
- message.additional_kwargs.reasoning_details;
287
- }
288
- }
289
- }
290
- if (message.tool_call_id != null) {
291
- completionParam.tool_call_id = message.tool_call_id;
292
- }
293
- }
294
- if (message.additional_kwargs.audio &&
295
- typeof message.additional_kwargs.audio === 'object' &&
296
- 'id' in message.additional_kwargs.audio) {
297
- const audioMessage = {
298
- role: 'assistant',
299
- audio: {
300
- id: message.additional_kwargs.audio.id,
301
- },
302
- };
303
- return [completionParam, audioMessage];
304
- }
305
- return completionParam;
306
- });
307
- }
308
- const _FUNCTION_CALL_IDS_MAP_KEY = '__openai_function_call_ids__';
309
- function _convertReasoningSummaryToOpenAIResponsesParams(reasoning) {
310
- // combine summary parts that have the the same index and then remove the indexes
311
- const summary = (reasoning.summary.length > 1
312
- ? reasoning.summary.reduce((acc, curr) => {
313
- const last = acc.at(-1);
314
- if (last.index === curr.index) {
315
- last.text += curr.text;
316
- }
317
- else {
318
- acc.push(curr);
319
- }
320
- return acc;
321
- }, [{ ...reasoning.summary[0] }])
322
- : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== 'index')));
323
- return {
324
- ...reasoning,
325
- summary,
326
- };
327
- }
328
- export function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
329
- return messages.flatMap((lcMsg) => {
330
- const additional_kwargs = lcMsg.additional_kwargs;
331
- let role = messageToOpenAIRole(lcMsg);
332
- if (role === 'system' && isReasoningModel(model))
333
- role = 'developer';
334
- if (role === 'function') {
335
- throw new Error('Function messages are not supported in Responses API');
336
- }
337
- if (role === 'tool') {
338
- const toolMessage = lcMsg;
339
- // Handle computer call output
340
- if (additional_kwargs.type === 'computer_call_output') {
341
- const output = (() => {
342
- if (typeof toolMessage.content === 'string') {
343
- return {
344
- type: 'computer_screenshot',
345
- image_url: toolMessage.content,
346
- };
347
- }
348
- if (Array.isArray(toolMessage.content)) {
349
- const oaiScreenshot = toolMessage.content.find((i) => i.type === 'computer_screenshot');
350
- if (oaiScreenshot)
351
- return oaiScreenshot;
352
- const lcImage = toolMessage.content.find((i) => i.type === 'image_url');
353
- if (lcImage) {
354
- return {
355
- type: 'computer_screenshot',
356
- image_url: typeof lcImage.image_url === 'string'
357
- ? lcImage.image_url
358
- : lcImage.image_url.url,
359
- };
360
- }
361
- }
362
- throw new Error('Invalid computer call output');
363
- })();
364
- return {
365
- type: 'computer_call_output',
366
- output,
367
- call_id: toolMessage.tool_call_id,
368
- };
369
- }
370
- return {
371
- type: 'function_call_output',
372
- call_id: toolMessage.tool_call_id,
373
- id: toolMessage.id?.startsWith('fc_') ? toolMessage.id : undefined,
374
- output: typeof toolMessage.content !== 'string'
375
- ? JSON.stringify(toolMessage.content)
376
- : toolMessage.content,
377
- };
378
- }
379
- if (role === 'assistant') {
380
- // if we have the original response items, just reuse them
381
- if (!zdrEnabled &&
382
- lcMsg.response_metadata.output != null &&
383
- Array.isArray(lcMsg.response_metadata.output) &&
384
- lcMsg.response_metadata.output.length > 0 &&
385
- lcMsg.response_metadata.output.every((item) => 'type' in item)) {
386
- return lcMsg.response_metadata.output;
387
- }
388
- // otherwise, try to reconstruct the response from what we have
389
- const input = [];
390
- // reasoning items
391
- if (additional_kwargs.reasoning && !zdrEnabled) {
392
- const reasoningItem = _convertReasoningSummaryToOpenAIResponsesParams(additional_kwargs.reasoning);
393
- input.push(reasoningItem);
394
- }
395
- // ai content
396
- let { content } = lcMsg;
397
- if (additional_kwargs.refusal) {
398
- if (typeof content === 'string') {
399
- content = [{ type: 'output_text', text: content, annotations: [] }];
400
- }
401
- content = [
402
- ...content,
403
- { type: 'refusal', refusal: additional_kwargs.refusal },
404
- ];
405
- }
406
- input.push({
407
- type: 'message',
408
- role: 'assistant',
409
- ...(lcMsg.id && !zdrEnabled && lcMsg.id.startsWith('msg_')
410
- ? { id: lcMsg.id }
411
- : {}),
412
- content: typeof content === 'string'
413
- ? content
414
- : content.flatMap((item) => {
415
- if (item.type === 'text') {
416
- return {
417
- type: 'output_text',
418
- text: item.text,
419
- // @ts-expect-error TODO: add types for `annotations`
420
- annotations: item.annotations ?? [],
421
- };
422
- }
423
- if (item.type === 'output_text' || item.type === 'refusal') {
424
- return item;
425
- }
426
- return [];
427
- }),
428
- });
429
- const functionCallIds = additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY];
430
- if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) {
431
- input.push(...lcMsg.tool_calls.map((toolCall) => ({
432
- type: 'function_call',
433
- name: toolCall.name,
434
- arguments: JSON.stringify(toolCall.args),
435
- call_id: toolCall.id,
436
- ...(zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),
437
- })));
438
- }
439
- else if (additional_kwargs.tool_calls) {
440
- input.push(...additional_kwargs.tool_calls.map((toolCall) => ({
441
- type: 'function_call',
442
- name: toolCall.function.name,
443
- call_id: toolCall.id,
444
- arguments: toolCall.function.arguments,
445
- ...(zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),
446
- })));
447
- }
448
- const toolOutputs = (lcMsg.response_metadata.output?.length ?? 0) > 0
449
- ? lcMsg.response_metadata.output
450
- : additional_kwargs.tool_outputs;
451
- const fallthroughCallTypes = [
452
- 'computer_call',
453
- /** @ts-ignore */
454
- 'mcp_call',
455
- /** @ts-ignore */
456
- 'code_interpreter_call',
457
- /** @ts-ignore */
458
- 'image_generation_call',
459
- ];
460
- if (toolOutputs != null) {
461
- const castToolOutputs = toolOutputs;
462
- const fallthroughCalls = castToolOutputs.filter((item) => fallthroughCallTypes.includes(item.type));
463
- if (fallthroughCalls.length > 0)
464
- input.push(...fallthroughCalls);
465
- }
466
- return input;
467
- }
468
- if (role === 'user' || role === 'system' || role === 'developer') {
469
- if (typeof lcMsg.content === 'string') {
470
- return { type: 'message', role, content: lcMsg.content };
471
- }
472
- const messages = [];
473
- const content = lcMsg.content.flatMap((item) => {
474
- if (item.type === 'mcp_approval_response') {
475
- messages.push({
476
- // @ts-ignore
477
- type: 'mcp_approval_response',
478
- approval_request_id: item.approval_request_id,
479
- approve: item.approve,
480
- });
481
- }
482
- if (isDataContentBlock(item)) {
483
- return convertToProviderContentBlock(item, completionsApiContentBlockConverter);
484
- }
485
- if (item.type === 'text') {
486
- return {
487
- type: 'input_text',
488
- text: item.text,
489
- };
490
- }
491
- if (item.type === 'image_url') {
492
- return {
493
- type: 'input_image',
494
- image_url: typeof item.image_url === 'string'
495
- ? item.image_url
496
- : item.image_url.url,
497
- detail: typeof item.image_url === 'string'
498
- ? 'auto'
499
- : item.image_url.detail,
500
- };
501
- }
502
- if (item.type === 'input_text' ||
503
- item.type === 'input_image' ||
504
- item.type === 'input_file') {
505
- return item;
506
- }
507
- return [];
508
- });
509
- if (content.length > 0) {
510
- messages.push({ type: 'message', role, content });
511
- }
512
- return messages;
513
- }
514
- console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);
515
- return [];
516
- });
517
- }
518
- export function isReasoningModel(model) {
519
- return model != null && model !== '' && /\b(o\d|gpt-[5-9])\b/i.test(model);
520
- }
521
- function _convertOpenAIResponsesMessageToBaseMessage(response) {
522
- if (response.error) {
523
- // TODO: add support for `addLangChainErrorFields`
524
- const error = new Error(response.error.message);
525
- error.name = response.error.code;
526
- throw error;
527
- }
528
- let messageId;
529
- const content = [];
530
- const tool_calls = [];
531
- const invalid_tool_calls = [];
532
- const response_metadata = {
533
- model: response.model,
534
- created_at: response.created_at,
535
- id: response.id,
536
- incomplete_details: response.incomplete_details,
537
- metadata: response.metadata,
538
- object: response.object,
539
- status: response.status,
540
- user: response.user,
541
- service_tier: response.service_tier,
542
- // for compatibility with chat completion calls.
543
- model_name: response.model,
544
- };
545
- const additional_kwargs = {};
546
- for (const item of response.output) {
547
- if (item.type === 'message') {
548
- messageId = item.id;
549
- content.push(...item.content.flatMap((part) => {
550
- if (part.type === 'output_text') {
551
- if ('parsed' in part && part.parsed != null) {
552
- additional_kwargs.parsed = part.parsed;
553
- }
554
- return {
555
- type: 'text',
556
- text: part.text,
557
- annotations: part.annotations,
558
- };
559
- }
560
- if (part.type === 'refusal') {
561
- additional_kwargs.refusal = part.refusal;
562
- return [];
563
- }
564
- return part;
565
- }));
566
- }
567
- else if (item.type === 'function_call') {
568
- const fnAdapter = {
569
- function: { name: item.name, arguments: item.arguments },
570
- id: item.call_id,
571
- };
572
- try {
573
- tool_calls.push(parseToolCall(fnAdapter, { returnId: true }));
574
- }
575
- catch (e) {
576
- let errMessage;
577
- if (typeof e === 'object' &&
578
- e != null &&
579
- 'message' in e &&
580
- typeof e.message === 'string') {
581
- errMessage = e.message;
582
- }
583
- invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage));
584
- }
585
- additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};
586
- if (item.id) {
587
- additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;
588
- }
589
- }
590
- else if (item.type === 'reasoning') {
591
- additional_kwargs.reasoning = item;
592
- }
593
- else {
594
- additional_kwargs.tool_outputs ??= [];
595
- additional_kwargs.tool_outputs.push(item);
596
- }
597
- }
598
- return new AIMessage({
599
- id: messageId,
600
- content,
601
- tool_calls,
602
- invalid_tool_calls,
603
- usage_metadata: response.usage,
604
- additional_kwargs,
605
- response_metadata,
606
- });
607
- }
608
- export function _convertOpenAIResponsesDeltaToBaseMessageChunk(chunk) {
609
- const content = [];
610
- let generationInfo = {};
611
- let usage_metadata;
612
- const tool_call_chunks = [];
613
- const response_metadata = {};
614
- const additional_kwargs = {};
615
- let id;
616
- if (chunk.type === 'response.output_text.delta') {
617
- content.push({
618
- type: 'text',
619
- text: chunk.delta,
620
- index: chunk.content_index,
621
- });
622
- /** @ts-ignore */
623
- }
624
- else if (chunk.type === 'response.output_text_annotation.added') {
625
- content.push({
626
- type: 'text',
627
- text: '',
628
- /** @ts-ignore */
629
- annotations: [chunk.annotation],
630
- /** @ts-ignore */
631
- index: chunk.content_index,
632
- });
633
- }
634
- else if (chunk.type === 'response.output_item.added' &&
635
- chunk.item.type === 'message') {
636
- id = chunk.item.id;
637
- }
638
- else if (chunk.type === 'response.output_item.added' &&
639
- chunk.item.type === 'function_call') {
640
- tool_call_chunks.push({
641
- type: 'tool_call_chunk',
642
- name: chunk.item.name,
643
- args: chunk.item.arguments,
644
- id: chunk.item.call_id,
645
- index: chunk.output_index,
646
- });
647
- additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {
648
- [chunk.item.call_id]: chunk.item.id,
649
- };
650
- }
651
- else if (chunk.type === 'response.output_item.done' &&
652
- [
653
- 'web_search_call',
654
- 'file_search_call',
655
- 'computer_call',
656
- 'code_interpreter_call',
657
- 'mcp_call',
658
- 'mcp_list_tools',
659
- 'mcp_approval_request',
660
- 'image_generation_call',
661
- ].includes(chunk.item.type)) {
662
- additional_kwargs.tool_outputs = [chunk.item];
663
- }
664
- else if (chunk.type === 'response.created') {
665
- response_metadata.id = chunk.response.id;
666
- response_metadata.model_name = chunk.response.model;
667
- response_metadata.model = chunk.response.model;
668
- }
669
- else if (chunk.type === 'response.completed') {
670
- const msg = _convertOpenAIResponsesMessageToBaseMessage(chunk.response);
671
- usage_metadata = chunk.response.usage;
672
- if (chunk.response.text?.format?.type === 'json_schema') {
673
- additional_kwargs.parsed ??= JSON.parse(msg.text);
674
- }
675
- for (const [key, value] of Object.entries(chunk.response)) {
676
- if (key !== 'id')
677
- response_metadata[key] = value;
678
- }
679
- }
680
- else if (chunk.type === 'response.function_call_arguments.delta') {
681
- tool_call_chunks.push({
682
- type: 'tool_call_chunk',
683
- args: chunk.delta,
684
- index: chunk.output_index,
685
- });
686
- }
687
- else if (chunk.type === 'response.web_search_call.completed' ||
688
- chunk.type === 'response.file_search_call.completed') {
689
- generationInfo = {
690
- tool_outputs: {
691
- id: chunk.item_id,
692
- type: chunk.type.replace('response.', '').replace('.completed', ''),
693
- status: 'completed',
694
- },
695
- };
696
- }
697
- else if (chunk.type === 'response.refusal.done') {
698
- additional_kwargs.refusal = chunk.refusal;
699
- }
700
- else if (chunk.type === 'response.output_item.added' &&
701
- 'item' in chunk &&
702
- chunk.item.type === 'reasoning') {
703
- const summary = chunk
704
- .item.summary
705
- ? chunk.item.summary.map((s, index) => ({
706
- ...s,
707
- index,
708
- }))
709
- : undefined;
710
- additional_kwargs.reasoning = {
711
- // We only capture ID in the first chunk or else the concatenated result of all chunks will
712
- // have an ID field that is repeated once per chunk. There is special handling for the `type`
713
- // field that prevents this, however.
714
- id: chunk.item.id,
715
- type: chunk.item.type,
716
- ...(summary ? { summary } : {}),
717
- };
718
- }
719
- else if (chunk.type === 'response.reasoning_summary_part.added') {
720
- additional_kwargs.reasoning = {
721
- type: 'reasoning',
722
- summary: [{ ...chunk.part, index: chunk.summary_index }],
723
- };
724
- }
725
- else if (chunk.type === 'response.reasoning_summary_text.delta') {
726
- additional_kwargs.reasoning = {
727
- type: 'reasoning',
728
- summary: [
729
- { text: chunk.delta, type: 'summary_text', index: chunk.summary_index },
730
- ],
731
- };
732
- /** @ts-ignore */
733
- }
734
- else if (chunk.type === 'response.image_generation_call.partial_image') {
735
- // noop/fixme: retaining partial images in a message chunk means that _all_
736
- // partial images get kept in history, so we don't do anything here.
737
- return null;
738
- }
739
- else {
740
- return null;
741
- }
742
- return new ChatGenerationChunk({
743
- // Legacy reasons, `onLLMNewToken` should pulls this out
744
- text: content.map((part) => part.text).join(''),
745
- message: new AIMessageChunk({
746
- id,
747
- content,
748
- tool_call_chunks,
749
- usage_metadata,
750
- additional_kwargs,
751
- response_metadata,
752
- }),
753
- generationInfo,
754
- });
755
- }
756
- //# sourceMappingURL=index.js.map