@langchain/google-common 0.2.17 → 1.0.0

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