illuma-agents 1.0.7 → 1.0.9

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 (237) hide show
  1. package/LICENSE +1 -5
  2. package/dist/cjs/common/enum.cjs +1 -2
  3. package/dist/cjs/common/enum.cjs.map +1 -1
  4. package/dist/cjs/instrumentation.cjs.map +1 -1
  5. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  6. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -2
  7. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  8. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +99 -0
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -0
  11. package/dist/cjs/llm/fake.cjs.map +1 -1
  12. package/dist/cjs/llm/google/index.cjs +78 -9
  13. package/dist/cjs/llm/google/index.cjs.map +1 -1
  14. package/dist/cjs/llm/google/utils/common.cjs +185 -28
  15. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  16. package/dist/cjs/llm/providers.cjs +13 -16
  17. package/dist/cjs/llm/providers.cjs.map +1 -1
  18. package/dist/cjs/llm/text.cjs.map +1 -1
  19. package/dist/cjs/messages/core.cjs +14 -14
  20. package/dist/cjs/messages/core.cjs.map +1 -1
  21. package/dist/cjs/messages/ids.cjs.map +1 -1
  22. package/dist/cjs/messages/prune.cjs.map +1 -1
  23. package/dist/cjs/run.cjs +10 -1
  24. package/dist/cjs/run.cjs.map +1 -1
  25. package/dist/cjs/splitStream.cjs.map +1 -1
  26. package/dist/cjs/stream.cjs +4 -1
  27. package/dist/cjs/stream.cjs.map +1 -1
  28. package/dist/cjs/tools/ToolNode.cjs +163 -55
  29. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  30. package/dist/cjs/tools/handlers.cjs +29 -25
  31. package/dist/cjs/tools/handlers.cjs.map +1 -1
  32. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  33. package/dist/cjs/tools/search/content.cjs.map +1 -1
  34. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  35. package/dist/cjs/tools/search/format.cjs.map +1 -1
  36. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  37. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  38. package/dist/cjs/tools/search/schema.cjs +25 -25
  39. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  40. package/dist/cjs/tools/search/search.cjs +6 -1
  41. package/dist/cjs/tools/search/search.cjs.map +1 -1
  42. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  43. package/dist/cjs/tools/search/tool.cjs +162 -35
  44. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  45. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  46. package/dist/cjs/utils/graph.cjs.map +1 -1
  47. package/dist/cjs/utils/llm.cjs +0 -1
  48. package/dist/cjs/utils/llm.cjs.map +1 -1
  49. package/dist/cjs/utils/misc.cjs.map +1 -1
  50. package/dist/cjs/utils/run.cjs.map +1 -1
  51. package/dist/cjs/utils/title.cjs +7 -7
  52. package/dist/cjs/utils/title.cjs.map +1 -1
  53. package/dist/esm/common/enum.mjs +1 -2
  54. package/dist/esm/common/enum.mjs.map +1 -1
  55. package/dist/esm/instrumentation.mjs.map +1 -1
  56. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  57. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -2
  58. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  59. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  60. package/dist/esm/llm/bedrock/index.mjs +97 -0
  61. package/dist/esm/llm/bedrock/index.mjs.map +1 -0
  62. package/dist/esm/llm/fake.mjs.map +1 -1
  63. package/dist/esm/llm/google/index.mjs +79 -10
  64. package/dist/esm/llm/google/index.mjs.map +1 -1
  65. package/dist/esm/llm/google/utils/common.mjs +184 -30
  66. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  67. package/dist/esm/llm/providers.mjs +2 -5
  68. package/dist/esm/llm/providers.mjs.map +1 -1
  69. package/dist/esm/llm/text.mjs.map +1 -1
  70. package/dist/esm/messages/core.mjs +14 -14
  71. package/dist/esm/messages/core.mjs.map +1 -1
  72. package/dist/esm/messages/ids.mjs.map +1 -1
  73. package/dist/esm/messages/prune.mjs.map +1 -1
  74. package/dist/esm/run.mjs +10 -1
  75. package/dist/esm/run.mjs.map +1 -1
  76. package/dist/esm/splitStream.mjs.map +1 -1
  77. package/dist/esm/stream.mjs +4 -1
  78. package/dist/esm/stream.mjs.map +1 -1
  79. package/dist/esm/tools/ToolNode.mjs +164 -56
  80. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  81. package/dist/esm/tools/handlers.mjs +30 -26
  82. package/dist/esm/tools/handlers.mjs.map +1 -1
  83. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  84. package/dist/esm/tools/search/content.mjs.map +1 -1
  85. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  86. package/dist/esm/tools/search/format.mjs.map +1 -1
  87. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  88. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  89. package/dist/esm/tools/search/schema.mjs +25 -25
  90. package/dist/esm/tools/search/schema.mjs.map +1 -1
  91. package/dist/esm/tools/search/search.mjs +6 -1
  92. package/dist/esm/tools/search/search.mjs.map +1 -1
  93. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  94. package/dist/esm/tools/search/tool.mjs +162 -35
  95. package/dist/esm/tools/search/tool.mjs.map +1 -1
  96. package/dist/esm/tools/search/utils.mjs.map +1 -1
  97. package/dist/esm/utils/graph.mjs.map +1 -1
  98. package/dist/esm/utils/llm.mjs +0 -1
  99. package/dist/esm/utils/llm.mjs.map +1 -1
  100. package/dist/esm/utils/misc.mjs.map +1 -1
  101. package/dist/esm/utils/run.mjs.map +1 -1
  102. package/dist/esm/utils/title.mjs +7 -7
  103. package/dist/esm/utils/title.mjs.map +1 -1
  104. package/dist/types/common/enum.d.ts +1 -2
  105. package/dist/types/llm/bedrock/index.d.ts +36 -0
  106. package/dist/types/llm/google/index.d.ts +10 -0
  107. package/dist/types/llm/google/types.d.ts +11 -1
  108. package/dist/types/llm/google/utils/common.d.ts +17 -2
  109. package/dist/types/tools/ToolNode.d.ts +9 -1
  110. package/dist/types/tools/search/types.d.ts +2 -0
  111. package/dist/types/types/llm.d.ts +3 -8
  112. package/dist/types/types/tools.d.ts +1 -1
  113. package/package.json +15 -11
  114. package/src/common/enum.ts +1 -2
  115. package/src/common/index.ts +1 -1
  116. package/src/instrumentation.ts +22 -22
  117. package/src/llm/anthropic/llm.spec.ts +1442 -1442
  118. package/src/llm/anthropic/types.ts +140 -140
  119. package/src/llm/anthropic/utils/message_inputs.ts +757 -660
  120. package/src/llm/anthropic/utils/output_parsers.ts +133 -133
  121. package/src/llm/anthropic/utils/tools.ts +29 -29
  122. package/src/llm/bedrock/index.ts +128 -0
  123. package/src/llm/fake.ts +133 -133
  124. package/src/llm/google/data/gettysburg10.wav +0 -0
  125. package/src/llm/google/data/hotdog.jpg +0 -0
  126. package/src/llm/google/index.ts +129 -14
  127. package/src/llm/google/llm.spec.ts +932 -0
  128. package/src/llm/google/types.ts +56 -43
  129. package/src/llm/google/utils/common.ts +873 -660
  130. package/src/llm/google/utils/tools.ts +160 -160
  131. package/src/llm/openai/types.ts +24 -24
  132. package/src/llm/openai/utils/isReasoningModel.test.ts +90 -90
  133. package/src/llm/providers.ts +2 -7
  134. package/src/llm/text.ts +94 -94
  135. package/src/messages/core.ts +463 -463
  136. package/src/messages/formatAgentMessages.tools.test.ts +400 -400
  137. package/src/messages/formatMessage.test.ts +693 -693
  138. package/src/messages/ids.ts +26 -26
  139. package/src/messages/prune.ts +567 -567
  140. package/src/messages/shiftIndexTokenCountMap.test.ts +81 -81
  141. package/src/mockStream.ts +98 -98
  142. package/src/prompts/collab.ts +5 -5
  143. package/src/prompts/index.ts +1 -1
  144. package/src/prompts/taskmanager.ts +61 -61
  145. package/src/run.ts +13 -4
  146. package/src/scripts/ant_web_search_edge_case.ts +162 -0
  147. package/src/scripts/ant_web_search_error_edge_case.ts +148 -0
  148. package/src/scripts/args.ts +48 -48
  149. package/src/scripts/caching.ts +123 -123
  150. package/src/scripts/code_exec_files.ts +193 -193
  151. package/src/scripts/empty_input.ts +137 -137
  152. package/src/scripts/image.ts +178 -178
  153. package/src/scripts/memory.ts +97 -97
  154. package/src/scripts/thinking.ts +149 -149
  155. package/src/specs/anthropic.simple.test.ts +67 -0
  156. package/src/specs/spec.utils.ts +3 -3
  157. package/src/specs/token-distribution-edge-case.test.ts +316 -316
  158. package/src/specs/tool-error.test.ts +193 -193
  159. package/src/splitStream.test.ts +691 -691
  160. package/src/splitStream.ts +234 -234
  161. package/src/stream.test.ts +94 -94
  162. package/src/stream.ts +4 -1
  163. package/src/tools/ToolNode.ts +206 -64
  164. package/src/tools/handlers.ts +32 -28
  165. package/src/tools/search/anthropic.ts +51 -51
  166. package/src/tools/search/content.test.ts +173 -173
  167. package/src/tools/search/content.ts +147 -147
  168. package/src/tools/search/direct-url.test.ts +530 -0
  169. package/src/tools/search/firecrawl.ts +210 -210
  170. package/src/tools/search/format.ts +250 -250
  171. package/src/tools/search/highlights.ts +320 -320
  172. package/src/tools/search/index.ts +2 -2
  173. package/src/tools/search/jina-reranker.test.ts +126 -126
  174. package/src/tools/search/output.md +2775 -2775
  175. package/src/tools/search/rerankers.ts +242 -242
  176. package/src/tools/search/schema.ts +63 -63
  177. package/src/tools/search/search.ts +766 -759
  178. package/src/tools/search/serper-scraper.ts +155 -155
  179. package/src/tools/search/test.html +883 -883
  180. package/src/tools/search/test.md +642 -642
  181. package/src/tools/search/test.ts +159 -159
  182. package/src/tools/search/tool.ts +619 -471
  183. package/src/tools/search/types.ts +689 -687
  184. package/src/tools/search/utils.ts +79 -79
  185. package/src/types/index.ts +6 -6
  186. package/src/types/llm.ts +2 -8
  187. package/src/types/tools.ts +80 -80
  188. package/src/utils/graph.ts +10 -10
  189. package/src/utils/llm.ts +26 -27
  190. package/src/utils/llmConfig.ts +5 -3
  191. package/src/utils/logging.ts +48 -48
  192. package/src/utils/misc.ts +57 -57
  193. package/src/utils/run.ts +100 -100
  194. package/src/utils/title.ts +165 -165
  195. package/dist/cjs/llm/ollama/index.cjs +0 -70
  196. package/dist/cjs/llm/ollama/index.cjs.map +0 -1
  197. package/dist/cjs/llm/ollama/utils.cjs +0 -158
  198. package/dist/cjs/llm/ollama/utils.cjs.map +0 -1
  199. package/dist/esm/llm/ollama/index.mjs +0 -68
  200. package/dist/esm/llm/ollama/index.mjs.map +0 -1
  201. package/dist/esm/llm/ollama/utils.mjs +0 -155
  202. package/dist/esm/llm/ollama/utils.mjs.map +0 -1
  203. package/dist/types/llm/ollama/index.d.ts +0 -8
  204. package/dist/types/llm/ollama/utils.d.ts +0 -7
  205. package/src/llm/ollama/index.ts +0 -92
  206. package/src/llm/ollama/utils.ts +0 -193
  207. package/src/proto/CollabGraph.ts +0 -269
  208. package/src/proto/TaskManager.ts +0 -243
  209. package/src/proto/collab.ts +0 -200
  210. package/src/proto/collab_design.ts +0 -184
  211. package/src/proto/collab_design_v2.ts +0 -224
  212. package/src/proto/collab_design_v3.ts +0 -255
  213. package/src/proto/collab_design_v4.ts +0 -220
  214. package/src/proto/collab_design_v5.ts +0 -251
  215. package/src/proto/collab_graph.ts +0 -181
  216. package/src/proto/collab_original.ts +0 -123
  217. package/src/proto/example.ts +0 -93
  218. package/src/proto/example_new.ts +0 -68
  219. package/src/proto/example_old.ts +0 -201
  220. package/src/proto/example_test.ts +0 -152
  221. package/src/proto/example_test_anthropic.ts +0 -100
  222. package/src/proto/log_stream.ts +0 -202
  223. package/src/proto/main_collab_community_event.ts +0 -133
  224. package/src/proto/main_collab_design_v2.ts +0 -96
  225. package/src/proto/main_collab_design_v4.ts +0 -100
  226. package/src/proto/main_collab_design_v5.ts +0 -135
  227. package/src/proto/main_collab_global_analysis.ts +0 -122
  228. package/src/proto/main_collab_hackathon_event.ts +0 -153
  229. package/src/proto/main_collab_space_mission.ts +0 -153
  230. package/src/proto/main_philosophy.ts +0 -210
  231. package/src/proto/original_script.ts +0 -126
  232. package/src/proto/standard.ts +0 -100
  233. package/src/proto/stream.ts +0 -56
  234. package/src/proto/tasks.ts +0 -118
  235. package/src/proto/tools/global_analysis_tools.ts +0 -86
  236. package/src/proto/tools/space_mission_tools.ts +0 -60
  237. package/src/proto/vertexai.ts +0 -54
@@ -1,660 +1,757 @@
1
- /* eslint-disable @typescript-eslint/explicit-function-return-type */
2
- /* eslint-disable no-console */
3
- /**
4
- * This util file contains functions for converting LangChain messages to Anthropic messages.
5
- */
6
- import {
7
- type BaseMessage,
8
- type SystemMessage,
9
- HumanMessage,
10
- type AIMessage,
11
- type ToolMessage,
12
- isAIMessage,
13
- type StandardContentBlockConverter,
14
- type StandardTextBlock,
15
- type StandardImageBlock,
16
- type StandardFileBlock,
17
- MessageContentComplex,
18
- isDataContentBlock,
19
- convertToProviderContentBlock,
20
- parseBase64DataUrl,
21
- } from '@langchain/core/messages';
22
- import { ToolCall } from '@langchain/core/messages/tool';
23
- import {
24
- AnthropicImageBlockParam,
25
- AnthropicMessageCreateParams,
26
- AnthropicTextBlockParam,
27
- AnthropicToolResultBlockParam,
28
- AnthropicToolUseBlockParam,
29
- AnthropicDocumentBlockParam,
30
- AnthropicThinkingBlockParam,
31
- AnthropicRedactedThinkingBlockParam,
32
- AnthropicServerToolUseBlockParam,
33
- AnthropicWebSearchToolResultBlockParam,
34
- isAnthropicImageBlockParam,
35
- AnthropicSearchResultBlockParam,
36
- AnthropicToolResponse,
37
- } from '../types';
38
-
39
- function _formatImage(imageUrl: string) {
40
- const parsed = parseBase64DataUrl({ dataUrl: imageUrl });
41
- if (parsed) {
42
- return {
43
- type: 'base64',
44
- media_type: parsed.mime_type,
45
- data: parsed.data,
46
- };
47
- }
48
- let parsedUrl: URL;
49
-
50
- try {
51
- parsedUrl = new URL(imageUrl);
52
- } catch {
53
- throw new Error(
54
- [
55
- `Malformed image URL: ${JSON.stringify(
56
- imageUrl
57
- )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,
58
- 'Example: data:image/png;base64,/9j/4AAQSk...',
59
- 'Example: https://example.com/image.jpg',
60
- ].join('\n\n')
61
- );
62
- }
63
-
64
- if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
65
- return {
66
- type: 'url',
67
- url: imageUrl,
68
- };
69
- }
70
-
71
- throw new Error(
72
- [
73
- `Invalid image URL protocol: ${JSON.stringify(
74
- parsedUrl.protocol
75
- )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,
76
- 'Example: data:image/png;base64,/9j/4AAQSk...',
77
- 'Example: https://example.com/image.jpg',
78
- ].join('\n\n')
79
- );
80
- }
81
-
82
- function _ensureMessageContents(
83
- messages: BaseMessage[]
84
- ): (SystemMessage | HumanMessage | AIMessage)[] {
85
- // Merge runs of human/tool messages into single human messages with content blocks.
86
- const updatedMsgs = [];
87
- for (const message of messages) {
88
- if (message._getType() === 'tool') {
89
- if (typeof message.content === 'string') {
90
- const previousMessage = updatedMsgs[updatedMsgs.length - 1];
91
- if (
92
- previousMessage._getType() === 'human' &&
93
- Array.isArray(previousMessage.content) &&
94
- 'type' in previousMessage.content[0] &&
95
- previousMessage.content[0].type === 'tool_result'
96
- ) {
97
- // If the previous message was a tool result, we merge this tool message into it.
98
- (previousMessage.content as MessageContentComplex[]).push({
99
- type: 'tool_result',
100
- content: message.content,
101
- tool_use_id: (message as ToolMessage).tool_call_id,
102
- });
103
- } else {
104
- // If not, we create a new human message with the tool result.
105
- updatedMsgs.push(
106
- new HumanMessage({
107
- content: [
108
- {
109
- type: 'tool_result',
110
- content: message.content,
111
- tool_use_id: (message as ToolMessage).tool_call_id,
112
- },
113
- ],
114
- })
115
- );
116
- }
117
- } else {
118
- updatedMsgs.push(
119
- new HumanMessage({
120
- content: [
121
- {
122
- type: 'tool_result',
123
- // rare case: message.content could be undefined
124
- ...(message.content != null
125
- ? { content: _formatContent(message) }
126
- : {}),
127
- tool_use_id: (message as ToolMessage).tool_call_id,
128
- },
129
- ],
130
- })
131
- );
132
- }
133
- } else {
134
- updatedMsgs.push(message);
135
- }
136
- }
137
- return updatedMsgs;
138
- }
139
-
140
- export function _convertLangChainToolCallToAnthropic(
141
- toolCall: ToolCall
142
- ): AnthropicToolResponse {
143
- if (toolCall.id === undefined) {
144
- throw new Error('Anthropic requires all tool calls to have an "id".');
145
- }
146
- return {
147
- type: 'tool_use',
148
- id: toolCall.id,
149
- name: toolCall.name,
150
- input: toolCall.args,
151
- };
152
- }
153
-
154
- const standardContentBlockConverter: StandardContentBlockConverter<{
155
- text: AnthropicTextBlockParam;
156
- image: AnthropicImageBlockParam;
157
- file: AnthropicDocumentBlockParam;
158
- }> = {
159
- providerName: 'anthropic',
160
-
161
- fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {
162
- return {
163
- type: 'text',
164
- text: block.text,
165
- ...('citations' in (block.metadata ?? {})
166
- ? { citations: block.metadata!.citations }
167
- : {}),
168
- ...('cache_control' in (block.metadata ?? {})
169
- ? { cache_control: block.metadata!.cache_control }
170
- : {}),
171
- } as AnthropicTextBlockParam;
172
- },
173
-
174
- fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {
175
- if (block.source_type === 'url') {
176
- const data = parseBase64DataUrl({
177
- dataUrl: block.url,
178
- asTypedArray: false,
179
- });
180
- if (data) {
181
- return {
182
- type: 'image',
183
- source: {
184
- type: 'base64',
185
- data: data.data,
186
- media_type: data.mime_type,
187
- },
188
- ...('cache_control' in (block.metadata ?? {})
189
- ? { cache_control: block.metadata!.cache_control }
190
- : {}),
191
- } as AnthropicImageBlockParam;
192
- } else {
193
- return {
194
- type: 'image',
195
- source: {
196
- type: 'url',
197
- url: block.url,
198
- media_type: block.mime_type ?? '',
199
- },
200
- ...('cache_control' in (block.metadata ?? {})
201
- ? { cache_control: block.metadata!.cache_control }
202
- : {}),
203
- } as AnthropicImageBlockParam;
204
- }
205
- } else {
206
- if (block.source_type === 'base64') {
207
- return {
208
- type: 'image',
209
- source: {
210
- type: 'base64',
211
- data: block.data,
212
- media_type: block.mime_type ?? '',
213
- },
214
- ...('cache_control' in (block.metadata ?? {})
215
- ? { cache_control: block.metadata!.cache_control }
216
- : {}),
217
- } as AnthropicImageBlockParam;
218
- } else {
219
- throw new Error(`Unsupported image source type: ${block.source_type}`);
220
- }
221
- }
222
- },
223
-
224
- fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {
225
- const mime_type = (block.mime_type ?? '').split(';')[0];
226
-
227
- if (block.source_type === 'url') {
228
- if (mime_type === 'application/pdf' || mime_type === '') {
229
- return {
230
- type: 'document',
231
- source: {
232
- type: 'url',
233
- url: block.url,
234
- media_type: block.mime_type ?? '',
235
- },
236
- ...('cache_control' in (block.metadata ?? {})
237
- ? { cache_control: block.metadata!.cache_control }
238
- : {}),
239
- ...('citations' in (block.metadata ?? {})
240
- ? { citations: block.metadata!.citations }
241
- : {}),
242
- ...('context' in (block.metadata ?? {})
243
- ? { context: block.metadata!.context }
244
- : {}),
245
- ...('title' in (block.metadata ?? {})
246
- ? { title: block.metadata!.title }
247
- : {}),
248
- } as AnthropicDocumentBlockParam;
249
- }
250
- throw new Error(
251
- `Unsupported file mime type for file url source: ${block.mime_type}`
252
- );
253
- } else if (block.source_type === 'text') {
254
- if (mime_type === 'text/plain' || mime_type === '') {
255
- return {
256
- type: 'document',
257
- source: {
258
- type: 'text',
259
- data: block.text,
260
- media_type: block.mime_type ?? '',
261
- },
262
- ...('cache_control' in (block.metadata ?? {})
263
- ? { cache_control: block.metadata!.cache_control }
264
- : {}),
265
- ...('citations' in (block.metadata ?? {})
266
- ? { citations: block.metadata!.citations }
267
- : {}),
268
- ...('context' in (block.metadata ?? {})
269
- ? { context: block.metadata!.context }
270
- : {}),
271
- ...('title' in (block.metadata ?? {})
272
- ? { title: block.metadata!.title }
273
- : {}),
274
- } as AnthropicDocumentBlockParam;
275
- } else {
276
- throw new Error(
277
- `Unsupported file mime type for file text source: ${block.mime_type}`
278
- );
279
- }
280
- } else if (block.source_type === 'base64') {
281
- if (mime_type === 'application/pdf' || mime_type === '') {
282
- return {
283
- type: 'document',
284
- source: {
285
- type: 'base64',
286
- data: block.data,
287
- media_type: 'application/pdf',
288
- },
289
- ...('cache_control' in (block.metadata ?? {})
290
- ? { cache_control: block.metadata!.cache_control }
291
- : {}),
292
- ...('citations' in (block.metadata ?? {})
293
- ? { citations: block.metadata!.citations }
294
- : {}),
295
- ...('context' in (block.metadata ?? {})
296
- ? { context: block.metadata!.context }
297
- : {}),
298
- ...('title' in (block.metadata ?? {})
299
- ? { title: block.metadata!.title }
300
- : {}),
301
- } as AnthropicDocumentBlockParam;
302
- } else if (
303
- ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(
304
- mime_type
305
- )
306
- ) {
307
- return {
308
- type: 'document',
309
- source: {
310
- type: 'content',
311
- content: [
312
- {
313
- type: 'image',
314
- source: {
315
- type: 'base64',
316
- data: block.data,
317
- media_type: mime_type as
318
- | 'image/jpeg'
319
- | 'image/png'
320
- | 'image/gif'
321
- | 'image/webp',
322
- },
323
- },
324
- ],
325
- },
326
- ...('cache_control' in (block.metadata ?? {})
327
- ? { cache_control: block.metadata!.cache_control }
328
- : {}),
329
- ...('citations' in (block.metadata ?? {})
330
- ? { citations: block.metadata!.citations }
331
- : {}),
332
- ...('context' in (block.metadata ?? {})
333
- ? { context: block.metadata!.context }
334
- : {}),
335
- ...('title' in (block.metadata ?? {})
336
- ? { title: block.metadata!.title }
337
- : {}),
338
- } as AnthropicDocumentBlockParam;
339
- } else {
340
- throw new Error(
341
- `Unsupported file mime type for file base64 source: ${block.mime_type}`
342
- );
343
- }
344
- } else {
345
- throw new Error(`Unsupported file source type: ${block.source_type}`);
346
- }
347
- },
348
- };
349
-
350
- function _formatContent(message: BaseMessage) {
351
- const toolTypes = [
352
- 'tool_use',
353
- 'tool_result',
354
- 'input_json_delta',
355
- 'server_tool_use',
356
- 'web_search_tool_result',
357
- 'web_search_result',
358
- ];
359
- const textTypes = ['text', 'text_delta'];
360
- const { content } = message;
361
-
362
- if (typeof content === 'string') {
363
- return content;
364
- } else {
365
- const contentBlocks = content.map((contentPart) => {
366
- if (isDataContentBlock(contentPart)) {
367
- return convertToProviderContentBlock(
368
- contentPart,
369
- standardContentBlockConverter
370
- );
371
- }
372
-
373
- const cacheControl =
374
- 'cache_control' in contentPart ? contentPart.cache_control : undefined;
375
-
376
- if (contentPart.type === 'image_url') {
377
- let source;
378
- if (typeof contentPart.image_url === 'string') {
379
- source = _formatImage(contentPart.image_url);
380
- } else {
381
- source = _formatImage(contentPart.image_url.url);
382
- }
383
- return {
384
- type: 'image' as const, // Explicitly setting the type as "image"
385
- source,
386
- ...(cacheControl ? { cache_control: cacheControl } : {}),
387
- };
388
- } else if (isAnthropicImageBlockParam(contentPart)) {
389
- return contentPart;
390
- } else if (contentPart.type === 'document') {
391
- // PDF
392
- return {
393
- ...contentPart,
394
- ...(cacheControl ? { cache_control: cacheControl } : {}),
395
- };
396
- } else if (contentPart.type === 'thinking') {
397
- const block: AnthropicThinkingBlockParam = {
398
- type: 'thinking' as const, // Explicitly setting the type as "thinking"
399
- thinking: contentPart.thinking,
400
- signature: contentPart.signature,
401
- ...(cacheControl ? { cache_control: cacheControl } : {}),
402
- };
403
- return block;
404
- } else if (contentPart.type === 'redacted_thinking') {
405
- const block: AnthropicRedactedThinkingBlockParam = {
406
- type: 'redacted_thinking' as const, // Explicitly setting the type as "redacted_thinking"
407
- data: contentPart.data,
408
- ...(cacheControl ? { cache_control: cacheControl } : {}),
409
- };
410
- return block;
411
- } else if (contentPart.type === 'search_result') {
412
- const block: AnthropicSearchResultBlockParam = {
413
- type: 'search_result' as const, // Explicitly setting the type as "search_result"
414
- title: contentPart.title,
415
- source: contentPart.source,
416
- ...('cache_control' in contentPart && contentPart.cache_control
417
- ? { cache_control: contentPart.cache_control }
418
- : {}),
419
- ...('citations' in contentPart && contentPart.citations
420
- ? { citations: contentPart.citations }
421
- : {}),
422
- content: contentPart.content,
423
- };
424
- return block;
425
- } else if (
426
- textTypes.find((t) => t === contentPart.type) &&
427
- 'text' in contentPart
428
- ) {
429
- // Assuming contentPart is of type MessageContentText here
430
- return {
431
- type: 'text' as const, // Explicitly setting the type as "text"
432
- text: contentPart.text,
433
- ...(cacheControl ? { cache_control: cacheControl } : {}),
434
- ...('citations' in contentPart && contentPart.citations
435
- ? { citations: contentPart.citations }
436
- : {}),
437
- };
438
- } else if (toolTypes.find((t) => t === contentPart.type)) {
439
- const contentPartCopy = { ...contentPart };
440
- if ('index' in contentPartCopy) {
441
- // Anthropic does not support passing the index field here, so we remove it.
442
- delete contentPartCopy.index;
443
- }
444
-
445
- if (contentPartCopy.type === 'input_json_delta') {
446
- // `input_json_delta` type only represents yielding partial tool inputs
447
- // and is not a valid type for Anthropic messages.
448
- contentPartCopy.type = 'tool_use';
449
- }
450
-
451
- if ('input' in contentPartCopy) {
452
- // Anthropic tool use inputs should be valid objects, when applicable.
453
- if (typeof contentPartCopy.input === 'string') {
454
- try {
455
- contentPartCopy.input = JSON.parse(contentPartCopy.input);
456
- } catch {
457
- contentPartCopy.input = {};
458
- }
459
- }
460
- }
461
-
462
- // TODO: Fix when SDK types are fixed
463
- return {
464
- ...contentPartCopy,
465
- ...(cacheControl ? { cache_control: cacheControl } : {}),
466
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
467
- } as any;
468
- } else if (
469
- 'functionCall' in contentPart &&
470
- contentPart.functionCall &&
471
- typeof contentPart.functionCall === 'object' &&
472
- isAIMessage(message)
473
- ) {
474
- const correspondingToolCall = message.tool_calls?.find(
475
- (toolCall) => toolCall.name === contentPart.functionCall.name
476
- );
477
- if (!correspondingToolCall) {
478
- throw new Error(
479
- `Could not find tool call for function call ${contentPart.functionCall.name}`
480
- );
481
- }
482
- // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.
483
- return {
484
- id: correspondingToolCall.id,
485
- type: 'tool_use',
486
- name: correspondingToolCall.name,
487
- input: contentPart.functionCall.args,
488
- };
489
- } else {
490
- throw new Error('Unsupported message content format');
491
- }
492
- });
493
- return contentBlocks;
494
- }
495
- }
496
-
497
- /**
498
- * Formats messages as a prompt for the model.
499
- * Used in LangSmith, export is important here.
500
- * @param messages The base messages to format as a prompt.
501
- * @returns The formatted prompt.
502
- */
503
- export function _convertMessagesToAnthropicPayload(
504
- messages: BaseMessage[]
505
- ): AnthropicMessageCreateParams {
506
- const mergedMessages = _ensureMessageContents(messages);
507
- let system;
508
- if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {
509
- system = messages[0].content;
510
- }
511
- const conversationMessages =
512
- system !== undefined ? mergedMessages.slice(1) : mergedMessages;
513
- const formattedMessages = conversationMessages.map((message) => {
514
- let role;
515
- if (message._getType() === 'human') {
516
- role = 'user' as const;
517
- } else if (message._getType() === 'ai') {
518
- role = 'assistant' as const;
519
- } else if (message._getType() === 'tool') {
520
- role = 'user' as const;
521
- } else if (message._getType() === 'system') {
522
- throw new Error(
523
- 'System messages are only permitted as the first passed message.'
524
- );
525
- } else {
526
- throw new Error(`Message type "${message._getType()}" is not supported.`);
527
- }
528
- if (isAIMessage(message) && !!message.tool_calls?.length) {
529
- if (typeof message.content === 'string') {
530
- if (message.content === '') {
531
- return {
532
- role,
533
- content: message.tool_calls.map(
534
- _convertLangChainToolCallToAnthropic
535
- ),
536
- };
537
- } else {
538
- return {
539
- role,
540
- content: [
541
- { type: 'text', text: message.content },
542
- ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),
543
- ],
544
- };
545
- }
546
- } else {
547
- const { content } = message;
548
- const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>
549
- content.find(
550
- (contentPart) =>
551
- (contentPart.type === 'tool_use' ||
552
- contentPart.type === 'input_json_delta' ||
553
- contentPart.type === 'server_tool_use') &&
554
- contentPart.id === toolCall.id
555
- )
556
- );
557
- if (hasMismatchedToolCalls) {
558
- console.warn(
559
- 'The "tool_calls" field on a message is only respected if content is a string.'
560
- );
561
- }
562
- return {
563
- role,
564
- content: _formatContent(message),
565
- };
566
- }
567
- } else {
568
- return {
569
- role,
570
- content: _formatContent(message),
571
- };
572
- }
573
- });
574
- return {
575
- messages: mergeMessages(formattedMessages),
576
- system,
577
- } as AnthropicMessageCreateParams;
578
- }
579
-
580
- function mergeMessages(messages: AnthropicMessageCreateParams['messages']) {
581
- if (!messages || messages.length <= 1) {
582
- return messages;
583
- }
584
-
585
- const result: AnthropicMessageCreateParams['messages'] = [];
586
- let currentMessage = messages[0];
587
-
588
- const normalizeContent = (
589
- content:
590
- | string
591
- | Array<
592
- | AnthropicTextBlockParam
593
- | AnthropicImageBlockParam
594
- | AnthropicToolUseBlockParam
595
- | AnthropicToolResultBlockParam
596
- | AnthropicDocumentBlockParam
597
- | AnthropicThinkingBlockParam
598
- | AnthropicRedactedThinkingBlockParam
599
- | AnthropicServerToolUseBlockParam
600
- | AnthropicWebSearchToolResultBlockParam
601
- >
602
- ): Array<
603
- | AnthropicTextBlockParam
604
- | AnthropicImageBlockParam
605
- | AnthropicToolUseBlockParam
606
- | AnthropicToolResultBlockParam
607
- | AnthropicDocumentBlockParam
608
- | AnthropicThinkingBlockParam
609
- | AnthropicRedactedThinkingBlockParam
610
- | AnthropicServerToolUseBlockParam
611
- | AnthropicWebSearchToolResultBlockParam
612
- > => {
613
- if (typeof content === 'string') {
614
- return [
615
- {
616
- type: 'text',
617
- text: content,
618
- },
619
- ];
620
- }
621
- return content;
622
- };
623
-
624
- const isToolResultMessage = (msg: (typeof messages)[0]) => {
625
- if (msg.role !== 'user') return false;
626
-
627
- if (typeof msg.content === 'string') {
628
- return false;
629
- }
630
-
631
- return (
632
- Array.isArray(msg.content) &&
633
- msg.content.every((item) => item.type === 'tool_result')
634
- );
635
- };
636
-
637
- for (let i = 1; i < messages.length; i += 1) {
638
- const nextMessage = messages[i];
639
-
640
- if (
641
- isToolResultMessage(currentMessage) &&
642
- isToolResultMessage(nextMessage)
643
- ) {
644
- // Merge the messages by combining their content arrays
645
- currentMessage = {
646
- ...currentMessage,
647
- content: [
648
- ...normalizeContent(currentMessage.content),
649
- ...normalizeContent(nextMessage.content),
650
- ],
651
- };
652
- } else {
653
- result.push(currentMessage);
654
- currentMessage = nextMessage;
655
- }
656
- }
657
-
658
- result.push(currentMessage);
659
- return result;
660
- }
1
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
2
+ /* eslint-disable no-console */
3
+ /**
4
+ * This util file contains functions for converting LangChain messages to Anthropic messages.
5
+ */
6
+ import {
7
+ type BaseMessage,
8
+ type SystemMessage,
9
+ HumanMessage,
10
+ type AIMessage,
11
+ type ToolMessage,
12
+ isAIMessage,
13
+ type StandardContentBlockConverter,
14
+ type StandardTextBlock,
15
+ type StandardImageBlock,
16
+ type StandardFileBlock,
17
+ MessageContentComplex,
18
+ isDataContentBlock,
19
+ convertToProviderContentBlock,
20
+ parseBase64DataUrl,
21
+ } from '@langchain/core/messages';
22
+ import { ToolCall } from '@langchain/core/messages/tool';
23
+ import {
24
+ AnthropicImageBlockParam,
25
+ AnthropicMessageCreateParams,
26
+ AnthropicTextBlockParam,
27
+ AnthropicToolResultBlockParam,
28
+ AnthropicToolUseBlockParam,
29
+ AnthropicDocumentBlockParam,
30
+ AnthropicThinkingBlockParam,
31
+ AnthropicRedactedThinkingBlockParam,
32
+ AnthropicServerToolUseBlockParam,
33
+ AnthropicWebSearchToolResultBlockParam,
34
+ isAnthropicImageBlockParam,
35
+ AnthropicSearchResultBlockParam,
36
+ AnthropicToolResponse,
37
+ } from '../types';
38
+
39
+ function _formatImage(imageUrl: string) {
40
+ const parsed = parseBase64DataUrl({ dataUrl: imageUrl });
41
+ if (parsed) {
42
+ return {
43
+ type: 'base64',
44
+ media_type: parsed.mime_type,
45
+ data: parsed.data,
46
+ };
47
+ }
48
+ let parsedUrl: URL;
49
+
50
+ try {
51
+ parsedUrl = new URL(imageUrl);
52
+ } catch {
53
+ throw new Error(
54
+ [
55
+ `Malformed image URL: ${JSON.stringify(
56
+ imageUrl
57
+ )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,
58
+ 'Example: data:image/png;base64,/9j/4AAQSk...',
59
+ 'Example: https://example.com/image.jpg',
60
+ ].join('\n\n')
61
+ );
62
+ }
63
+
64
+ if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
65
+ return {
66
+ type: 'url',
67
+ url: imageUrl,
68
+ };
69
+ }
70
+
71
+ throw new Error(
72
+ [
73
+ `Invalid image URL protocol: ${JSON.stringify(
74
+ parsedUrl.protocol
75
+ )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,
76
+ 'Example: data:image/png;base64,/9j/4AAQSk...',
77
+ 'Example: https://example.com/image.jpg',
78
+ ].join('\n\n')
79
+ );
80
+ }
81
+
82
+ function _ensureMessageContents(
83
+ messages: BaseMessage[]
84
+ ): (SystemMessage | HumanMessage | AIMessage)[] {
85
+ // Merge runs of human/tool messages into single human messages with content blocks.
86
+ const updatedMsgs = [];
87
+ for (const message of messages) {
88
+ if (message._getType() === 'tool') {
89
+ if (typeof message.content === 'string') {
90
+ const previousMessage = updatedMsgs[updatedMsgs.length - 1];
91
+ if (
92
+ previousMessage._getType() === 'human' &&
93
+ Array.isArray(previousMessage.content) &&
94
+ 'type' in previousMessage.content[0] &&
95
+ previousMessage.content[0].type === 'tool_result'
96
+ ) {
97
+ // If the previous message was a tool result, we merge this tool message into it.
98
+ (previousMessage.content as MessageContentComplex[]).push({
99
+ type: 'tool_result',
100
+ content: message.content,
101
+ tool_use_id: (message as ToolMessage).tool_call_id,
102
+ });
103
+ } else {
104
+ // If not, we create a new human message with the tool result.
105
+ updatedMsgs.push(
106
+ new HumanMessage({
107
+ content: [
108
+ {
109
+ type: 'tool_result',
110
+ content: message.content,
111
+ tool_use_id: (message as ToolMessage).tool_call_id,
112
+ },
113
+ ],
114
+ })
115
+ );
116
+ }
117
+ } else {
118
+ updatedMsgs.push(
119
+ new HumanMessage({
120
+ content: [
121
+ {
122
+ type: 'tool_result',
123
+ // rare case: message.content could be undefined
124
+ ...(message.content != null
125
+ ? { content: _formatContent(message) }
126
+ : {}),
127
+ tool_use_id: (message as ToolMessage).tool_call_id,
128
+ },
129
+ ],
130
+ })
131
+ );
132
+ }
133
+ } else {
134
+ updatedMsgs.push(message);
135
+ }
136
+ }
137
+ return updatedMsgs;
138
+ }
139
+
140
+ export function _convertLangChainToolCallToAnthropic(
141
+ toolCall: ToolCall
142
+ ): AnthropicToolResponse {
143
+ if (toolCall.id === undefined) {
144
+ throw new Error('Anthropic requires all tool calls to have an "id".');
145
+ }
146
+ return {
147
+ type: 'tool_use',
148
+ id: toolCall.id,
149
+ name: toolCall.name,
150
+ input: toolCall.args,
151
+ };
152
+ }
153
+
154
+ const standardContentBlockConverter: StandardContentBlockConverter<{
155
+ text: AnthropicTextBlockParam;
156
+ image: AnthropicImageBlockParam;
157
+ file: AnthropicDocumentBlockParam;
158
+ }> = {
159
+ providerName: 'anthropic',
160
+
161
+ fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {
162
+ return {
163
+ type: 'text',
164
+ text: block.text,
165
+ ...('citations' in (block.metadata ?? {})
166
+ ? { citations: block.metadata!.citations }
167
+ : {}),
168
+ ...('cache_control' in (block.metadata ?? {})
169
+ ? { cache_control: block.metadata!.cache_control }
170
+ : {}),
171
+ } as AnthropicTextBlockParam;
172
+ },
173
+
174
+ fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {
175
+ if (block.source_type === 'url') {
176
+ const data = parseBase64DataUrl({
177
+ dataUrl: block.url,
178
+ asTypedArray: false,
179
+ });
180
+ if (data) {
181
+ return {
182
+ type: 'image',
183
+ source: {
184
+ type: 'base64',
185
+ data: data.data,
186
+ media_type: data.mime_type,
187
+ },
188
+ ...('cache_control' in (block.metadata ?? {})
189
+ ? { cache_control: block.metadata!.cache_control }
190
+ : {}),
191
+ } as AnthropicImageBlockParam;
192
+ } else {
193
+ return {
194
+ type: 'image',
195
+ source: {
196
+ type: 'url',
197
+ url: block.url,
198
+ media_type: block.mime_type ?? '',
199
+ },
200
+ ...('cache_control' in (block.metadata ?? {})
201
+ ? { cache_control: block.metadata!.cache_control }
202
+ : {}),
203
+ } as AnthropicImageBlockParam;
204
+ }
205
+ } else {
206
+ if (block.source_type === 'base64') {
207
+ return {
208
+ type: 'image',
209
+ source: {
210
+ type: 'base64',
211
+ data: block.data,
212
+ media_type: block.mime_type ?? '',
213
+ },
214
+ ...('cache_control' in (block.metadata ?? {})
215
+ ? { cache_control: block.metadata!.cache_control }
216
+ : {}),
217
+ } as AnthropicImageBlockParam;
218
+ } else {
219
+ throw new Error(`Unsupported image source type: ${block.source_type}`);
220
+ }
221
+ }
222
+ },
223
+
224
+ fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {
225
+ const mime_type = (block.mime_type ?? '').split(';')[0];
226
+
227
+ if (block.source_type === 'url') {
228
+ if (mime_type === 'application/pdf' || mime_type === '') {
229
+ return {
230
+ type: 'document',
231
+ source: {
232
+ type: 'url',
233
+ url: block.url,
234
+ media_type: block.mime_type ?? '',
235
+ },
236
+ ...('cache_control' in (block.metadata ?? {})
237
+ ? { cache_control: block.metadata!.cache_control }
238
+ : {}),
239
+ ...('citations' in (block.metadata ?? {})
240
+ ? { citations: block.metadata!.citations }
241
+ : {}),
242
+ ...('context' in (block.metadata ?? {})
243
+ ? { context: block.metadata!.context }
244
+ : {}),
245
+ ...('title' in (block.metadata ?? {})
246
+ ? { title: block.metadata!.title }
247
+ : {}),
248
+ } as AnthropicDocumentBlockParam;
249
+ }
250
+ throw new Error(
251
+ `Unsupported file mime type for file url source: ${block.mime_type}`
252
+ );
253
+ } else if (block.source_type === 'text') {
254
+ if (mime_type === 'text/plain' || mime_type === '') {
255
+ return {
256
+ type: 'document',
257
+ source: {
258
+ type: 'text',
259
+ data: block.text,
260
+ media_type: block.mime_type ?? '',
261
+ },
262
+ ...('cache_control' in (block.metadata ?? {})
263
+ ? { cache_control: block.metadata!.cache_control }
264
+ : {}),
265
+ ...('citations' in (block.metadata ?? {})
266
+ ? { citations: block.metadata!.citations }
267
+ : {}),
268
+ ...('context' in (block.metadata ?? {})
269
+ ? { context: block.metadata!.context }
270
+ : {}),
271
+ ...('title' in (block.metadata ?? {})
272
+ ? { title: block.metadata!.title }
273
+ : {}),
274
+ } as AnthropicDocumentBlockParam;
275
+ } else {
276
+ throw new Error(
277
+ `Unsupported file mime type for file text source: ${block.mime_type}`
278
+ );
279
+ }
280
+ } else if (block.source_type === 'base64') {
281
+ if (mime_type === 'application/pdf' || mime_type === '') {
282
+ return {
283
+ type: 'document',
284
+ source: {
285
+ type: 'base64',
286
+ data: block.data,
287
+ media_type: 'application/pdf',
288
+ },
289
+ ...('cache_control' in (block.metadata ?? {})
290
+ ? { cache_control: block.metadata!.cache_control }
291
+ : {}),
292
+ ...('citations' in (block.metadata ?? {})
293
+ ? { citations: block.metadata!.citations }
294
+ : {}),
295
+ ...('context' in (block.metadata ?? {})
296
+ ? { context: block.metadata!.context }
297
+ : {}),
298
+ ...('title' in (block.metadata ?? {})
299
+ ? { title: block.metadata!.title }
300
+ : {}),
301
+ } as AnthropicDocumentBlockParam;
302
+ } else if (
303
+ ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(
304
+ mime_type
305
+ )
306
+ ) {
307
+ return {
308
+ type: 'document',
309
+ source: {
310
+ type: 'content',
311
+ content: [
312
+ {
313
+ type: 'image',
314
+ source: {
315
+ type: 'base64',
316
+ data: block.data,
317
+ media_type: mime_type as
318
+ | 'image/jpeg'
319
+ | 'image/png'
320
+ | 'image/gif'
321
+ | 'image/webp',
322
+ },
323
+ },
324
+ ],
325
+ },
326
+ ...('cache_control' in (block.metadata ?? {})
327
+ ? { cache_control: block.metadata!.cache_control }
328
+ : {}),
329
+ ...('citations' in (block.metadata ?? {})
330
+ ? { citations: block.metadata!.citations }
331
+ : {}),
332
+ ...('context' in (block.metadata ?? {})
333
+ ? { context: block.metadata!.context }
334
+ : {}),
335
+ ...('title' in (block.metadata ?? {})
336
+ ? { title: block.metadata!.title }
337
+ : {}),
338
+ } as AnthropicDocumentBlockParam;
339
+ } else {
340
+ throw new Error(
341
+ `Unsupported file mime type for file base64 source: ${block.mime_type}`
342
+ );
343
+ }
344
+ } else {
345
+ throw new Error(`Unsupported file source type: ${block.source_type}`);
346
+ }
347
+ },
348
+ };
349
+
350
+ function _formatContent(message: BaseMessage) {
351
+ const toolTypes = [
352
+ 'tool_use',
353
+ 'tool_result',
354
+ 'input_json_delta',
355
+ 'server_tool_use',
356
+ 'web_search_tool_result',
357
+ 'web_search_result',
358
+ ];
359
+ const textTypes = ['text', 'text_delta'];
360
+ const { content } = message;
361
+
362
+ if (typeof content === 'string') {
363
+ return content;
364
+ } else {
365
+ const contentBlocks = content.map((contentPart) => {
366
+ /**
367
+ * Handle malformed blocks that have server tool fields mixed with text type.
368
+ * These can occur when server_tool_use blocks get mislabeled during aggregation.
369
+ * Correct their type ONLY if we can confirm it's a server tool by checking the ID prefix.
370
+ * Anthropic needs both server_tool_use and web_search_tool_result blocks for citations to work.
371
+ */
372
+ if (
373
+ 'id' in contentPart &&
374
+ 'name' in contentPart &&
375
+ 'input' in contentPart &&
376
+ contentPart.type === 'text'
377
+ ) {
378
+ const rawPart = contentPart as Record<string, unknown>;
379
+ const id = rawPart.id as string;
380
+
381
+ // Only correct if this is definitely a server tool (ID starts with 'srvtoolu_')
382
+ if (id && id.startsWith('srvtoolu_')) {
383
+ let input = rawPart.input;
384
+
385
+ // Ensure input is an object
386
+ if (typeof input === 'string') {
387
+ try {
388
+ input = JSON.parse(input);
389
+ } catch {
390
+ input = {};
391
+ }
392
+ }
393
+
394
+ const corrected: AnthropicServerToolUseBlockParam = {
395
+ type: 'server_tool_use',
396
+ id,
397
+ name: 'web_search',
398
+ input: input as Record<string, unknown>,
399
+ };
400
+
401
+ return corrected;
402
+ }
403
+
404
+ // If it's not a server tool, skip it (return null to filter it out)
405
+ return null;
406
+ }
407
+
408
+ /**
409
+ * Handle malformed web_search_tool_result blocks marked as text.
410
+ * These have tool_use_id and nested content - fix their type instead of filtering.
411
+ * Only correct if we can confirm it's a web search result by checking the tool_use_id prefix.
412
+ *
413
+ * Handles both success results (array content) and error results (object with error_code).
414
+ */
415
+ if (
416
+ 'tool_use_id' in contentPart &&
417
+ 'content' in contentPart &&
418
+ contentPart.type === 'text'
419
+ ) {
420
+ const rawPart = contentPart as Record<string, unknown>;
421
+ const toolUseId = rawPart.tool_use_id as string;
422
+ const content = rawPart.content;
423
+
424
+ // Only correct if this is definitely a server tool result (tool_use_id starts with 'srvtoolu_')
425
+ if (toolUseId && toolUseId.startsWith('srvtoolu_')) {
426
+ // Verify content is either an array (success) or error object
427
+ const isValidContent =
428
+ Array.isArray(content) ||
429
+ (content != null &&
430
+ typeof content === 'object' &&
431
+ 'type' in content &&
432
+ (content as Record<string, unknown>).type ===
433
+ 'web_search_tool_result_error');
434
+
435
+ if (isValidContent) {
436
+ const corrected: AnthropicWebSearchToolResultBlockParam = {
437
+ type: 'web_search_tool_result',
438
+ tool_use_id: toolUseId,
439
+ content:
440
+ content as AnthropicWebSearchToolResultBlockParam['content'],
441
+ };
442
+ return corrected;
443
+ }
444
+ }
445
+
446
+ // If it's not a recognized server tool result format, skip it (return null to filter it out)
447
+ return null;
448
+ }
449
+
450
+ if (isDataContentBlock(contentPart)) {
451
+ return convertToProviderContentBlock(
452
+ contentPart,
453
+ standardContentBlockConverter
454
+ );
455
+ }
456
+
457
+ const cacheControl =
458
+ 'cache_control' in contentPart ? contentPart.cache_control : undefined;
459
+
460
+ if (contentPart.type === 'image_url') {
461
+ let source;
462
+ if (typeof contentPart.image_url === 'string') {
463
+ source = _formatImage(contentPart.image_url);
464
+ } else {
465
+ source = _formatImage(contentPart.image_url.url);
466
+ }
467
+ return {
468
+ type: 'image' as const, // Explicitly setting the type as "image"
469
+ source,
470
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
471
+ };
472
+ } else if (isAnthropicImageBlockParam(contentPart)) {
473
+ return contentPart;
474
+ } else if (contentPart.type === 'document') {
475
+ // PDF
476
+ return {
477
+ ...contentPart,
478
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
479
+ };
480
+ } else if (contentPart.type === 'thinking') {
481
+ const block: AnthropicThinkingBlockParam = {
482
+ type: 'thinking' as const, // Explicitly setting the type as "thinking"
483
+ thinking: contentPart.thinking,
484
+ signature: contentPart.signature,
485
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
486
+ };
487
+ return block;
488
+ } else if (contentPart.type === 'redacted_thinking') {
489
+ const block: AnthropicRedactedThinkingBlockParam = {
490
+ type: 'redacted_thinking' as const, // Explicitly setting the type as "redacted_thinking"
491
+ data: contentPart.data,
492
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
493
+ };
494
+ return block;
495
+ } else if (contentPart.type === 'search_result') {
496
+ const block: AnthropicSearchResultBlockParam = {
497
+ type: 'search_result' as const, // Explicitly setting the type as "search_result"
498
+ title: contentPart.title,
499
+ source: contentPart.source,
500
+ ...('cache_control' in contentPart && contentPart.cache_control
501
+ ? { cache_control: contentPart.cache_control }
502
+ : {}),
503
+ ...('citations' in contentPart && contentPart.citations
504
+ ? { citations: contentPart.citations }
505
+ : {}),
506
+ content: contentPart.content,
507
+ };
508
+ return block;
509
+ } else if (
510
+ textTypes.find((t) => t === contentPart.type) &&
511
+ 'text' in contentPart
512
+ ) {
513
+ // Assuming contentPart is of type MessageContentText here
514
+ return {
515
+ type: 'text' as const, // Explicitly setting the type as "text"
516
+ text: contentPart.text,
517
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
518
+ ...('citations' in contentPart && contentPart.citations
519
+ ? { citations: contentPart.citations }
520
+ : {}),
521
+ };
522
+ } else if (toolTypes.find((t) => t === contentPart.type)) {
523
+ const contentPartCopy = { ...contentPart };
524
+ if ('index' in contentPartCopy) {
525
+ // Anthropic does not support passing the index field here, so we remove it.
526
+ delete contentPartCopy.index;
527
+ }
528
+
529
+ if (contentPartCopy.type === 'input_json_delta') {
530
+ // `input_json_delta` type only represents yielding partial tool inputs
531
+ // and is not a valid type for Anthropic messages.
532
+ contentPartCopy.type = 'tool_use';
533
+ }
534
+
535
+ if ('input' in contentPartCopy) {
536
+ // Anthropic tool use inputs should be valid objects, when applicable.
537
+ if (typeof contentPartCopy.input === 'string') {
538
+ try {
539
+ contentPartCopy.input = JSON.parse(contentPartCopy.input);
540
+ } catch {
541
+ contentPartCopy.input = {};
542
+ }
543
+ }
544
+ }
545
+
546
+ /**
547
+ * For multi-turn conversations with citations, we must preserve ALL blocks
548
+ * including server_tool_use, web_search_tool_result, and web_search_result.
549
+ * Citations reference search results by index, so filtering changes indices and breaks references.
550
+ *
551
+ * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.
552
+ */
553
+
554
+ // TODO: Fix when SDK types are fixed
555
+ return {
556
+ ...contentPartCopy,
557
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
558
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
559
+ } as any;
560
+ } else if (
561
+ 'functionCall' in contentPart &&
562
+ contentPart.functionCall &&
563
+ typeof contentPart.functionCall === 'object' &&
564
+ isAIMessage(message)
565
+ ) {
566
+ const correspondingToolCall = message.tool_calls?.find(
567
+ (toolCall) => toolCall.name === contentPart.functionCall.name
568
+ );
569
+ if (!correspondingToolCall) {
570
+ throw new Error(
571
+ `Could not find tool call for function call ${contentPart.functionCall.name}`
572
+ );
573
+ }
574
+ // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.
575
+ return {
576
+ id: correspondingToolCall.id,
577
+ type: 'tool_use',
578
+ name: correspondingToolCall.name,
579
+ input: contentPart.functionCall.args,
580
+ };
581
+ } else {
582
+ console.error(
583
+ 'Unsupported content part:',
584
+ JSON.stringify(contentPart, null, 2)
585
+ );
586
+ throw new Error('Unsupported message content format');
587
+ }
588
+ });
589
+ return contentBlocks.filter((block) => block !== null);
590
+ }
591
+ }
592
+
593
+ /**
594
+ * Formats messages as a prompt for the model.
595
+ * Used in LangSmith, export is important here.
596
+ * @param messages The base messages to format as a prompt.
597
+ * @returns The formatted prompt.
598
+ */
599
+ export function _convertMessagesToAnthropicPayload(
600
+ messages: BaseMessage[]
601
+ ): AnthropicMessageCreateParams {
602
+ const mergedMessages = _ensureMessageContents(messages);
603
+ let system;
604
+ if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {
605
+ system = messages[0].content;
606
+ }
607
+ const conversationMessages =
608
+ system !== undefined ? mergedMessages.slice(1) : mergedMessages;
609
+ const formattedMessages = conversationMessages.map((message) => {
610
+ let role;
611
+ if (message._getType() === 'human') {
612
+ role = 'user' as const;
613
+ } else if (message._getType() === 'ai') {
614
+ role = 'assistant' as const;
615
+ } else if (message._getType() === 'tool') {
616
+ role = 'user' as const;
617
+ } else if (message._getType() === 'system') {
618
+ throw new Error(
619
+ 'System messages are only permitted as the first passed message.'
620
+ );
621
+ } else {
622
+ throw new Error(`Message type "${message._getType()}" is not supported.`);
623
+ }
624
+ if (isAIMessage(message) && !!message.tool_calls?.length) {
625
+ if (typeof message.content === 'string') {
626
+ if (message.content === '') {
627
+ return {
628
+ role,
629
+ content: message.tool_calls.map(
630
+ _convertLangChainToolCallToAnthropic
631
+ ),
632
+ };
633
+ } else {
634
+ return {
635
+ role,
636
+ content: [
637
+ { type: 'text', text: message.content },
638
+ ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),
639
+ ],
640
+ };
641
+ }
642
+ } else {
643
+ const { content } = message;
644
+ const hasMismatchedToolCalls = !message.tool_calls.every(
645
+ (toolCall) =>
646
+ !!content.find(
647
+ (contentPart) =>
648
+ (contentPart.type === 'tool_use' ||
649
+ contentPart.type === 'input_json_delta' ||
650
+ contentPart.type === 'server_tool_use') &&
651
+ contentPart.id === toolCall.id
652
+ )
653
+ );
654
+ if (hasMismatchedToolCalls) {
655
+ console.warn(
656
+ 'The "tool_calls" field on a message is only respected if content is a string.'
657
+ );
658
+ }
659
+ return {
660
+ role,
661
+ content: _formatContent(message),
662
+ };
663
+ }
664
+ } else {
665
+ return {
666
+ role,
667
+ content: _formatContent(message),
668
+ };
669
+ }
670
+ });
671
+ return {
672
+ messages: mergeMessages(formattedMessages),
673
+ system,
674
+ } as AnthropicMessageCreateParams;
675
+ }
676
+
677
+ function mergeMessages(messages: AnthropicMessageCreateParams['messages']) {
678
+ if (!messages || messages.length <= 1) {
679
+ return messages;
680
+ }
681
+
682
+ const result: AnthropicMessageCreateParams['messages'] = [];
683
+ let currentMessage = messages[0];
684
+
685
+ const normalizeContent = (
686
+ content:
687
+ | string
688
+ | Array<
689
+ | AnthropicTextBlockParam
690
+ | AnthropicImageBlockParam
691
+ | AnthropicToolUseBlockParam
692
+ | AnthropicToolResultBlockParam
693
+ | AnthropicDocumentBlockParam
694
+ | AnthropicThinkingBlockParam
695
+ | AnthropicRedactedThinkingBlockParam
696
+ | AnthropicServerToolUseBlockParam
697
+ | AnthropicWebSearchToolResultBlockParam
698
+ >
699
+ ): Array<
700
+ | AnthropicTextBlockParam
701
+ | AnthropicImageBlockParam
702
+ | AnthropicToolUseBlockParam
703
+ | AnthropicToolResultBlockParam
704
+ | AnthropicDocumentBlockParam
705
+ | AnthropicThinkingBlockParam
706
+ | AnthropicRedactedThinkingBlockParam
707
+ | AnthropicServerToolUseBlockParam
708
+ | AnthropicWebSearchToolResultBlockParam
709
+ > => {
710
+ if (typeof content === 'string') {
711
+ return [
712
+ {
713
+ type: 'text',
714
+ text: content,
715
+ },
716
+ ];
717
+ }
718
+ return content;
719
+ };
720
+
721
+ const isToolResultMessage = (msg: (typeof messages)[0]) => {
722
+ if (msg.role !== 'user') return false;
723
+
724
+ if (typeof msg.content === 'string') {
725
+ return false;
726
+ }
727
+
728
+ return (
729
+ Array.isArray(msg.content) &&
730
+ msg.content.every((item) => item.type === 'tool_result')
731
+ );
732
+ };
733
+
734
+ for (let i = 1; i < messages.length; i += 1) {
735
+ const nextMessage = messages[i];
736
+
737
+ if (
738
+ isToolResultMessage(currentMessage) &&
739
+ isToolResultMessage(nextMessage)
740
+ ) {
741
+ // Merge the messages by combining their content arrays
742
+ currentMessage = {
743
+ ...currentMessage,
744
+ content: [
745
+ ...normalizeContent(currentMessage.content),
746
+ ...normalizeContent(nextMessage.content),
747
+ ],
748
+ };
749
+ } else {
750
+ result.push(currentMessage);
751
+ currentMessage = nextMessage;
752
+ }
753
+ }
754
+
755
+ result.push(currentMessage);
756
+ return result;
757
+ }