@langchain/google-common 0.2.18 → 1.0.1

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 (173) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +6 -6
  3. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  4. package/dist/auth.cjs +82 -116
  5. package/dist/auth.cjs.map +1 -0
  6. package/dist/auth.d.cts +46 -0
  7. package/dist/auth.d.cts.map +1 -0
  8. package/dist/auth.d.ts +41 -36
  9. package/dist/auth.d.ts.map +1 -0
  10. package/dist/auth.js +80 -110
  11. package/dist/auth.js.map +1 -0
  12. package/dist/chat_models.cjs +264 -466
  13. package/dist/chat_models.cjs.map +1 -0
  14. package/dist/chat_models.d.cts +109 -0
  15. package/dist/chat_models.d.cts.map +1 -0
  16. package/dist/chat_models.d.ts +98 -73
  17. package/dist/chat_models.d.ts.map +1 -0
  18. package/dist/chat_models.js +258 -457
  19. package/dist/chat_models.js.map +1 -0
  20. package/dist/connection.cjs +321 -466
  21. package/dist/connection.cjs.map +1 -0
  22. package/dist/connection.d.cts +109 -0
  23. package/dist/connection.d.cts.map +1 -0
  24. package/dist/connection.d.ts +98 -91
  25. package/dist/connection.d.ts.map +1 -0
  26. package/dist/connection.js +317 -459
  27. package/dist/connection.js.map +1 -0
  28. package/dist/embeddings.cjs +135 -186
  29. package/dist/embeddings.cjs.map +1 -0
  30. package/dist/embeddings.d.cts +44 -0
  31. package/dist/embeddings.d.cts.map +1 -0
  32. package/dist/embeddings.d.ts +38 -32
  33. package/dist/embeddings.d.ts.map +1 -0
  34. package/dist/embeddings.js +133 -181
  35. package/dist/embeddings.js.map +1 -0
  36. package/dist/experimental/media.cjs +380 -482
  37. package/dist/experimental/media.cjs.map +1 -0
  38. package/dist/experimental/media.d.cts +198 -0
  39. package/dist/experimental/media.d.cts.map +1 -0
  40. package/dist/experimental/media.d.ts +190 -202
  41. package/dist/experimental/media.d.ts.map +1 -0
  42. package/dist/experimental/media.js +369 -468
  43. package/dist/experimental/media.js.map +1 -0
  44. package/dist/experimental/utils/media_core.cjs +403 -517
  45. package/dist/experimental/utils/media_core.cjs.map +1 -0
  46. package/dist/experimental/utils/media_core.d.cts +215 -0
  47. package/dist/experimental/utils/media_core.d.cts.map +1 -0
  48. package/dist/experimental/utils/media_core.d.ts +171 -165
  49. package/dist/experimental/utils/media_core.d.ts.map +1 -0
  50. package/dist/experimental/utils/media_core.js +395 -506
  51. package/dist/experimental/utils/media_core.js.map +1 -0
  52. package/dist/index.cjs +58 -27
  53. package/dist/index.d.cts +13 -0
  54. package/dist/index.d.ts +13 -11
  55. package/dist/index.js +13 -11
  56. package/dist/llms.cjs +157 -244
  57. package/dist/llms.cjs.map +1 -0
  58. package/dist/llms.d.cts +72 -0
  59. package/dist/llms.d.cts.map +1 -0
  60. package/dist/llms.d.ts +64 -54
  61. package/dist/llms.d.ts.map +1 -0
  62. package/dist/llms.js +154 -238
  63. package/dist/llms.js.map +1 -0
  64. package/dist/output_parsers.cjs +148 -173
  65. package/dist/output_parsers.cjs.map +1 -0
  66. package/dist/output_parsers.d.cts +53 -0
  67. package/dist/output_parsers.d.cts.map +1 -0
  68. package/dist/output_parsers.d.ts +46 -42
  69. package/dist/output_parsers.d.ts.map +1 -0
  70. package/dist/output_parsers.js +146 -168
  71. package/dist/output_parsers.js.map +1 -0
  72. package/dist/profiles.cjs +219 -0
  73. package/dist/profiles.cjs.map +1 -0
  74. package/dist/profiles.js +218 -0
  75. package/dist/profiles.js.map +1 -0
  76. package/dist/types-anthropic.d.cts +229 -0
  77. package/dist/types-anthropic.d.cts.map +1 -0
  78. package/dist/types-anthropic.d.ts +221 -215
  79. package/dist/types-anthropic.d.ts.map +1 -0
  80. package/dist/types.cjs +51 -62
  81. package/dist/types.cjs.map +1 -0
  82. package/dist/types.d.cts +748 -0
  83. package/dist/types.d.cts.map +1 -0
  84. package/dist/types.d.ts +669 -656
  85. package/dist/types.d.ts.map +1 -0
  86. package/dist/types.js +46 -45
  87. package/dist/types.js.map +1 -0
  88. package/dist/utils/anthropic.cjs +598 -821
  89. package/dist/utils/anthropic.cjs.map +1 -0
  90. package/dist/utils/anthropic.js +597 -818
  91. package/dist/utils/anthropic.js.map +1 -0
  92. package/dist/utils/common.cjs +130 -211
  93. package/dist/utils/common.cjs.map +1 -0
  94. package/dist/utils/common.d.cts +13 -0
  95. package/dist/utils/common.d.cts.map +1 -0
  96. package/dist/utils/common.d.ts +12 -7
  97. package/dist/utils/common.d.ts.map +1 -0
  98. package/dist/utils/common.js +128 -207
  99. package/dist/utils/common.js.map +1 -0
  100. package/dist/utils/failed_handler.cjs +28 -30
  101. package/dist/utils/failed_handler.cjs.map +1 -0
  102. package/dist/utils/failed_handler.d.cts +9 -0
  103. package/dist/utils/failed_handler.d.cts.map +1 -0
  104. package/dist/utils/failed_handler.d.ts +8 -2
  105. package/dist/utils/failed_handler.d.ts.map +1 -0
  106. package/dist/utils/failed_handler.js +28 -28
  107. package/dist/utils/failed_handler.js.map +1 -0
  108. package/dist/utils/gemini.cjs +1020 -1488
  109. package/dist/utils/gemini.cjs.map +1 -0
  110. package/dist/utils/gemini.d.cts +51 -0
  111. package/dist/utils/gemini.d.cts.map +1 -0
  112. package/dist/utils/gemini.d.ts +51 -48
  113. package/dist/utils/gemini.d.ts.map +1 -0
  114. package/dist/utils/gemini.js +1015 -1479
  115. package/dist/utils/gemini.js.map +1 -0
  116. package/dist/utils/index.cjs +38 -23
  117. package/dist/utils/index.d.cts +8 -0
  118. package/dist/utils/index.d.ts +8 -7
  119. package/dist/utils/index.js +8 -7
  120. package/dist/utils/palm.d.cts +11 -0
  121. package/dist/utils/palm.d.cts.map +1 -0
  122. package/dist/utils/palm.d.ts +9 -4
  123. package/dist/utils/palm.d.ts.map +1 -0
  124. package/dist/utils/safety.cjs +13 -22
  125. package/dist/utils/safety.cjs.map +1 -0
  126. package/dist/utils/safety.d.cts +12 -0
  127. package/dist/utils/safety.d.cts.map +1 -0
  128. package/dist/utils/safety.d.ts +10 -4
  129. package/dist/utils/safety.d.ts.map +1 -0
  130. package/dist/utils/safety.js +13 -19
  131. package/dist/utils/safety.js.map +1 -0
  132. package/dist/utils/stream.cjs +296 -475
  133. package/dist/utils/stream.cjs.map +1 -0
  134. package/dist/utils/stream.d.cts +165 -0
  135. package/dist/utils/stream.d.cts.map +1 -0
  136. package/dist/utils/stream.d.ts +156 -131
  137. package/dist/utils/stream.d.ts.map +1 -0
  138. package/dist/utils/stream.js +293 -469
  139. package/dist/utils/stream.js.map +1 -0
  140. package/dist/utils/zod_to_gemini_parameters.cjs +43 -81
  141. package/dist/utils/zod_to_gemini_parameters.cjs.map +1 -0
  142. package/dist/utils/zod_to_gemini_parameters.d.cts +22 -0
  143. package/dist/utils/zod_to_gemini_parameters.d.cts.map +1 -0
  144. package/dist/utils/zod_to_gemini_parameters.d.ts +21 -6
  145. package/dist/utils/zod_to_gemini_parameters.d.ts.map +1 -0
  146. package/dist/utils/zod_to_gemini_parameters.js +40 -76
  147. package/dist/utils/zod_to_gemini_parameters.js.map +1 -0
  148. package/package.json +72 -85
  149. package/dist/types-anthropic.cjs +0 -2
  150. package/dist/types-anthropic.js +0 -1
  151. package/dist/utils/anthropic.d.ts +0 -4
  152. package/dist/utils/palm.cjs +0 -2
  153. package/dist/utils/palm.js +0 -1
  154. package/experimental/media.cjs +0 -1
  155. package/experimental/media.d.cts +0 -1
  156. package/experimental/media.d.ts +0 -1
  157. package/experimental/media.js +0 -1
  158. package/experimental/utils/media_core.cjs +0 -1
  159. package/experimental/utils/media_core.d.cts +0 -1
  160. package/experimental/utils/media_core.d.ts +0 -1
  161. package/experimental/utils/media_core.js +0 -1
  162. package/index.cjs +0 -1
  163. package/index.d.cts +0 -1
  164. package/index.d.ts +0 -1
  165. package/index.js +0 -1
  166. package/types.cjs +0 -1
  167. package/types.d.cts +0 -1
  168. package/types.d.ts +0 -1
  169. package/types.js +0 -1
  170. package/utils.cjs +0 -1
  171. package/utils.d.cts +0 -1
  172. package/utils.d.ts +0 -1
  173. package/utils.js +0 -1
@@ -1,825 +1,602 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAnthropicAPI = getAnthropicAPI;
4
- exports.validateClaudeParams = validateClaudeParams;
5
- exports.isModelClaude = isModelClaude;
6
- const outputs_1 = require("@langchain/core/outputs");
7
- const messages_1 = require("@langchain/core/messages");
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const __langchain_core_outputs = require_rolldown_runtime.__toESM(require("@langchain/core/outputs"));
3
+ const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
4
+
5
+ //#region src/utils/anthropic.ts
8
6
  function getAnthropicAPI(config) {
9
- function partToString(part) {
10
- return "text" in part ? part.text : "";
11
- }
12
- function messageToString(message) {
13
- const content = message?.content ?? [];
14
- const ret = content.reduce((acc, part) => {
15
- const str = partToString(part);
16
- return acc + str;
17
- }, "");
18
- return ret;
19
- }
20
- function responseToString(response) {
21
- const data = response.data;
22
- switch (data?.type) {
23
- case "message":
24
- return messageToString(data);
25
- default:
26
- throw Error(`Unknown type: ${data?.type}`);
27
- }
28
- }
29
- /**
30
- * Normalize the AIMessageChunk.
31
- * If the fields are just a string - use that as content.
32
- * If the content is an array of just text fields, turn them into a string.
33
- * @param fields
34
- */
35
- function newAIMessageChunk(fields) {
36
- if (typeof fields === "string") {
37
- return new messages_1.AIMessageChunk(fields);
38
- }
39
- const ret = {
40
- ...fields,
41
- };
42
- if (Array.isArray(fields?.content)) {
43
- let str = "";
44
- fields.content.forEach((val) => {
45
- if (str !== undefined && val.type === "text") {
46
- str = `${str}${val.text}`;
47
- }
48
- else {
49
- str = undefined;
50
- }
51
- });
52
- if (str) {
53
- ret.content = str;
54
- }
55
- }
56
- return new messages_1.AIMessageChunk(ret);
57
- }
58
- function textContentToMessageFields(textContent) {
59
- return {
60
- content: [textContent],
61
- };
62
- }
63
- function toolUseContentToMessageFields(toolUseContent) {
64
- const tool = {
65
- id: toolUseContent.id,
66
- name: toolUseContent.name,
67
- type: "tool_call",
68
- args: toolUseContent.input,
69
- };
70
- return {
71
- content: [],
72
- tool_calls: [tool],
73
- };
74
- }
75
- function thinkingContentToMessageFields(thinkingContent) {
76
- // TODO: Once a reasoning/thinking type is defined in LangChain, use it
77
- return {
78
- content: [thinkingContent],
79
- };
80
- }
81
- function redactedThinkingContentToMessageFields(thinkingContent) {
82
- // TODO: Once a reasoning/thinking type is defined in LangChain, use it
83
- return {
84
- content: [thinkingContent],
85
- };
86
- }
87
- function anthropicContentToMessageFields(anthropicContent) {
88
- const type = anthropicContent?.type;
89
- switch (type) {
90
- case "text":
91
- return textContentToMessageFields(anthropicContent);
92
- case "tool_use":
93
- return toolUseContentToMessageFields(anthropicContent);
94
- case "thinking":
95
- return thinkingContentToMessageFields(anthropicContent);
96
- case "redacted_thinking":
97
- return redactedThinkingContentToMessageFields(anthropicContent);
98
- default:
99
- console.error(`Unknown message type: ${type}`, anthropicContent);
100
- return undefined;
101
- }
102
- }
103
- function contentToMessage(anthropicContent) {
104
- const complexContent = [];
105
- const toolCalls = [];
106
- anthropicContent.forEach((ac) => {
107
- const messageFields = anthropicContentToMessageFields(ac);
108
- if (messageFields?.content) {
109
- complexContent.push(...messageFields.content);
110
- }
111
- if (messageFields?.tool_calls) {
112
- toolCalls.push(...messageFields.tool_calls);
113
- }
114
- });
115
- const ret = {
116
- content: complexContent,
117
- tool_calls: toolCalls,
118
- };
119
- return newAIMessageChunk(ret);
120
- }
121
- function messageToUsageMetadata(message) {
122
- const usage = message?.usage;
123
- const inputTokens = usage?.input_tokens ?? 0;
124
- const outputTokens = usage?.output_tokens ?? 0;
125
- const usageMetadata = {
126
- input_tokens: inputTokens,
127
- output_tokens: outputTokens,
128
- total_tokens: inputTokens + outputTokens,
129
- input_token_details: {
130
- cache_read: usage?.cache_read_input_tokens ?? 0,
131
- cache_creation: usage?.cache_creation_input_tokens ?? 0,
132
- },
133
- };
134
- return usageMetadata;
135
- }
136
- function messageToGenerationInfo(message) {
137
- const usageMetadata = messageToUsageMetadata(message);
138
- return {
139
- usage_metadata: usageMetadata,
140
- finish_reason: message.stop_reason,
141
- };
142
- }
143
- function messageToChatGeneration(responseMessage) {
144
- const content = responseMessage?.content ?? [];
145
- const text = messageToString(responseMessage);
146
- const message = contentToMessage(content);
147
- const generationInfo = messageToGenerationInfo(responseMessage);
148
- return new outputs_1.ChatGenerationChunk({
149
- text,
150
- message,
151
- generationInfo,
152
- });
153
- }
154
- function messageStartToChatGeneration(event) {
155
- const responseMessage = event.message;
156
- return messageToChatGeneration(responseMessage);
157
- }
158
- function messageDeltaToChatGeneration(event) {
159
- const responseMessage = event.delta;
160
- return messageToChatGeneration(responseMessage);
161
- }
162
- function contentBlockStartTextToChatGeneration(event) {
163
- const content = event.content_block;
164
- const message = contentToMessage([content]);
165
- if (!message) {
166
- return null;
167
- }
168
- const text = "text" in content ? content.text : "";
169
- return new outputs_1.ChatGenerationChunk({
170
- message,
171
- text,
172
- });
173
- }
174
- function contentBlockStartToolUseToChatGeneration(event) {
175
- const contentBlock = event.content_block;
176
- const text = "";
177
- const toolChunk = {
178
- type: "tool_call_chunk",
179
- index: event.index,
180
- name: contentBlock.name,
181
- id: contentBlock.id,
182
- };
183
- if (typeof contentBlock.input === "object" &&
184
- Object.keys(contentBlock.input).length > 0) {
185
- toolChunk.args = JSON.stringify(contentBlock.input);
186
- }
187
- const toolChunks = [toolChunk];
188
- const content = [
189
- {
190
- index: event.index,
191
- ...contentBlock,
192
- },
193
- ];
194
- const messageFields = {
195
- content,
196
- tool_call_chunks: toolChunks,
197
- };
198
- const message = newAIMessageChunk(messageFields);
199
- return new outputs_1.ChatGenerationChunk({
200
- message,
201
- text,
202
- });
203
- }
204
- function contentBlockStartToChatGeneration(event) {
205
- switch (event.content_block.type) {
206
- case "text":
207
- return contentBlockStartTextToChatGeneration(event);
208
- case "tool_use":
209
- return contentBlockStartToolUseToChatGeneration(event);
210
- default:
211
- console.warn(`Unexpected start content_block type: ${JSON.stringify(event)}`);
212
- return null;
213
- }
214
- }
215
- function contentBlockDeltaTextToChatGeneration(event) {
216
- const delta = event.delta;
217
- const text = delta?.text;
218
- const message = newAIMessageChunk(text);
219
- return new outputs_1.ChatGenerationChunk({
220
- message,
221
- text,
222
- });
223
- }
224
- function contentBlockDeltaInputJsonDeltaToChatGeneration(event) {
225
- const delta = event.delta;
226
- const text = "";
227
- const toolChunks = [
228
- {
229
- index: event.index,
230
- args: delta.partial_json,
231
- },
232
- ];
233
- const content = [
234
- {
235
- index: event.index,
236
- ...delta,
237
- },
238
- ];
239
- const messageFields = {
240
- content,
241
- tool_call_chunks: toolChunks,
242
- };
243
- const message = newAIMessageChunk(messageFields);
244
- return new outputs_1.ChatGenerationChunk({
245
- message,
246
- text,
247
- });
248
- }
249
- function contentBlockDeltaToChatGeneration(event) {
250
- switch (event.delta.type) {
251
- case "text_delta":
252
- return contentBlockDeltaTextToChatGeneration(event);
253
- case "input_json_delta":
254
- return contentBlockDeltaInputJsonDeltaToChatGeneration(event);
255
- default:
256
- console.warn(`Unexpected delta content_block type: ${JSON.stringify(event)}`);
257
- return null;
258
- }
259
- }
260
- function responseToChatGeneration(response) {
261
- const data = response.data;
262
- switch (data.type) {
263
- case "message":
264
- return messageToChatGeneration(data);
265
- case "message_start":
266
- return messageStartToChatGeneration(data);
267
- case "message_delta":
268
- return messageDeltaToChatGeneration(data);
269
- case "content_block_start":
270
- return contentBlockStartToChatGeneration(data);
271
- case "content_block_delta":
272
- return contentBlockDeltaToChatGeneration(data);
273
- case "ping":
274
- case "message_stop":
275
- case "content_block_stop":
276
- // These are ignorable
277
- return null;
278
- case "error":
279
- throw new Error(`Error while streaming results: ${JSON.stringify(data)}`);
280
- default:
281
- // We don't know what type this is, but Anthropic may have added
282
- // new ones without telling us. Don't error, but don't use them.
283
- console.warn("Unknown data for responseToChatGeneration", data);
284
- // throw new Error(`Unknown response type: ${data.type}`);
285
- return null;
286
- }
287
- }
288
- function chunkToString(chunk) {
289
- if (chunk === null) {
290
- return "";
291
- }
292
- else if (typeof chunk.content === "string") {
293
- return chunk.content;
294
- }
295
- else if (chunk.content.length === 0) {
296
- return "";
297
- }
298
- else if (chunk.content[0].type === "text") {
299
- return chunk.content[0].text;
300
- }
301
- else {
302
- throw new Error(`Unexpected chunk: ${chunk}`);
303
- }
304
- }
305
- function responseToBaseMessage(response) {
306
- const data = response.data;
307
- const content = data?.content ?? [];
308
- return contentToMessage(content);
309
- }
310
- function responseToChatResult(response) {
311
- const message = response.data;
312
- const generations = [];
313
- const gen = responseToChatGeneration(response);
314
- if (gen) {
315
- generations.push(gen);
316
- }
317
- const llmOutput = messageToGenerationInfo(message);
318
- return {
319
- generations,
320
- llmOutput,
321
- };
322
- }
323
- function formatAnthropicVersion() {
324
- return config?.version ?? "vertex-2023-10-16";
325
- }
326
- function textContentToAnthropicContent(content) {
327
- return content;
328
- }
329
- function extractMimeType(str) {
330
- if (str.startsWith("data:")) {
331
- return {
332
- media_type: str.split(":")[1].split(";")[0],
333
- data: str.split(",")[1],
334
- };
335
- }
336
- return null;
337
- }
338
- function imageContentToAnthropicContent(content) {
339
- const dataUrl = content.image_url;
340
- const url = typeof dataUrl === "string" ? dataUrl : dataUrl?.url;
341
- const urlInfo = extractMimeType(url);
342
- if (!urlInfo) {
343
- return undefined;
344
- }
345
- return {
346
- type: "image",
347
- source: {
348
- type: "base64",
349
- ...urlInfo,
350
- },
351
- };
352
- }
353
- function thinkingContentToAnthropicContent(
354
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
- content) {
356
- // TODO: Once a Langchain Thinking type is defined, use it
357
- return {
358
- type: "thinking",
359
- thinking: content.thinking,
360
- signature: content.signature,
361
- };
362
- }
363
- function redactedThinkingContentToAnthropicContent(
364
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
365
- content) {
366
- // TODO: Once a Langchain Thinking type is defined, use it
367
- return {
368
- type: "redacted_thinking",
369
- data: content.data,
370
- };
371
- }
372
- function contentComplexToAnthropicContent(content) {
373
- const type = content?.type;
374
- switch (type) {
375
- case "text":
376
- return textContentToAnthropicContent(content);
377
- case "image_url":
378
- return imageContentToAnthropicContent(content);
379
- case "thinking":
380
- return thinkingContentToAnthropicContent(content);
381
- case "redacted_thinking":
382
- return redactedThinkingContentToAnthropicContent(content);
383
- default:
384
- console.warn(`Unexpected content type: ${type}`, content);
385
- return undefined;
386
- }
387
- }
388
- const anthropicContentConverter = {
389
- providerName: "anthropic",
390
- fromStandardTextBlock(block) {
391
- return {
392
- type: "text",
393
- text: block.text,
394
- ...("cache_control" in (block.metadata ?? {})
395
- ? {
396
- cache_control: block.metadata
397
- .cache_control,
398
- }
399
- : {}),
400
- };
401
- },
402
- fromStandardImageBlock(block) {
403
- if (block.source_type === "url") {
404
- const data = (0, messages_1.parseBase64DataUrl)({
405
- dataUrl: block.url,
406
- asTypedArray: false,
407
- });
408
- if (data) {
409
- return {
410
- type: "image",
411
- source: {
412
- type: "base64",
413
- data: data.data,
414
- media_type: data.mime_type,
415
- },
416
- ...("cache_control" in (block.metadata ?? {})
417
- ? { cache_control: block.metadata.cache_control }
418
- : {}),
419
- };
420
- }
421
- else {
422
- return {
423
- type: "image",
424
- source: {
425
- type: "url",
426
- url: block.url,
427
- media_type: block.mime_type ?? "",
428
- },
429
- ...("cache_control" in (block.metadata ?? {})
430
- ? { cache_control: block.metadata.cache_control }
431
- : {}),
432
- };
433
- }
434
- }
435
- else {
436
- if (block.source_type === "base64") {
437
- return {
438
- type: "image",
439
- source: {
440
- type: "base64",
441
- data: block.data,
442
- media_type: block.mime_type ?? "",
443
- },
444
- ...("cache_control" in (block.metadata ?? {})
445
- ? { cache_control: block.metadata.cache_control }
446
- : {}),
447
- };
448
- }
449
- else {
450
- throw new Error(`Unsupported image source type: ${block.source_type}`);
451
- }
452
- }
453
- },
454
- fromStandardFileBlock(block) {
455
- const mime_type = (block.mime_type ?? "").split(";")[0];
456
- if (block.source_type === "url") {
457
- if (mime_type === "application/pdf" || mime_type === "") {
458
- return {
459
- type: "document",
460
- source: {
461
- type: "url",
462
- url: block.url,
463
- media_type: block.mime_type ?? "",
464
- },
465
- ...("cache_control" in (block.metadata ?? {})
466
- ? {
467
- cache_control: block.metadata
468
- .cache_control,
469
- }
470
- : {}),
471
- ...("citations" in (block.metadata ?? {})
472
- ? {
473
- citations: block.metadata.citations,
474
- }
475
- : {}),
476
- ...("context" in (block.metadata ?? {})
477
- ? { context: block.metadata.context }
478
- : {}),
479
- ...(block.metadata?.title ||
480
- block.metadata?.filename ||
481
- block.metadata?.name
482
- ? {
483
- title: (block.metadata?.title ||
484
- block.metadata?.filename ||
485
- block.metadata?.name),
486
- }
487
- : {}),
488
- };
489
- }
490
- throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`);
491
- }
492
- else if (block.source_type === "text") {
493
- if (mime_type === "text/plain" || mime_type === "") {
494
- return {
495
- type: "document",
496
- source: {
497
- type: "text",
498
- data: block.text,
499
- media_type: block.mime_type ?? "",
500
- },
501
- ...("cache_control" in (block.metadata ?? {})
502
- ? {
503
- cache_control: block.metadata
504
- .cache_control,
505
- }
506
- : {}),
507
- ...("citations" in (block.metadata ?? {})
508
- ? {
509
- citations: block.metadata.citations,
510
- }
511
- : {}),
512
- ...("context" in (block.metadata ?? {})
513
- ? { context: block.metadata.context }
514
- : {}),
515
- ...("title" in (block.metadata ?? {})
516
- ? { title: block.metadata.title }
517
- : {}),
518
- };
519
- }
520
- else {
521
- throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`);
522
- }
523
- }
524
- else if (block.source_type === "base64") {
525
- if (mime_type === "application/pdf" || mime_type === "") {
526
- return {
527
- type: "document",
528
- source: {
529
- type: "base64",
530
- data: block.data,
531
- media_type: "application/pdf",
532
- },
533
- ...("cache_control" in (block.metadata ?? {})
534
- ? {
535
- cache_control: block.metadata
536
- .cache_control,
537
- }
538
- : {}),
539
- ...("citations" in (block.metadata ?? {})
540
- ? {
541
- citations: block.metadata.citations,
542
- }
543
- : {}),
544
- ...("context" in (block.metadata ?? {})
545
- ? { context: block.metadata.context }
546
- : {}),
547
- ...("title" in (block.metadata ?? {})
548
- ? { title: block.metadata.title }
549
- : {}),
550
- };
551
- }
552
- else if (["image/jpeg", "image/png", "image/gif", "image/webp"].includes(mime_type)) {
553
- return {
554
- type: "document",
555
- source: {
556
- type: "content",
557
- content: [
558
- {
559
- type: "image",
560
- source: {
561
- type: "base64",
562
- data: block.data,
563
- media_type: mime_type,
564
- },
565
- },
566
- ],
567
- },
568
- ...("cache_control" in (block.metadata ?? {})
569
- ? {
570
- cache_control: block.metadata
571
- .cache_control,
572
- }
573
- : {}),
574
- ...("citations" in (block.metadata ?? {})
575
- ? {
576
- citations: block.metadata.citations,
577
- }
578
- : {}),
579
- ...("context" in (block.metadata ?? {})
580
- ? { context: block.metadata.context }
581
- : {}),
582
- ...("title" in (block.metadata ?? {})
583
- ? { title: block.metadata.title }
584
- : {}),
585
- };
586
- }
587
- else {
588
- throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`);
589
- }
590
- }
591
- else {
592
- throw new Error(`Unsupported file source type: ${block.source_type}`);
593
- }
594
- },
595
- };
596
- function contentToAnthropicContent(content) {
597
- const ca = typeof content === "string" ? [{ type: "text", text: content }] : content;
598
- return ca
599
- .map((complex) => (0, messages_1.isDataContentBlock)(complex)
600
- ? (0, messages_1.convertToProviderContentBlock)(complex, anthropicContentConverter)
601
- : contentComplexToAnthropicContent(complex))
602
- .filter(Boolean);
603
- }
604
- function toolCallToAnthropicContent(toolCall) {
605
- return {
606
- type: "tool_use",
607
- id: toolCall.id,
608
- name: toolCall.name,
609
- input: toolCall.args,
610
- };
611
- }
612
- function toolCallsToAnthropicContent(toolCalls) {
613
- if (toolCalls === undefined) {
614
- return [];
615
- }
616
- return toolCalls.map(toolCallToAnthropicContent);
617
- }
618
- function baseRoleToAnthropicMessage(base, role) {
619
- const content = contentToAnthropicContent(base.content);
620
- return {
621
- role,
622
- content,
623
- };
624
- }
625
- function aiMessageToAnthropicMessage(base) {
626
- const ret = baseRoleToAnthropicMessage(base, "assistant");
627
- const toolContent = toolCallsToAnthropicContent(base.tool_calls);
628
- if (toolContent.length > 0) {
629
- const content = ret.content;
630
- ret.content = [...content, ...toolContent];
631
- }
632
- return ret;
633
- }
634
- function toolMessageToAnthropicMessage(base) {
635
- const role = "user";
636
- const toolUseId = base.tool_call_id;
637
- const toolContent = contentToAnthropicContent(base.content);
638
- const content = [
639
- {
640
- type: "tool_result",
641
- tool_use_id: toolUseId,
642
- content: toolContent,
643
- },
644
- ];
645
- return {
646
- role,
647
- content,
648
- };
649
- }
650
- function baseToAnthropicMessage(base) {
651
- const type = base._getType();
652
- switch (type) {
653
- case "human":
654
- return baseRoleToAnthropicMessage(base, "user");
655
- case "ai":
656
- return aiMessageToAnthropicMessage(base);
657
- case "tool":
658
- return toolMessageToAnthropicMessage(base);
659
- case "system":
660
- // System messages are handled in formatSystem()
661
- return undefined;
662
- default:
663
- console.warn(`Unknown BaseMessage type: ${type}`, base);
664
- return undefined;
665
- }
666
- }
667
- function formatMessages(input) {
668
- const ret = [];
669
- input.forEach((baseMessage) => {
670
- const anthropicMessage = baseToAnthropicMessage(baseMessage);
671
- if (anthropicMessage) {
672
- ret.push(anthropicMessage);
673
- }
674
- });
675
- return ret;
676
- }
677
- function formatSettings(parameters) {
678
- const ret = {
679
- stream: parameters?.streaming ?? false,
680
- max_tokens: parameters?.maxOutputTokens ?? 8192,
681
- };
682
- if (parameters.topP) {
683
- ret.top_p = parameters.topP;
684
- }
685
- if (parameters.topK) {
686
- ret.top_k = parameters.topK;
687
- }
688
- if (parameters.temperature) {
689
- ret.temperature = parameters.temperature;
690
- }
691
- if (parameters.stopSequences) {
692
- ret.stop_sequences = parameters.stopSequences;
693
- }
694
- return ret;
695
- }
696
- function contentComplexArrayToText(contentArray) {
697
- let ret = "";
698
- contentArray.forEach((content) => {
699
- const contentType = content?.type;
700
- if (contentType === "text") {
701
- const textContent = content;
702
- ret = `${ret}\n${textContent.text}`;
703
- }
704
- });
705
- return ret;
706
- }
707
- function formatSystem(input) {
708
- let ret = "";
709
- input.forEach((message) => {
710
- if (message._getType() === "system") {
711
- const content = message?.content;
712
- const contentString = typeof content === "string"
713
- ? content
714
- : contentComplexArrayToText(content);
715
- ret = `${ret}\n${contentString}`;
716
- }
717
- });
718
- return ret;
719
- }
720
- function formatGeminiTool(tool) {
721
- if (Object.hasOwn(tool, "functionDeclarations")) {
722
- const funcs = tool?.functionDeclarations ?? [];
723
- return funcs.map((func) => {
724
- const inputSchema = func.parameters;
725
- return {
726
- // type: "tool", // This may only be valid for models 20241022+
727
- name: func.name,
728
- description: func.description,
729
- input_schema: inputSchema,
730
- };
731
- });
732
- }
733
- else {
734
- console.warn(`Unable to format GeminiTool: ${JSON.stringify(tool, null, 1)}`);
735
- return [];
736
- }
737
- }
738
- function formatTool(tool) {
739
- if (Object.hasOwn(tool, "name")) {
740
- return [tool];
741
- }
742
- else {
743
- return formatGeminiTool(tool);
744
- }
745
- }
746
- function formatTools(parameters) {
747
- const tools = parameters?.tools ?? [];
748
- const ret = [];
749
- tools.forEach((tool) => {
750
- const anthropicTools = formatTool(tool);
751
- anthropicTools.forEach((anthropicTool) => {
752
- if (anthropicTool) {
753
- ret.push(anthropicTool);
754
- }
755
- });
756
- });
757
- return ret;
758
- }
759
- function formatToolChoice(parameters) {
760
- const choice = parameters?.tool_choice;
761
- if (!choice) {
762
- return undefined;
763
- }
764
- else if (typeof choice === "object") {
765
- return choice;
766
- }
767
- else {
768
- switch (choice) {
769
- case "any":
770
- case "auto":
771
- return {
772
- type: choice,
773
- };
774
- case "none":
775
- return undefined;
776
- default:
777
- return {
778
- type: "tool",
779
- name: choice,
780
- };
781
- }
782
- }
783
- }
784
- async function formatData(input, parameters) {
785
- const typedInput = input;
786
- const anthropicVersion = formatAnthropicVersion();
787
- const messages = formatMessages(typedInput);
788
- const settings = formatSettings(parameters);
789
- const system = formatSystem(typedInput);
790
- const tools = formatTools(parameters);
791
- const toolChoice = formatToolChoice(parameters);
792
- const ret = {
793
- anthropic_version: anthropicVersion,
794
- messages,
795
- ...settings,
796
- };
797
- if (tools && tools.length && parameters?.tool_choice !== "none") {
798
- ret.tools = tools;
799
- }
800
- if (toolChoice) {
801
- ret.tool_choice = toolChoice;
802
- }
803
- if (system?.length) {
804
- ret.system = system;
805
- }
806
- if (config?.thinking) {
807
- ret.thinking = config?.thinking;
808
- }
809
- return ret;
810
- }
811
- return {
812
- responseToString,
813
- responseToChatGeneration,
814
- chunkToString,
815
- responseToBaseMessage,
816
- responseToChatResult,
817
- formatData,
818
- };
819
- }
820
- function validateClaudeParams(_params) {
821
- // FIXME - validate the parameters
7
+ function partToString(part) {
8
+ return "text" in part ? part.text : "";
9
+ }
10
+ function messageToString(message) {
11
+ const content = message?.content ?? [];
12
+ const ret = content.reduce((acc, part) => {
13
+ const str = partToString(part);
14
+ return acc + str;
15
+ }, "");
16
+ return ret;
17
+ }
18
+ function responseToString(response) {
19
+ const data = response.data;
20
+ switch (data?.type) {
21
+ case "message": return messageToString(data);
22
+ default: throw Error(`Unknown type: ${data?.type}`);
23
+ }
24
+ }
25
+ /**
26
+ * Normalize the AIMessageChunk.
27
+ * If the fields are just a string - use that as content.
28
+ * If the content is an array of just text fields, turn them into a string.
29
+ * @param fields
30
+ */
31
+ function newAIMessageChunk(fields) {
32
+ if (typeof fields === "string") return new __langchain_core_messages.AIMessageChunk(fields);
33
+ const ret = { ...fields };
34
+ if (Array.isArray(fields?.content)) {
35
+ let str = "";
36
+ fields.content.forEach((val) => {
37
+ if (str !== void 0 && val.type === "text") str = `${str}${val.text}`;
38
+ else str = void 0;
39
+ });
40
+ if (str) ret.content = str;
41
+ }
42
+ return new __langchain_core_messages.AIMessageChunk(ret);
43
+ }
44
+ function textContentToMessageFields(textContent) {
45
+ return { content: [textContent] };
46
+ }
47
+ function toolUseContentToMessageFields(toolUseContent) {
48
+ const tool = {
49
+ id: toolUseContent.id,
50
+ name: toolUseContent.name,
51
+ type: "tool_call",
52
+ args: toolUseContent.input
53
+ };
54
+ return {
55
+ content: [],
56
+ tool_calls: [tool]
57
+ };
58
+ }
59
+ function thinkingContentToMessageFields(thinkingContent) {
60
+ return { content: [thinkingContent] };
61
+ }
62
+ function redactedThinkingContentToMessageFields(thinkingContent) {
63
+ return { content: [thinkingContent] };
64
+ }
65
+ function anthropicContentToMessageFields(anthropicContent) {
66
+ const type = anthropicContent?.type;
67
+ switch (type) {
68
+ case "text": return textContentToMessageFields(anthropicContent);
69
+ case "tool_use": return toolUseContentToMessageFields(anthropicContent);
70
+ case "thinking": return thinkingContentToMessageFields(anthropicContent);
71
+ case "redacted_thinking": return redactedThinkingContentToMessageFields(anthropicContent);
72
+ default:
73
+ console.error(`Unknown message type: ${type}`, anthropicContent);
74
+ return void 0;
75
+ }
76
+ }
77
+ function contentToMessage(anthropicContent) {
78
+ const complexContent = [];
79
+ const toolCalls = [];
80
+ anthropicContent.forEach((ac) => {
81
+ const messageFields = anthropicContentToMessageFields(ac);
82
+ if (messageFields?.content) complexContent.push(...messageFields.content);
83
+ if (messageFields?.tool_calls) toolCalls.push(...messageFields.tool_calls);
84
+ });
85
+ const ret = {
86
+ content: complexContent,
87
+ tool_calls: toolCalls
88
+ };
89
+ return newAIMessageChunk(ret);
90
+ }
91
+ function messageToUsageMetadata(message) {
92
+ const usage = message?.usage;
93
+ const inputTokens = usage?.input_tokens ?? 0;
94
+ const outputTokens = usage?.output_tokens ?? 0;
95
+ const usageMetadata = {
96
+ input_tokens: inputTokens,
97
+ output_tokens: outputTokens,
98
+ total_tokens: inputTokens + outputTokens,
99
+ input_token_details: {
100
+ cache_read: usage?.cache_read_input_tokens ?? 0,
101
+ cache_creation: usage?.cache_creation_input_tokens ?? 0
102
+ }
103
+ };
104
+ return usageMetadata;
105
+ }
106
+ function messageToGenerationInfo(message) {
107
+ const usageMetadata = messageToUsageMetadata(message);
108
+ return {
109
+ usage_metadata: usageMetadata,
110
+ finish_reason: message.stop_reason
111
+ };
112
+ }
113
+ function messageToChatGeneration(responseMessage) {
114
+ const content = responseMessage?.content ?? [];
115
+ const text = messageToString(responseMessage);
116
+ const message = contentToMessage(content);
117
+ const generationInfo = messageToGenerationInfo(responseMessage);
118
+ return new __langchain_core_outputs.ChatGenerationChunk({
119
+ text,
120
+ message,
121
+ generationInfo
122
+ });
123
+ }
124
+ function messageStartToChatGeneration(event) {
125
+ const responseMessage = event.message;
126
+ return messageToChatGeneration(responseMessage);
127
+ }
128
+ function messageDeltaToChatGeneration(event) {
129
+ const responseMessage = event.delta;
130
+ return messageToChatGeneration(responseMessage);
131
+ }
132
+ function contentBlockStartTextToChatGeneration(event) {
133
+ const content = event.content_block;
134
+ const message = contentToMessage([content]);
135
+ if (!message) return null;
136
+ const text = "text" in content ? content.text : "";
137
+ return new __langchain_core_outputs.ChatGenerationChunk({
138
+ message,
139
+ text
140
+ });
141
+ }
142
+ function contentBlockStartToolUseToChatGeneration(event) {
143
+ const contentBlock = event.content_block;
144
+ const text = "";
145
+ const toolChunk = {
146
+ type: "tool_call_chunk",
147
+ index: event.index,
148
+ name: contentBlock.name,
149
+ id: contentBlock.id
150
+ };
151
+ if (typeof contentBlock.input === "object" && Object.keys(contentBlock.input).length > 0) toolChunk.args = JSON.stringify(contentBlock.input);
152
+ const toolChunks = [toolChunk];
153
+ const content = [{
154
+ index: event.index,
155
+ ...contentBlock
156
+ }];
157
+ const messageFields = {
158
+ content,
159
+ tool_call_chunks: toolChunks
160
+ };
161
+ const message = newAIMessageChunk(messageFields);
162
+ return new __langchain_core_outputs.ChatGenerationChunk({
163
+ message,
164
+ text
165
+ });
166
+ }
167
+ function contentBlockStartToChatGeneration(event) {
168
+ switch (event.content_block.type) {
169
+ case "text": return contentBlockStartTextToChatGeneration(event);
170
+ case "tool_use": return contentBlockStartToolUseToChatGeneration(event);
171
+ default:
172
+ console.warn(`Unexpected start content_block type: ${JSON.stringify(event)}`);
173
+ return null;
174
+ }
175
+ }
176
+ function contentBlockDeltaTextToChatGeneration(event) {
177
+ const delta = event.delta;
178
+ const text = delta?.text;
179
+ const message = newAIMessageChunk(text);
180
+ return new __langchain_core_outputs.ChatGenerationChunk({
181
+ message,
182
+ text
183
+ });
184
+ }
185
+ function contentBlockDeltaInputJsonDeltaToChatGeneration(event) {
186
+ const delta = event.delta;
187
+ const text = "";
188
+ const toolChunks = [{
189
+ index: event.index,
190
+ args: delta.partial_json
191
+ }];
192
+ const content = [{
193
+ index: event.index,
194
+ ...delta
195
+ }];
196
+ const messageFields = {
197
+ content,
198
+ tool_call_chunks: toolChunks
199
+ };
200
+ const message = newAIMessageChunk(messageFields);
201
+ return new __langchain_core_outputs.ChatGenerationChunk({
202
+ message,
203
+ text
204
+ });
205
+ }
206
+ function contentBlockDeltaToChatGeneration(event) {
207
+ switch (event.delta.type) {
208
+ case "text_delta": return contentBlockDeltaTextToChatGeneration(event);
209
+ case "input_json_delta": return contentBlockDeltaInputJsonDeltaToChatGeneration(event);
210
+ default:
211
+ console.warn(`Unexpected delta content_block type: ${JSON.stringify(event)}`);
212
+ return null;
213
+ }
214
+ }
215
+ function responseToChatGeneration(response) {
216
+ const data = response.data;
217
+ switch (data.type) {
218
+ case "message": return messageToChatGeneration(data);
219
+ case "message_start": return messageStartToChatGeneration(data);
220
+ case "message_delta": return messageDeltaToChatGeneration(data);
221
+ case "content_block_start": return contentBlockStartToChatGeneration(data);
222
+ case "content_block_delta": return contentBlockDeltaToChatGeneration(data);
223
+ case "ping":
224
+ case "message_stop":
225
+ case "content_block_stop": return null;
226
+ case "error": throw new Error(`Error while streaming results: ${JSON.stringify(data)}`);
227
+ default:
228
+ console.warn("Unknown data for responseToChatGeneration", data);
229
+ return null;
230
+ }
231
+ }
232
+ function chunkToString(chunk) {
233
+ if (chunk === null) return "";
234
+ else if (typeof chunk.content === "string") return chunk.content;
235
+ else if (chunk.content.length === 0) return "";
236
+ else if (chunk.content[0].type === "text") return chunk.content[0].text;
237
+ else throw new Error(`Unexpected chunk: ${chunk}`);
238
+ }
239
+ function responseToBaseMessage(response) {
240
+ const data = response.data;
241
+ const content = data?.content ?? [];
242
+ return contentToMessage(content);
243
+ }
244
+ function responseToChatResult(response) {
245
+ const message = response.data;
246
+ const generations = [];
247
+ const gen = responseToChatGeneration(response);
248
+ if (gen) generations.push(gen);
249
+ const llmOutput = messageToGenerationInfo(message);
250
+ return {
251
+ generations,
252
+ llmOutput
253
+ };
254
+ }
255
+ function formatAnthropicVersion() {
256
+ return config?.version ?? "vertex-2023-10-16";
257
+ }
258
+ function textContentToAnthropicContent(content) {
259
+ return content;
260
+ }
261
+ function extractMimeType(str) {
262
+ if (str.startsWith("data:")) return {
263
+ media_type: str.split(":")[1].split(";")[0],
264
+ data: str.split(",")[1]
265
+ };
266
+ return null;
267
+ }
268
+ function imageContentToAnthropicContent(content) {
269
+ const dataUrl = content.image_url;
270
+ const url = typeof dataUrl === "string" ? dataUrl : dataUrl?.url;
271
+ const urlInfo = extractMimeType(url);
272
+ if (!urlInfo) return void 0;
273
+ return {
274
+ type: "image",
275
+ source: {
276
+ type: "base64",
277
+ ...urlInfo
278
+ }
279
+ };
280
+ }
281
+ function thinkingContentToAnthropicContent(content) {
282
+ return {
283
+ type: "thinking",
284
+ thinking: content.thinking,
285
+ signature: content.signature
286
+ };
287
+ }
288
+ function redactedThinkingContentToAnthropicContent(content) {
289
+ return {
290
+ type: "redacted_thinking",
291
+ data: content.data
292
+ };
293
+ }
294
+ function contentComplexToAnthropicContent(content) {
295
+ const type = content?.type;
296
+ switch (type) {
297
+ case "text": return textContentToAnthropicContent(content);
298
+ case "image_url": return imageContentToAnthropicContent(content);
299
+ case "thinking": return thinkingContentToAnthropicContent(content);
300
+ case "redacted_thinking": return redactedThinkingContentToAnthropicContent(content);
301
+ default:
302
+ console.warn(`Unexpected content type: ${type}`, content);
303
+ return void 0;
304
+ }
305
+ }
306
+ const anthropicContentConverter = {
307
+ providerName: "anthropic",
308
+ fromStandardTextBlock(block) {
309
+ return {
310
+ type: "text",
311
+ text: block.text,
312
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}
313
+ };
314
+ },
315
+ fromStandardImageBlock(block) {
316
+ if (block.source_type === "url") {
317
+ const data = (0, __langchain_core_messages.parseBase64DataUrl)({
318
+ dataUrl: block.url,
319
+ asTypedArray: false
320
+ });
321
+ if (data) return {
322
+ type: "image",
323
+ source: {
324
+ type: "base64",
325
+ data: data.data,
326
+ media_type: data.mime_type
327
+ },
328
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}
329
+ };
330
+ else return {
331
+ type: "image",
332
+ source: {
333
+ type: "url",
334
+ url: block.url,
335
+ media_type: block.mime_type ?? ""
336
+ },
337
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}
338
+ };
339
+ } else if (block.source_type === "base64") return {
340
+ type: "image",
341
+ source: {
342
+ type: "base64",
343
+ data: block.data,
344
+ media_type: block.mime_type ?? ""
345
+ },
346
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}
347
+ };
348
+ else throw new Error(`Unsupported image source type: ${block.source_type}`);
349
+ },
350
+ fromStandardFileBlock(block) {
351
+ const mime_type = (block.mime_type ?? "").split(";")[0];
352
+ if (block.source_type === "url") {
353
+ if (mime_type === "application/pdf" || mime_type === "") return {
354
+ type: "document",
355
+ source: {
356
+ type: "url",
357
+ url: block.url,
358
+ media_type: block.mime_type ?? ""
359
+ },
360
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},
361
+ ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},
362
+ ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},
363
+ ...block.metadata?.title || block.metadata?.filename || block.metadata?.name ? { title: block.metadata?.title || block.metadata?.filename || block.metadata?.name } : {}
364
+ };
365
+ throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`);
366
+ } else if (block.source_type === "text") if (mime_type === "text/plain" || mime_type === "") return {
367
+ type: "document",
368
+ source: {
369
+ type: "text",
370
+ data: block.text,
371
+ media_type: block.mime_type ?? ""
372
+ },
373
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},
374
+ ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},
375
+ ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},
376
+ ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {}
377
+ };
378
+ else throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`);
379
+ else if (block.source_type === "base64") if (mime_type === "application/pdf" || mime_type === "") return {
380
+ type: "document",
381
+ source: {
382
+ type: "base64",
383
+ data: block.data,
384
+ media_type: "application/pdf"
385
+ },
386
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},
387
+ ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},
388
+ ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},
389
+ ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {}
390
+ };
391
+ else if ([
392
+ "image/jpeg",
393
+ "image/png",
394
+ "image/gif",
395
+ "image/webp"
396
+ ].includes(mime_type)) return {
397
+ type: "document",
398
+ source: {
399
+ type: "content",
400
+ content: [{
401
+ type: "image",
402
+ source: {
403
+ type: "base64",
404
+ data: block.data,
405
+ media_type: mime_type
406
+ }
407
+ }]
408
+ },
409
+ ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {},
410
+ ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {},
411
+ ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {},
412
+ ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {}
413
+ };
414
+ else throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`);
415
+ else throw new Error(`Unsupported file source type: ${block.source_type}`);
416
+ }
417
+ };
418
+ function contentToAnthropicContent(content) {
419
+ const ca = typeof content === "string" ? [{
420
+ type: "text",
421
+ text: content
422
+ }] : content;
423
+ return ca.map((complex) => (0, __langchain_core_messages.isDataContentBlock)(complex) ? (0, __langchain_core_messages.convertToProviderContentBlock)(complex, anthropicContentConverter) : contentComplexToAnthropicContent(complex)).filter(Boolean);
424
+ }
425
+ function toolCallToAnthropicContent(toolCall) {
426
+ return {
427
+ type: "tool_use",
428
+ id: toolCall.id,
429
+ name: toolCall.name,
430
+ input: toolCall.args
431
+ };
432
+ }
433
+ function toolCallsToAnthropicContent(toolCalls) {
434
+ if (toolCalls === void 0) return [];
435
+ return toolCalls.map(toolCallToAnthropicContent);
436
+ }
437
+ function baseRoleToAnthropicMessage(base, role) {
438
+ const content = contentToAnthropicContent(base.content);
439
+ return {
440
+ role,
441
+ content
442
+ };
443
+ }
444
+ function aiMessageToAnthropicMessage(base) {
445
+ const ret = baseRoleToAnthropicMessage(base, "assistant");
446
+ const toolContent = toolCallsToAnthropicContent(base.tool_calls);
447
+ if (toolContent.length > 0) {
448
+ const content = ret.content;
449
+ ret.content = [...content, ...toolContent];
450
+ }
451
+ return ret;
452
+ }
453
+ function toolMessageToAnthropicMessage(base) {
454
+ const role = "user";
455
+ const toolUseId = base.tool_call_id;
456
+ const toolContent = contentToAnthropicContent(base.content);
457
+ const content = [{
458
+ type: "tool_result",
459
+ tool_use_id: toolUseId,
460
+ content: toolContent
461
+ }];
462
+ return {
463
+ role,
464
+ content
465
+ };
466
+ }
467
+ function baseToAnthropicMessage(base) {
468
+ const type = base._getType();
469
+ switch (type) {
470
+ case "human": return baseRoleToAnthropicMessage(base, "user");
471
+ case "ai": return aiMessageToAnthropicMessage(base);
472
+ case "tool": return toolMessageToAnthropicMessage(base);
473
+ case "system": return void 0;
474
+ default:
475
+ console.warn(`Unknown BaseMessage type: ${type}`, base);
476
+ return void 0;
477
+ }
478
+ }
479
+ function formatMessages(input) {
480
+ const ret = [];
481
+ input.forEach((baseMessage) => {
482
+ const anthropicMessage = baseToAnthropicMessage(baseMessage);
483
+ if (anthropicMessage) ret.push(anthropicMessage);
484
+ });
485
+ return ret;
486
+ }
487
+ function formatSettings(parameters) {
488
+ const ret = {
489
+ stream: parameters?.streaming ?? false,
490
+ max_tokens: parameters?.maxOutputTokens ?? 8192
491
+ };
492
+ if (parameters.topP) ret.top_p = parameters.topP;
493
+ if (parameters.topK) ret.top_k = parameters.topK;
494
+ if (parameters.temperature) ret.temperature = parameters.temperature;
495
+ if (parameters.stopSequences) ret.stop_sequences = parameters.stopSequences;
496
+ return ret;
497
+ }
498
+ function contentComplexArrayToText(contentArray) {
499
+ let ret = "";
500
+ contentArray.forEach((content) => {
501
+ const contentType = content?.type;
502
+ if (contentType === "text") {
503
+ const textContent = content;
504
+ ret = `${ret}\n${textContent.text}`;
505
+ }
506
+ });
507
+ return ret;
508
+ }
509
+ function formatSystem(input) {
510
+ let ret = "";
511
+ input.forEach((message) => {
512
+ if (message._getType() === "system") {
513
+ const content = message?.content;
514
+ const contentString = typeof content === "string" ? content : contentComplexArrayToText(content);
515
+ ret = `${ret}\n${contentString}`;
516
+ }
517
+ });
518
+ return ret;
519
+ }
520
+ function formatGeminiTool(tool) {
521
+ if (Object.hasOwn(tool, "functionDeclarations")) {
522
+ const funcs = tool?.functionDeclarations ?? [];
523
+ return funcs.map((func) => {
524
+ const inputSchema = func.parameters;
525
+ return {
526
+ name: func.name,
527
+ description: func.description,
528
+ input_schema: inputSchema
529
+ };
530
+ });
531
+ } else {
532
+ console.warn(`Unable to format GeminiTool: ${JSON.stringify(tool, null, 1)}`);
533
+ return [];
534
+ }
535
+ }
536
+ function formatTool(tool) {
537
+ if (Object.hasOwn(tool, "name")) return [tool];
538
+ else return formatGeminiTool(tool);
539
+ }
540
+ function formatTools(parameters) {
541
+ const tools = parameters?.tools ?? [];
542
+ const ret = [];
543
+ tools.forEach((tool) => {
544
+ const anthropicTools = formatTool(tool);
545
+ anthropicTools.forEach((anthropicTool) => {
546
+ if (anthropicTool) ret.push(anthropicTool);
547
+ });
548
+ });
549
+ return ret;
550
+ }
551
+ function formatToolChoice(parameters) {
552
+ const choice = parameters?.tool_choice;
553
+ if (!choice) return void 0;
554
+ else if (typeof choice === "object") return choice;
555
+ else switch (choice) {
556
+ case "any":
557
+ case "auto": return { type: choice };
558
+ case "none": return void 0;
559
+ default: return {
560
+ type: "tool",
561
+ name: choice
562
+ };
563
+ }
564
+ }
565
+ async function formatData(input, parameters) {
566
+ const typedInput = input;
567
+ const anthropicVersion = formatAnthropicVersion();
568
+ const messages = formatMessages(typedInput);
569
+ const settings = formatSettings(parameters);
570
+ const system = formatSystem(typedInput);
571
+ const tools = formatTools(parameters);
572
+ const toolChoice = formatToolChoice(parameters);
573
+ const ret = {
574
+ anthropic_version: anthropicVersion,
575
+ messages,
576
+ ...settings
577
+ };
578
+ if (tools && tools.length && parameters?.tool_choice !== "none") ret.tools = tools;
579
+ if (toolChoice) ret.tool_choice = toolChoice;
580
+ if (system?.length) ret.system = system;
581
+ if (config?.thinking) ret.thinking = config?.thinking;
582
+ return ret;
583
+ }
584
+ return {
585
+ responseToString,
586
+ responseToChatGeneration,
587
+ chunkToString,
588
+ responseToBaseMessage,
589
+ responseToChatResult,
590
+ formatData
591
+ };
822
592
  }
593
+ function validateClaudeParams(_params) {}
823
594
  function isModelClaude(modelName) {
824
- return modelName.toLowerCase().startsWith("claude");
595
+ return modelName.toLowerCase().startsWith("claude");
825
596
  }
597
+
598
+ //#endregion
599
+ exports.getAnthropicAPI = getAnthropicAPI;
600
+ exports.isModelClaude = isModelClaude;
601
+ exports.validateClaudeParams = validateClaudeParams;
602
+ //# sourceMappingURL=anthropic.cjs.map