@llumiverse/drivers 0.24.0-dev.202601221707 → 0.24.0-dev.20260203.164053Z

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 (227) hide show
  1. package/package.json +3 -3
  2. package/src/bedrock/index.ts +2 -109
  3. package/src/vertexai/index.ts +18 -37
  4. package/src/vertexai/models/claude.ts +1 -136
  5. package/lib/cjs/adobe/firefly.js +0 -120
  6. package/lib/cjs/adobe/firefly.js.map +0 -1
  7. package/lib/cjs/azure/azure_foundry.js +0 -432
  8. package/lib/cjs/azure/azure_foundry.js.map +0 -1
  9. package/lib/cjs/bedrock/converse.js +0 -285
  10. package/lib/cjs/bedrock/converse.js.map +0 -1
  11. package/lib/cjs/bedrock/index.js +0 -1186
  12. package/lib/cjs/bedrock/index.js.map +0 -1
  13. package/lib/cjs/bedrock/nova-image-payload.js +0 -207
  14. package/lib/cjs/bedrock/nova-image-payload.js.map +0 -1
  15. package/lib/cjs/bedrock/payloads.js +0 -3
  16. package/lib/cjs/bedrock/payloads.js.map +0 -1
  17. package/lib/cjs/bedrock/s3.js +0 -107
  18. package/lib/cjs/bedrock/s3.js.map +0 -1
  19. package/lib/cjs/bedrock/twelvelabs.js +0 -87
  20. package/lib/cjs/bedrock/twelvelabs.js.map +0 -1
  21. package/lib/cjs/groq/index.js +0 -323
  22. package/lib/cjs/groq/index.js.map +0 -1
  23. package/lib/cjs/huggingface_ie.js +0 -201
  24. package/lib/cjs/huggingface_ie.js.map +0 -1
  25. package/lib/cjs/index.js +0 -31
  26. package/lib/cjs/index.js.map +0 -1
  27. package/lib/cjs/mistral/index.js +0 -173
  28. package/lib/cjs/mistral/index.js.map +0 -1
  29. package/lib/cjs/mistral/types.js +0 -83
  30. package/lib/cjs/mistral/types.js.map +0 -1
  31. package/lib/cjs/openai/azure_openai.js +0 -72
  32. package/lib/cjs/openai/azure_openai.js.map +0 -1
  33. package/lib/cjs/openai/index.js +0 -665
  34. package/lib/cjs/openai/index.js.map +0 -1
  35. package/lib/cjs/openai/openai.js +0 -21
  36. package/lib/cjs/openai/openai.js.map +0 -1
  37. package/lib/cjs/openai/openai_compatible.js +0 -62
  38. package/lib/cjs/openai/openai_compatible.js.map +0 -1
  39. package/lib/cjs/openai/openai_format.js +0 -131
  40. package/lib/cjs/openai/openai_format.js.map +0 -1
  41. package/lib/cjs/package.json +0 -3
  42. package/lib/cjs/replicate.js +0 -275
  43. package/lib/cjs/replicate.js.map +0 -1
  44. package/lib/cjs/test-driver/TestErrorCompletionStream.js +0 -20
  45. package/lib/cjs/test-driver/TestErrorCompletionStream.js.map +0 -1
  46. package/lib/cjs/test-driver/TestValidationErrorCompletionStream.js +0 -24
  47. package/lib/cjs/test-driver/TestValidationErrorCompletionStream.js.map +0 -1
  48. package/lib/cjs/test-driver/index.js +0 -109
  49. package/lib/cjs/test-driver/index.js.map +0 -1
  50. package/lib/cjs/test-driver/utils.js +0 -30
  51. package/lib/cjs/test-driver/utils.js.map +0 -1
  52. package/lib/cjs/togetherai/index.js +0 -126
  53. package/lib/cjs/togetherai/index.js.map +0 -1
  54. package/lib/cjs/togetherai/interfaces.js +0 -3
  55. package/lib/cjs/togetherai/interfaces.js.map +0 -1
  56. package/lib/cjs/vertexai/debug.js +0 -12
  57. package/lib/cjs/vertexai/debug.js.map +0 -1
  58. package/lib/cjs/vertexai/embeddings/embeddings-image.js +0 -27
  59. package/lib/cjs/vertexai/embeddings/embeddings-image.js.map +0 -1
  60. package/lib/cjs/vertexai/embeddings/embeddings-text.js +0 -23
  61. package/lib/cjs/vertexai/embeddings/embeddings-text.js.map +0 -1
  62. package/lib/cjs/vertexai/index.js +0 -594
  63. package/lib/cjs/vertexai/index.js.map +0 -1
  64. package/lib/cjs/vertexai/models/claude.js +0 -597
  65. package/lib/cjs/vertexai/models/claude.js.map +0 -1
  66. package/lib/cjs/vertexai/models/gemini.js +0 -871
  67. package/lib/cjs/vertexai/models/gemini.js.map +0 -1
  68. package/lib/cjs/vertexai/models/imagen.js +0 -303
  69. package/lib/cjs/vertexai/models/imagen.js.map +0 -1
  70. package/lib/cjs/vertexai/models/llama.js +0 -183
  71. package/lib/cjs/vertexai/models/llama.js.map +0 -1
  72. package/lib/cjs/vertexai/models.js +0 -35
  73. package/lib/cjs/vertexai/models.js.map +0 -1
  74. package/lib/cjs/watsonx/index.js +0 -161
  75. package/lib/cjs/watsonx/index.js.map +0 -1
  76. package/lib/cjs/watsonx/interfaces.js +0 -3
  77. package/lib/cjs/watsonx/interfaces.js.map +0 -1
  78. package/lib/cjs/xai/index.js +0 -65
  79. package/lib/cjs/xai/index.js.map +0 -1
  80. package/lib/esm/adobe/firefly.js +0 -116
  81. package/lib/esm/adobe/firefly.js.map +0 -1
  82. package/lib/esm/azure/azure_foundry.js +0 -426
  83. package/lib/esm/azure/azure_foundry.js.map +0 -1
  84. package/lib/esm/bedrock/converse.js +0 -278
  85. package/lib/esm/bedrock/converse.js.map +0 -1
  86. package/lib/esm/bedrock/index.js +0 -1181
  87. package/lib/esm/bedrock/index.js.map +0 -1
  88. package/lib/esm/bedrock/nova-image-payload.js +0 -203
  89. package/lib/esm/bedrock/nova-image-payload.js.map +0 -1
  90. package/lib/esm/bedrock/payloads.js +0 -2
  91. package/lib/esm/bedrock/payloads.js.map +0 -1
  92. package/lib/esm/bedrock/s3.js +0 -99
  93. package/lib/esm/bedrock/s3.js.map +0 -1
  94. package/lib/esm/bedrock/twelvelabs.js +0 -84
  95. package/lib/esm/bedrock/twelvelabs.js.map +0 -1
  96. package/lib/esm/groq/index.js +0 -316
  97. package/lib/esm/groq/index.js.map +0 -1
  98. package/lib/esm/huggingface_ie.js +0 -197
  99. package/lib/esm/huggingface_ie.js.map +0 -1
  100. package/lib/esm/index.js +0 -15
  101. package/lib/esm/index.js.map +0 -1
  102. package/lib/esm/mistral/index.js +0 -169
  103. package/lib/esm/mistral/index.js.map +0 -1
  104. package/lib/esm/mistral/types.js +0 -80
  105. package/lib/esm/mistral/types.js.map +0 -1
  106. package/lib/esm/openai/azure_openai.js +0 -68
  107. package/lib/esm/openai/azure_openai.js.map +0 -1
  108. package/lib/esm/openai/index.js +0 -660
  109. package/lib/esm/openai/index.js.map +0 -1
  110. package/lib/esm/openai/openai.js +0 -14
  111. package/lib/esm/openai/openai.js.map +0 -1
  112. package/lib/esm/openai/openai_compatible.js +0 -55
  113. package/lib/esm/openai/openai_compatible.js.map +0 -1
  114. package/lib/esm/openai/openai_format.js +0 -127
  115. package/lib/esm/openai/openai_format.js.map +0 -1
  116. package/lib/esm/replicate.js +0 -268
  117. package/lib/esm/replicate.js.map +0 -1
  118. package/lib/esm/test-driver/TestErrorCompletionStream.js +0 -16
  119. package/lib/esm/test-driver/TestErrorCompletionStream.js.map +0 -1
  120. package/lib/esm/test-driver/TestValidationErrorCompletionStream.js +0 -20
  121. package/lib/esm/test-driver/TestValidationErrorCompletionStream.js.map +0 -1
  122. package/lib/esm/test-driver/index.js +0 -91
  123. package/lib/esm/test-driver/index.js.map +0 -1
  124. package/lib/esm/test-driver/utils.js +0 -25
  125. package/lib/esm/test-driver/utils.js.map +0 -1
  126. package/lib/esm/togetherai/index.js +0 -122
  127. package/lib/esm/togetherai/index.js.map +0 -1
  128. package/lib/esm/togetherai/interfaces.js +0 -2
  129. package/lib/esm/togetherai/interfaces.js.map +0 -1
  130. package/lib/esm/vertexai/debug.js +0 -6
  131. package/lib/esm/vertexai/debug.js.map +0 -1
  132. package/lib/esm/vertexai/embeddings/embeddings-image.js +0 -24
  133. package/lib/esm/vertexai/embeddings/embeddings-image.js.map +0 -1
  134. package/lib/esm/vertexai/embeddings/embeddings-text.js +0 -20
  135. package/lib/esm/vertexai/embeddings/embeddings-text.js.map +0 -1
  136. package/lib/esm/vertexai/index.js +0 -589
  137. package/lib/esm/vertexai/index.js.map +0 -1
  138. package/lib/esm/vertexai/models/claude.js +0 -590
  139. package/lib/esm/vertexai/models/claude.js.map +0 -1
  140. package/lib/esm/vertexai/models/gemini.js +0 -866
  141. package/lib/esm/vertexai/models/gemini.js.map +0 -1
  142. package/lib/esm/vertexai/models/imagen.js +0 -299
  143. package/lib/esm/vertexai/models/imagen.js.map +0 -1
  144. package/lib/esm/vertexai/models/llama.js +0 -179
  145. package/lib/esm/vertexai/models/llama.js.map +0 -1
  146. package/lib/esm/vertexai/models.js +0 -32
  147. package/lib/esm/vertexai/models.js.map +0 -1
  148. package/lib/esm/watsonx/index.js +0 -157
  149. package/lib/esm/watsonx/index.js.map +0 -1
  150. package/lib/esm/watsonx/interfaces.js +0 -2
  151. package/lib/esm/watsonx/interfaces.js.map +0 -1
  152. package/lib/esm/xai/index.js +0 -58
  153. package/lib/esm/xai/index.js.map +0 -1
  154. package/lib/types/adobe/firefly.d.ts +0 -30
  155. package/lib/types/adobe/firefly.d.ts.map +0 -1
  156. package/lib/types/azure/azure_foundry.d.ts +0 -52
  157. package/lib/types/azure/azure_foundry.d.ts.map +0 -1
  158. package/lib/types/bedrock/converse.d.ts +0 -9
  159. package/lib/types/bedrock/converse.d.ts.map +0 -1
  160. package/lib/types/bedrock/index.d.ts +0 -83
  161. package/lib/types/bedrock/index.d.ts.map +0 -1
  162. package/lib/types/bedrock/nova-image-payload.d.ts +0 -74
  163. package/lib/types/bedrock/nova-image-payload.d.ts.map +0 -1
  164. package/lib/types/bedrock/payloads.d.ts +0 -12
  165. package/lib/types/bedrock/payloads.d.ts.map +0 -1
  166. package/lib/types/bedrock/s3.d.ts +0 -23
  167. package/lib/types/bedrock/s3.d.ts.map +0 -1
  168. package/lib/types/bedrock/twelvelabs.d.ts +0 -50
  169. package/lib/types/bedrock/twelvelabs.d.ts.map +0 -1
  170. package/lib/types/groq/index.d.ts +0 -27
  171. package/lib/types/groq/index.d.ts.map +0 -1
  172. package/lib/types/huggingface_ie.d.ts +0 -35
  173. package/lib/types/huggingface_ie.d.ts.map +0 -1
  174. package/lib/types/index.d.ts +0 -15
  175. package/lib/types/index.d.ts.map +0 -1
  176. package/lib/types/mistral/index.d.ts +0 -25
  177. package/lib/types/mistral/index.d.ts.map +0 -1
  178. package/lib/types/mistral/types.d.ts +0 -132
  179. package/lib/types/mistral/types.d.ts.map +0 -1
  180. package/lib/types/openai/azure_openai.d.ts +0 -25
  181. package/lib/types/openai/azure_openai.d.ts.map +0 -1
  182. package/lib/types/openai/index.d.ts +0 -31
  183. package/lib/types/openai/index.d.ts.map +0 -1
  184. package/lib/types/openai/openai.d.ts +0 -15
  185. package/lib/types/openai/openai.d.ts.map +0 -1
  186. package/lib/types/openai/openai_compatible.d.ts +0 -26
  187. package/lib/types/openai/openai_compatible.d.ts.map +0 -1
  188. package/lib/types/openai/openai_format.d.ts +0 -21
  189. package/lib/types/openai/openai_format.d.ts.map +0 -1
  190. package/lib/types/replicate.d.ts +0 -48
  191. package/lib/types/replicate.d.ts.map +0 -1
  192. package/lib/types/test-driver/TestErrorCompletionStream.d.ts +0 -9
  193. package/lib/types/test-driver/TestErrorCompletionStream.d.ts.map +0 -1
  194. package/lib/types/test-driver/TestValidationErrorCompletionStream.d.ts +0 -9
  195. package/lib/types/test-driver/TestValidationErrorCompletionStream.d.ts.map +0 -1
  196. package/lib/types/test-driver/index.d.ts +0 -24
  197. package/lib/types/test-driver/index.d.ts.map +0 -1
  198. package/lib/types/test-driver/utils.d.ts +0 -5
  199. package/lib/types/test-driver/utils.d.ts.map +0 -1
  200. package/lib/types/togetherai/index.d.ts +0 -23
  201. package/lib/types/togetherai/index.d.ts.map +0 -1
  202. package/lib/types/togetherai/interfaces.d.ts +0 -96
  203. package/lib/types/togetherai/interfaces.d.ts.map +0 -1
  204. package/lib/types/vertexai/debug.d.ts +0 -2
  205. package/lib/types/vertexai/debug.d.ts.map +0 -1
  206. package/lib/types/vertexai/embeddings/embeddings-image.d.ts +0 -11
  207. package/lib/types/vertexai/embeddings/embeddings-image.d.ts.map +0 -1
  208. package/lib/types/vertexai/embeddings/embeddings-text.d.ts +0 -10
  209. package/lib/types/vertexai/embeddings/embeddings-text.d.ts.map +0 -1
  210. package/lib/types/vertexai/index.d.ts +0 -69
  211. package/lib/types/vertexai/index.d.ts.map +0 -1
  212. package/lib/types/vertexai/models/claude.d.ts +0 -40
  213. package/lib/types/vertexai/models/claude.d.ts.map +0 -1
  214. package/lib/types/vertexai/models/gemini.d.ts +0 -18
  215. package/lib/types/vertexai/models/gemini.d.ts.map +0 -1
  216. package/lib/types/vertexai/models/imagen.d.ts +0 -75
  217. package/lib/types/vertexai/models/imagen.d.ts.map +0 -1
  218. package/lib/types/vertexai/models/llama.d.ts +0 -20
  219. package/lib/types/vertexai/models/llama.d.ts.map +0 -1
  220. package/lib/types/vertexai/models.d.ts +0 -15
  221. package/lib/types/vertexai/models.d.ts.map +0 -1
  222. package/lib/types/watsonx/index.d.ts +0 -27
  223. package/lib/types/watsonx/index.d.ts.map +0 -1
  224. package/lib/types/watsonx/interfaces.d.ts +0 -65
  225. package/lib/types/watsonx/interfaces.d.ts.map +0 -1
  226. package/lib/types/xai/index.d.ts +0 -18
  227. package/lib/types/xai/index.d.ts.map +0 -1
@@ -1,1186 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BedrockDriver = void 0;
4
- exports.fixOrphanedToolUse = fixOrphanedToolUse;
5
- const client_bedrock_1 = require("@aws-sdk/client-bedrock");
6
- const client_bedrock_runtime_1 = require("@aws-sdk/client-bedrock-runtime");
7
- const client_s3_1 = require("@aws-sdk/client-s3");
8
- const core_1 = require("@llumiverse/core");
9
- const async_1 = require("@llumiverse/core/async");
10
- const formatters_1 = require("@llumiverse/core/formatters");
11
- const mnemonist_1 = require("mnemonist");
12
- const converse_js_1 = require("./converse.js");
13
- const nova_image_payload_js_1 = require("./nova-image-payload.js");
14
- const s3_js_1 = require("./s3.js");
15
- const twelvelabs_js_1 = require("./twelvelabs.js");
16
- const supportStreamingCache = new mnemonist_1.LRUCache(4096);
17
- var BedrockModelType;
18
- (function (BedrockModelType) {
19
- BedrockModelType["FoundationModel"] = "foundation-model";
20
- BedrockModelType["InferenceProfile"] = "inference-profile";
21
- BedrockModelType["CustomModel"] = "custom-model";
22
- BedrockModelType["Unknown"] = "unknown";
23
- })(BedrockModelType || (BedrockModelType = {}));
24
- ;
25
- function converseFinishReason(reason) {
26
- //Possible values:
27
- //end_turn | tool_use | max_tokens | stop_sequence | guardrail_intervened | content_filtered
28
- if (!reason)
29
- return undefined;
30
- switch (reason) {
31
- case 'end_turn': return "stop";
32
- case 'max_tokens': return "length";
33
- default: return reason;
34
- }
35
- }
36
- //Used to get a max_token value when not specified in the model options. Claude requires it to be set.
37
- function maxTokenFallbackClaude(option) {
38
- const modelOptions = option.model_options;
39
- if (modelOptions && typeof modelOptions.max_tokens === "number") {
40
- return modelOptions.max_tokens;
41
- }
42
- else {
43
- const thinking_budget = modelOptions?.thinking_budget_tokens ?? 0;
44
- let maxSupportedTokens = (0, core_1.getMaxTokensLimitBedrock)(option.model) ?? 8192; // Should always return a number for claude, 8192 is to satisfy the TypeScript type checker;
45
- // Fallback to the default max tokens limit for the model
46
- if (option.model.includes('claude-3-7-sonnet') && (modelOptions?.thinking_budget_tokens ?? 0) < 48000) {
47
- maxSupportedTokens = 64000; // Claude 3.7 can go up to 128k with a beta header, but when no max tokens is specified, we default to 64k.
48
- }
49
- return Math.min(16000 + thinking_budget, maxSupportedTokens); // Cap to 16k, to avoid taking up too much context window and quota.
50
- }
51
- }
52
- class BedrockDriver extends core_1.AbstractDriver {
53
- static PROVIDER = "bedrock";
54
- provider = BedrockDriver.PROVIDER;
55
- _executor;
56
- _service;
57
- _service_region;
58
- constructor(options) {
59
- super(options);
60
- if (!options.region) {
61
- throw new Error("No region found. Set the region in the environment's endpoint URL.");
62
- }
63
- }
64
- getExecutor() {
65
- if (!this._executor) {
66
- this._executor = new client_bedrock_runtime_1.BedrockRuntime({
67
- region: this.options.region,
68
- credentials: this.options.credentials,
69
- });
70
- }
71
- return this._executor;
72
- }
73
- getService(region = this.options.region) {
74
- if (!this._service || this._service_region != region) {
75
- this._service = new client_bedrock_1.Bedrock({
76
- region: region,
77
- credentials: this.options.credentials,
78
- });
79
- this._service_region = region;
80
- }
81
- return this._service;
82
- }
83
- async formatPrompt(segments, opts) {
84
- if (opts.model.includes("canvas")) {
85
- return await (0, formatters_1.formatNovaPrompt)(segments, opts.result_schema);
86
- }
87
- if (opts.model.includes("twelvelabs.pegasus")) {
88
- return await (0, twelvelabs_js_1.formatTwelvelabsPegasusPrompt)(segments, opts);
89
- }
90
- return await (0, converse_js_1.formatConversePrompt)(segments, opts);
91
- }
92
- getExtractedExecution(result, _prompt, options) {
93
- let resultText = "";
94
- let reasoning = "";
95
- if (result.output?.message?.content) {
96
- for (const content of result.output.message.content) {
97
- // Get text output
98
- if (content.text) {
99
- resultText += content.text;
100
- }
101
- else if (content.reasoningContent) {
102
- // Get reasoning content only if include_thoughts is true
103
- const claudeOptions = options?.model_options;
104
- if (claudeOptions?.include_thoughts) {
105
- if (content.reasoningContent.reasoningText) {
106
- reasoning += content.reasoningContent.reasoningText.text;
107
- }
108
- else if (content.reasoningContent.redactedContent) {
109
- // Handle redacted thinking content
110
- const redactedData = new TextDecoder().decode(content.reasoningContent.redactedContent);
111
- reasoning += `[Redacted thinking: ${redactedData}]`;
112
- }
113
- }
114
- else {
115
- this.logger.info("[Bedrock] Not outputting reasoning content as include_thoughts is false");
116
- }
117
- }
118
- else {
119
- // Get content block type
120
- const type = Object.keys(content).find(key => key !== '$unknown' && content[key] !== undefined);
121
- this.logger.info({ type }, "[Bedrock] Unsupported content response type:");
122
- }
123
- }
124
- // Add spacing if we have reasoning content
125
- if (reasoning) {
126
- reasoning += '\n\n';
127
- }
128
- }
129
- const completionResult = {
130
- result: reasoning + resultText ? [{ type: "text", value: reasoning + resultText }] : [],
131
- token_usage: {
132
- prompt: result.usage?.inputTokens,
133
- result: result.usage?.outputTokens,
134
- total: result.usage?.totalTokens,
135
- },
136
- finish_reason: converseFinishReason(result.stopReason),
137
- };
138
- return completionResult;
139
- }
140
- ;
141
- getExtractedStream(result, _prompt, options) {
142
- let output = "";
143
- let reasoning = "";
144
- let stop_reason = "";
145
- let token_usage;
146
- // Check if we should include thoughts
147
- const shouldIncludeThoughts = options && options.model_options?.include_thoughts;
148
- // Handle content block start events (for reasoning blocks)
149
- if (result.contentBlockStart) {
150
- // Handle redacted content at block start
151
- if (result.contentBlockStart.start && 'reasoningContent' in result.contentBlockStart.start && shouldIncludeThoughts) {
152
- const reasoningStart = result.contentBlockStart.start;
153
- if (reasoningStart.reasoningContent?.redactedContent) {
154
- const redactedData = new TextDecoder().decode(reasoningStart.reasoningContent.redactedContent);
155
- reasoning = `[Redacted thinking: ${redactedData}]`;
156
- }
157
- }
158
- }
159
- // Handle content block deltas (text and reasoning)
160
- if (result.contentBlockDelta) {
161
- const delta = result.contentBlockDelta.delta;
162
- if (delta?.text) {
163
- output = delta.text;
164
- }
165
- else if (delta?.reasoningContent && shouldIncludeThoughts) {
166
- if (delta.reasoningContent.text) {
167
- reasoning = delta.reasoningContent.text;
168
- }
169
- else if (delta.reasoningContent.redactedContent) {
170
- const redactedData = new TextDecoder().decode(delta.reasoningContent.redactedContent);
171
- reasoning = `[Redacted thinking: ${redactedData}]`;
172
- }
173
- else if (delta.reasoningContent.signature) {
174
- // Handle signature updates for reasoning content - end of thinking
175
- reasoning = "\n\n";
176
- // Putting logging here so it only triggers once.
177
- this.logger.info("[Bedrock] Not outputting reasoning content as include_thoughts is false");
178
- }
179
- }
180
- else if (delta) {
181
- // Get content block type
182
- const type = Object.keys(delta).find(key => key !== '$unknown' && delta[key] !== undefined);
183
- this.logger.info({ type }, "[Bedrock] Unsupported content response type:");
184
- }
185
- }
186
- // Handle content block stop events
187
- if (result.contentBlockStop) {
188
- // Content block ended - could be end of reasoning or text block
189
- // Add minimal spacing for reasoning blocks if not already present
190
- if (reasoning && !reasoning.endsWith('\n\n') && shouldIncludeThoughts) {
191
- reasoning += '\n\n';
192
- }
193
- }
194
- if (result.messageStop) {
195
- stop_reason = result.messageStop.stopReason ?? "";
196
- }
197
- if (result.metadata) {
198
- token_usage = {
199
- prompt: result.metadata.usage?.inputTokens,
200
- result: result.metadata.usage?.outputTokens,
201
- total: result.metadata.usage?.totalTokens,
202
- };
203
- }
204
- const completionResult = {
205
- result: reasoning + output ? [{ type: "text", value: reasoning + output }] : [],
206
- token_usage: token_usage,
207
- finish_reason: converseFinishReason(stop_reason),
208
- };
209
- return completionResult;
210
- }
211
- ;
212
- extractRegion(modelString, defaultRegion) {
213
- // Match region in full ARN pattern
214
- const arnMatch = modelString.match(/arn:aws[^:]*:bedrock:([^:]+):/);
215
- if (arnMatch) {
216
- return arnMatch[1];
217
- }
218
- // Match common AWS regions directly in string
219
- const regionMatch = modelString.match(/(?:us|eu|ap|sa|ca|me|af)[-](east|west|central|south|north|southeast|southwest|northeast|northwest)[-][1-9]/);
220
- if (regionMatch) {
221
- return regionMatch[0];
222
- }
223
- return defaultRegion;
224
- }
225
- async getCanStream(model, type) {
226
- let canStream = false;
227
- let error = null;
228
- const region = this.extractRegion(model, this.options.region);
229
- if (type == BedrockModelType.FoundationModel || type == BedrockModelType.Unknown) {
230
- try {
231
- const response = await this.getService(region).getFoundationModel({
232
- modelIdentifier: model
233
- });
234
- canStream = response.modelDetails?.responseStreamingSupported ?? false;
235
- return canStream;
236
- }
237
- catch (e) {
238
- error = e;
239
- }
240
- }
241
- if (type == BedrockModelType.InferenceProfile || type == BedrockModelType.Unknown) {
242
- try {
243
- const response = await this.getService(region).getInferenceProfile({
244
- inferenceProfileIdentifier: model
245
- });
246
- canStream = await this.getCanStream(response.models?.[0].modelArn ?? "", BedrockModelType.FoundationModel);
247
- return canStream;
248
- }
249
- catch (e) {
250
- error = e;
251
- }
252
- }
253
- if (type == BedrockModelType.CustomModel || type == BedrockModelType.Unknown) {
254
- try {
255
- const response = await this.getService(region).getCustomModel({
256
- modelIdentifier: model
257
- });
258
- canStream = await this.getCanStream(response.baseModelArn ?? "", BedrockModelType.FoundationModel);
259
- return canStream;
260
- }
261
- catch (e) {
262
- error = e;
263
- }
264
- }
265
- if (error) {
266
- console.warn("Error on canStream check for model: " + model + " region detected: " + region, error);
267
- }
268
- return canStream;
269
- }
270
- async canStream(options) {
271
- // // TwelveLabs Pegasus supports streaming according to the documentation
272
- // if (options.model.includes("twelvelabs.pegasus")) {
273
- // return true;
274
- // }
275
- let canStream = supportStreamingCache.get(options.model);
276
- if (canStream == null) {
277
- let type = BedrockModelType.Unknown;
278
- if (options.model.includes("foundation-model")) {
279
- type = BedrockModelType.FoundationModel;
280
- }
281
- else if (options.model.includes("inference-profile")) {
282
- type = BedrockModelType.InferenceProfile;
283
- }
284
- else if (options.model.includes("custom-model")) {
285
- type = BedrockModelType.CustomModel;
286
- }
287
- canStream = await this.getCanStream(options.model, type);
288
- supportStreamingCache.set(options.model, canStream);
289
- }
290
- return canStream;
291
- }
292
- /**
293
- * Build conversation context after streaming completion.
294
- * Reconstructs the assistant message from accumulated results and applies stripping.
295
- */
296
- buildStreamingConversation(prompt, result, toolUse, options) {
297
- // Only handle ConverseRequest prompts (not NovaMessagesPrompt or TwelvelabsPegasusRequest)
298
- if (options.model.includes("canvas") || options.model.includes("twelvelabs.pegasus")) {
299
- return undefined;
300
- }
301
- const conversePrompt = prompt;
302
- const completionResults = result;
303
- // Convert accumulated results to text content for assistant message
304
- const textContent = completionResults
305
- .map(r => {
306
- switch (r.type) {
307
- case 'text':
308
- return r.value;
309
- case 'json':
310
- return typeof r.value === 'string' ? r.value : JSON.stringify(r.value);
311
- case 'image':
312
- // Skip images in conversation - they're in the result
313
- return '';
314
- default:
315
- return String(r.value || '');
316
- }
317
- })
318
- .join('');
319
- // Deserialize any base64-encoded binary data back to Uint8Array
320
- const incomingConversation = (0, core_1.deserializeBinaryFromStorage)(options.conversation);
321
- // Start with the conversation from options combined with the prompt
322
- let conversation = updateConversation(incomingConversation, conversePrompt);
323
- // Build assistant message content
324
- const messageContent = [];
325
- if (textContent) {
326
- messageContent.push({ text: textContent });
327
- }
328
- // Add tool use blocks if present
329
- if (toolUse && toolUse.length > 0) {
330
- for (const tool of toolUse) {
331
- messageContent.push({
332
- toolUse: {
333
- toolUseId: tool.id,
334
- name: tool.tool_name,
335
- input: tool.tool_input,
336
- }
337
- });
338
- }
339
- }
340
- // Add assistant message
341
- const assistantMessage = {
342
- messages: [{
343
- content: messageContent.length > 0 ? messageContent : [{ text: '' }],
344
- role: "assistant"
345
- }],
346
- modelId: conversePrompt.modelId,
347
- };
348
- conversation = updateConversation(conversation, assistantMessage);
349
- // Increment turn counter
350
- conversation = (0, core_1.incrementConversationTurn)(conversation);
351
- // Apply stripping based on options
352
- const currentTurn = (0, core_1.getConversationMeta)(conversation).turnNumber;
353
- const stripOptions = {
354
- keepForTurns: options.stripImagesAfterTurns ?? Infinity,
355
- currentTurn,
356
- textMaxTokens: options.stripTextMaxTokens
357
- };
358
- let processedConversation = (0, core_1.stripBinaryFromConversation)(conversation, stripOptions);
359
- processedConversation = (0, core_1.truncateLargeTextInConversation)(processedConversation, stripOptions);
360
- return processedConversation;
361
- }
362
- async requestTextCompletion(prompt, options) {
363
- // Handle Twelvelabs Pegasus models
364
- if (options.model.includes("twelvelabs.pegasus")) {
365
- return this.requestTwelvelabsPegasusCompletion(prompt, options);
366
- }
367
- // Handle other Bedrock models that use Converse API
368
- const conversePrompt = prompt;
369
- // Deserialize any base64-encoded binary data back to Uint8Array before API call
370
- const incomingConversation = (0, core_1.deserializeBinaryFromStorage)(options.conversation);
371
- let conversation = updateConversation(incomingConversation, conversePrompt);
372
- const payload = this.preparePayload(conversation, options);
373
- const executor = this.getExecutor();
374
- const res = await executor.converse({
375
- ...payload,
376
- });
377
- conversation = updateConversation(conversation, {
378
- messages: [res.output?.message ?? { content: [{ text: "" }], role: "assistant" }],
379
- modelId: conversePrompt.modelId,
380
- });
381
- // Increment turn counter for deferred stripping
382
- conversation = (0, core_1.incrementConversationTurn)(conversation);
383
- let tool_use = undefined;
384
- //Get tool requests, we check tool use regardless of finish reason, as you can hit length and still get a valid response.
385
- tool_use = res.output?.message?.content?.reduce((tools, c) => {
386
- if (c.toolUse) {
387
- tools.push({
388
- tool_name: c.toolUse.name ?? "",
389
- tool_input: c.toolUse.input,
390
- id: c.toolUse.toolUseId ?? "",
391
- });
392
- }
393
- return tools;
394
- }, []);
395
- //If no tools were used, set to undefined
396
- if (tool_use && tool_use.length == 0) {
397
- tool_use = undefined;
398
- }
399
- // Strip/serialize binary data based on options.stripImagesAfterTurns
400
- const currentTurn = (0, core_1.getConversationMeta)(conversation).turnNumber;
401
- const stripOptions = {
402
- keepForTurns: options.stripImagesAfterTurns ?? Infinity,
403
- currentTurn,
404
- textMaxTokens: options.stripTextMaxTokens
405
- };
406
- let processedConversation = (0, core_1.stripBinaryFromConversation)(conversation, stripOptions);
407
- // Truncate large text content if configured
408
- processedConversation = (0, core_1.truncateLargeTextInConversation)(processedConversation, stripOptions);
409
- const completion = {
410
- ...this.getExtractedExecution(res, conversePrompt, options),
411
- original_response: options.include_original_response ? res : undefined,
412
- conversation: processedConversation,
413
- tool_use: tool_use,
414
- };
415
- return completion;
416
- }
417
- async requestTwelvelabsPegasusCompletion(prompt, options) {
418
- const executor = this.getExecutor();
419
- const res = await executor.invokeModel({
420
- modelId: options.model,
421
- contentType: "application/json",
422
- accept: "application/json",
423
- body: JSON.stringify(prompt),
424
- });
425
- const decoder = new TextDecoder();
426
- const body = decoder.decode(res.body);
427
- const result = JSON.parse(body);
428
- // Extract the response according to TwelveLabs Pegasus format
429
- let finishReason;
430
- switch (result.finishReason) {
431
- case "stop":
432
- finishReason = "stop";
433
- break;
434
- case "length":
435
- finishReason = "length";
436
- break;
437
- default:
438
- finishReason = result.finishReason;
439
- }
440
- return {
441
- result: result.message ? [{ type: "text", value: result.message }] : [],
442
- finish_reason: finishReason,
443
- original_response: options.include_original_response ? result : undefined,
444
- };
445
- }
446
- async requestTwelvelabsPegasusCompletionStream(prompt, options) {
447
- const executor = this.getExecutor();
448
- const res = await executor.invokeModelWithResponseStream({
449
- modelId: options.model,
450
- contentType: "application/json",
451
- accept: "application/json",
452
- body: JSON.stringify(prompt),
453
- });
454
- if (!res.body) {
455
- throw new Error("[Bedrock] Stream not found in response");
456
- }
457
- return (0, async_1.transformAsyncIterator)(res.body, (chunk) => {
458
- if (chunk.chunk?.bytes) {
459
- const decoder = new TextDecoder();
460
- const body = decoder.decode(chunk.chunk.bytes);
461
- try {
462
- const result = JSON.parse(body);
463
- // Extract streaming response according to TwelveLabs Pegasus format
464
- let finishReason;
465
- if (result.finishReason) {
466
- switch (result.finishReason) {
467
- case "stop":
468
- finishReason = "stop";
469
- break;
470
- case "length":
471
- finishReason = "length";
472
- break;
473
- default:
474
- finishReason = result.finishReason;
475
- }
476
- }
477
- return {
478
- result: result.delta || result.message ? [{ type: "text", value: result.delta || result.message || "" }] : [],
479
- finish_reason: finishReason,
480
- };
481
- }
482
- catch (error) {
483
- // If JSON parsing fails, return empty chunk
484
- return {
485
- result: [],
486
- };
487
- }
488
- }
489
- return {
490
- result: [],
491
- };
492
- });
493
- }
494
- async requestTextCompletionStream(prompt, options) {
495
- // Handle Twelvelabs Pegasus models
496
- if (options.model.includes("twelvelabs.pegasus")) {
497
- return this.requestTwelvelabsPegasusCompletionStream(prompt, options);
498
- }
499
- // Handle other Bedrock models that use Converse API
500
- const conversePrompt = prompt;
501
- // Include conversation history (same as non-streaming)
502
- // Deserialize any base64-encoded binary data back to Uint8Array before API call
503
- const incomingConversation = (0, core_1.deserializeBinaryFromStorage)(options.conversation);
504
- const conversation = updateConversation(incomingConversation, conversePrompt);
505
- const payload = this.preparePayload(conversation, options);
506
- const executor = this.getExecutor();
507
- return executor.converseStream({
508
- ...payload,
509
- }).then((res) => {
510
- const stream = res.stream;
511
- if (!stream) {
512
- throw new Error("[Bedrock] Stream not found in response");
513
- }
514
- return (0, async_1.transformAsyncIterator)(stream, (streamSegment) => {
515
- return this.getExtractedStream(streamSegment, conversePrompt, options);
516
- });
517
- }).catch((err) => {
518
- this.logger.error({ error: err }, "[Bedrock] Failed to stream");
519
- throw err;
520
- });
521
- }
522
- preparePayload(prompt, options) {
523
- const model_options = options.model_options ?? { _option_id: "text-fallback" };
524
- let additionalField = {};
525
- let supportsJSONPrefill = false;
526
- if (options.model.includes("amazon")) {
527
- supportsJSONPrefill = true;
528
- //Titan models also exists but does not support any additional options
529
- if (options.model.includes("nova")) {
530
- additionalField = { inferenceConfig: { topK: model_options.top_k } };
531
- }
532
- }
533
- else if (options.model.includes("claude")) {
534
- const claude_options = model_options;
535
- const thinking = claude_options.thinking_mode ?? false;
536
- supportsJSONPrefill = !thinking;
537
- if (options.model.includes("claude-3-7") || options.model.includes("-4-")) {
538
- additionalField = {
539
- ...additionalField,
540
- reasoning_config: {
541
- type: thinking ? "enabled" : "disabled",
542
- budget_tokens: thinking ? (claude_options.thinking_budget_tokens ?? 1024) : undefined,
543
- }
544
- };
545
- if (thinking && options.model.includes("claude-3-7-sonnet") &&
546
- ((claude_options.max_tokens ?? 0) > 64000 || (claude_options.thinking_budget_tokens ?? 0) > 64000)) {
547
- additionalField = {
548
- ...additionalField,
549
- anthropic_beta: ["output-128k-2025-02-19"]
550
- };
551
- }
552
- }
553
- //Needs max_tokens to be set
554
- if (!model_options.max_tokens) {
555
- model_options.max_tokens = maxTokenFallbackClaude(options);
556
- }
557
- additionalField = { ...additionalField, top_k: model_options.top_k };
558
- }
559
- else if (options.model.includes("meta")) {
560
- //LLaMA models support no additional options
561
- }
562
- else if (options.model.includes("mistral")) {
563
- //7B instruct and 8x7B instruct
564
- if (options.model.includes("7b")) {
565
- additionalField = { top_k: model_options.top_k };
566
- //Does not support system messages
567
- if (prompt.system && prompt.system?.length != 0) {
568
- prompt.messages?.push((0, converse_js_1.converseSystemToMessages)(prompt.system));
569
- prompt.system = undefined;
570
- prompt.messages = (0, converse_js_1.converseConcatMessages)(prompt.messages);
571
- }
572
- }
573
- else {
574
- //Other models such as Mistral Small,Large and Large 2
575
- //Support no additional fields.
576
- }
577
- }
578
- else if (options.model.includes("ai21")) {
579
- //Jamba models support no additional options
580
- //Jurassic 2 models do.
581
- if (options.model.includes("j2")) {
582
- additionalField = {
583
- presencePenalty: { scale: model_options.presence_penalty },
584
- frequencyPenalty: { scale: model_options.frequency_penalty },
585
- };
586
- //Does not support system messages
587
- if (prompt.system && prompt.system?.length != 0) {
588
- prompt.messages?.push((0, converse_js_1.converseSystemToMessages)(prompt.system));
589
- prompt.system = undefined;
590
- prompt.messages = (0, converse_js_1.converseConcatMessages)(prompt.messages);
591
- }
592
- }
593
- }
594
- else if (options.model.includes("cohere.command")) {
595
- // If last message is "```json", remove it.
596
- //Command R and R plus
597
- if (options.model.includes("cohere.command-r")) {
598
- additionalField = {
599
- k: model_options.top_k,
600
- frequency_penalty: model_options.frequency_penalty,
601
- presence_penalty: model_options.presence_penalty,
602
- };
603
- }
604
- else {
605
- // Command non-R
606
- additionalField = { k: model_options.top_k };
607
- //Does not support system messages
608
- if (prompt.system && prompt.system?.length != 0) {
609
- prompt.messages?.push((0, converse_js_1.converseSystemToMessages)(prompt.system));
610
- prompt.system = undefined;
611
- prompt.messages = (0, converse_js_1.converseConcatMessages)(prompt.messages);
612
- }
613
- }
614
- }
615
- else if (options.model.includes("palmyra")) {
616
- const palmyraOptions = model_options;
617
- additionalField = {
618
- seed: palmyraOptions?.seed,
619
- presence_penalty: palmyraOptions?.presence_penalty,
620
- frequency_penalty: palmyraOptions?.frequency_penalty,
621
- min_tokens: palmyraOptions?.min_tokens,
622
- };
623
- }
624
- else if (options.model.includes("deepseek")) {
625
- //DeepSeek models support no additional options
626
- }
627
- else if (options.model.includes("gpt-oss")) {
628
- const gptOssOptions = model_options;
629
- additionalField = {
630
- reasoning_effort: gptOssOptions?.reasoning_effort,
631
- };
632
- }
633
- //If last message is "```json", add corresponding ``` as a stop sequence.
634
- if (prompt.messages && prompt.messages.length > 0) {
635
- if (prompt.messages[prompt.messages.length - 1].content?.[0].text === "```json") {
636
- const stopSeq = model_options.stop_sequence;
637
- if (!stopSeq) {
638
- model_options.stop_sequence = ["```"];
639
- }
640
- else if (!stopSeq.includes("```")) {
641
- stopSeq.push("```");
642
- model_options.stop_sequence = stopSeq;
643
- }
644
- }
645
- }
646
- const tool_defs = getToolDefinitions(options.tools);
647
- // Use prefill when there is a schema and tools are not being used
648
- if (supportsJSONPrefill && options.result_schema && !tool_defs) {
649
- prompt.messages = (0, converse_js_1.converseJSONprefill)(prompt.messages);
650
- }
651
- // Clean undefined values from additionalField since AWS Bedrock requires valid JSON
652
- // and will throw an exception for unrecognized parameters
653
- const cleanedAdditionalFields = removeUndefinedValues(additionalField);
654
- const cleanedModelOptions = removeUndefinedValues({
655
- maxTokens: model_options.max_tokens,
656
- temperature: model_options.temperature,
657
- topP: model_options.top_p,
658
- stopSequences: model_options.stop_sequence,
659
- });
660
- //Construct the final request payload
661
- // We only add fields that are defined to avoid AWS errors
662
- const request = {
663
- modelId: options.model,
664
- };
665
- if (prompt.messages) {
666
- request.messages = prompt.messages;
667
- }
668
- if (prompt.system) {
669
- request.system = prompt.system;
670
- }
671
- if (Object.keys(cleanedModelOptions).length > 0) {
672
- request.inferenceConfig = cleanedModelOptions;
673
- }
674
- if (Object.keys(cleanedAdditionalFields).length > 0) {
675
- request.additionalModelRequestFields = cleanedAdditionalFields;
676
- }
677
- if (tool_defs?.length) {
678
- request.toolConfig = {
679
- tools: tool_defs,
680
- };
681
- }
682
- return request;
683
- }
684
- isImageModel(model) {
685
- return model.includes("titan-image") || model.includes("stable-diffusion") || model.includes("nova-canvas");
686
- }
687
- async requestImageGeneration(prompt, options) {
688
- if (options.model_options?._option_id !== "bedrock-nova-canvas") {
689
- this.logger.warn({ options: options.model_options }, "Invalid model options");
690
- }
691
- const model_options = options.model_options;
692
- const executor = this.getExecutor();
693
- const taskType = model_options.taskType ?? nova_image_payload_js_1.NovaImageGenerationTaskType.TEXT_IMAGE;
694
- this.logger.info("Task type: " + taskType);
695
- if (typeof prompt === "string") {
696
- throw new Error("Bad prompt format");
697
- }
698
- const payload = await (0, nova_image_payload_js_1.formatNovaImageGenerationPayload)(taskType, prompt, options);
699
- const res = await executor.invokeModel({
700
- modelId: options.model,
701
- contentType: "application/json",
702
- accept: "application/json",
703
- body: JSON.stringify(payload),
704
- }, {
705
- requestTimeout: 60000 * 5
706
- });
707
- const decoder = new TextDecoder();
708
- const body = decoder.decode(res.body);
709
- const bedrockResult = JSON.parse(body);
710
- return {
711
- error: bedrockResult.error,
712
- result: bedrockResult.images.map((image) => ({
713
- type: "image",
714
- value: image
715
- }))
716
- };
717
- }
718
- async startTraining(dataset, options) {
719
- //convert options.params to Record<string, string>
720
- const params = {};
721
- for (const [key, value] of Object.entries(options.params || {})) {
722
- params[key] = String(value);
723
- }
724
- if (!this.options.training_bucket) {
725
- throw new Error("Training cannot nbe used since the 'training_bucket' property was not specified in driver options");
726
- }
727
- const s3 = new client_s3_1.S3Client({ region: this.options.region, credentials: this.options.credentials });
728
- const stream = await dataset.getStream();
729
- const upload = await (0, s3_js_1.forceUploadFile)(s3, stream, this.options.training_bucket, dataset.name);
730
- const service = this.getService();
731
- const response = await service.send(new client_bedrock_1.CreateModelCustomizationJobCommand({
732
- jobName: options.name + "-job",
733
- customModelName: options.name,
734
- roleArn: this.options.training_role_arn || undefined,
735
- baseModelIdentifier: options.model,
736
- clientRequestToken: "llumiverse-" + Date.now(),
737
- trainingDataConfig: {
738
- s3Uri: `s3://${upload.Bucket}/${upload.Key}`,
739
- },
740
- outputDataConfig: undefined,
741
- hyperParameters: params,
742
- //TODO not supported?
743
- //customizationType: "FINE_TUNING",
744
- }));
745
- const job = await service.send(new client_bedrock_1.GetModelCustomizationJobCommand({
746
- jobIdentifier: response.jobArn
747
- }));
748
- return jobInfo(job, response.jobArn);
749
- }
750
- async cancelTraining(jobId) {
751
- const service = this.getService();
752
- await service.send(new client_bedrock_1.StopModelCustomizationJobCommand({
753
- jobIdentifier: jobId
754
- }));
755
- const job = await service.send(new client_bedrock_1.GetModelCustomizationJobCommand({
756
- jobIdentifier: jobId
757
- }));
758
- return jobInfo(job, jobId);
759
- }
760
- async getTrainingJob(jobId) {
761
- const service = this.getService();
762
- const job = await service.send(new client_bedrock_1.GetModelCustomizationJobCommand({
763
- jobIdentifier: jobId
764
- }));
765
- return jobInfo(job, jobId);
766
- }
767
- // ===================== management API ==================
768
- async validateConnection() {
769
- const service = this.getService();
770
- this.logger.debug("[Bedrock] validating connection", service.config.credentials.name);
771
- //return true as if the client has been initialized, it means the connection is valid
772
- return true;
773
- }
774
- async listTrainableModels() {
775
- this.logger.debug("[Bedrock] listing trainable models");
776
- return this._listModels(m => m.customizationsSupported ? m.customizationsSupported.includes("FINE_TUNING") : false);
777
- }
778
- async listModels() {
779
- this.logger.debug("[Bedrock] listing models");
780
- // exclude trainable models since they are not executable
781
- // exclude embedding models, not to be used for typical completions.
782
- const filter = (m) => (m.inferenceTypesSupported?.includes("ON_DEMAND") && !m.outputModalities?.includes("EMBEDDING")) ?? false;
783
- return this._listModels(filter);
784
- }
785
- async _listModels(foundationFilter) {
786
- const service = this.getService();
787
- const [foundationModelsList, customModelsList, inferenceProfilesList] = await Promise.all([
788
- service.listFoundationModels({}).catch(() => {
789
- this.logger.warn("[Bedrock] Can't list foundation models. Check if the user has the right permissions.");
790
- return undefined;
791
- }),
792
- service.listCustomModels({}).catch(() => {
793
- this.logger.warn("[Bedrock] Can't list custom models. Check if the user has the right permissions.");
794
- return undefined;
795
- }),
796
- service.listInferenceProfiles({}).catch(() => {
797
- this.logger.warn("[Bedrock] Can't list inference profiles. Check if the user has the right permissions.");
798
- return undefined;
799
- }),
800
- ]);
801
- if (!foundationModelsList?.modelSummaries) {
802
- throw new Error("Foundation models not found");
803
- }
804
- let foundationModels = foundationModelsList.modelSummaries || [];
805
- if (foundationFilter) {
806
- foundationModels = foundationModels.filter(foundationFilter);
807
- }
808
- const supportedPublishers = ["amazon", "anthropic", "cohere", "ai21",
809
- "mistral", "meta", "deepseek", "writer",
810
- "openai", "twelvelabs", "qwen"];
811
- const unsupportedModelsByPublisher = {
812
- amazon: ["titan-image-generator", "nova-reel", "nova-sonic", "rerank"],
813
- anthropic: [],
814
- cohere: ["rerank", "embed"],
815
- ai21: [],
816
- mistral: [],
817
- meta: [],
818
- deepseek: [],
819
- writer: [],
820
- openai: [],
821
- twelvelabs: ["marengo"],
822
- qwen: [],
823
- };
824
- // Helper function to check if model should be filtered out
825
- const shouldIncludeModel = (modelId, providerName) => {
826
- if (!modelId || !providerName)
827
- return false;
828
- const normalizedProvider = providerName.toLowerCase();
829
- // Check if provider is supported
830
- const isProviderSupported = supportedPublishers.some(provider => normalizedProvider.includes(provider));
831
- if (!isProviderSupported)
832
- return false;
833
- // Check if model is in the unsupported list for its provider
834
- for (const provider of supportedPublishers) {
835
- if (normalizedProvider.includes(provider)) {
836
- const unsupportedModels = unsupportedModelsByPublisher[provider] || [];
837
- return !unsupportedModels.some(unsupported => modelId.toLowerCase().includes(unsupported));
838
- }
839
- }
840
- return true;
841
- };
842
- foundationModels = foundationModels.filter(m => shouldIncludeModel(m.modelId, m.providerName));
843
- const aiModels = foundationModels.map((m) => {
844
- if (!m.modelId) {
845
- throw new Error("modelId not found");
846
- }
847
- const modelCapability = (0, core_1.getModelCapabilities)(m.modelArn ?? m.modelId, this.provider);
848
- const model = {
849
- id: m.modelArn ?? m.modelId,
850
- name: `${m.providerName} ${m.modelName}`,
851
- provider: this.provider,
852
- owner: m.providerName,
853
- can_stream: m.responseStreamingSupported ?? false,
854
- input_modalities: m.inputModalities ? formatAmazonModalities(m.inputModalities) : (0, core_1.modelModalitiesToArray)(modelCapability.input),
855
- output_modalities: m.outputModalities ? formatAmazonModalities(m.outputModalities) : (0, core_1.modelModalitiesToArray)(modelCapability.input),
856
- tool_support: modelCapability.tool_support,
857
- };
858
- return model;
859
- });
860
- //add custom models
861
- if (customModelsList?.modelSummaries) {
862
- customModelsList.modelSummaries.forEach((m) => {
863
- if (!m.modelArn) {
864
- throw new Error("Model ID not found");
865
- }
866
- const modelCapability = (0, core_1.getModelCapabilities)(m.modelArn, this.provider);
867
- const model = {
868
- id: m.modelArn,
869
- name: m.modelName ?? m.modelArn,
870
- provider: this.provider,
871
- owner: "custom",
872
- description: `Custom model from ${m.baseModelName}`,
873
- is_custom: true,
874
- input_modalities: (0, core_1.modelModalitiesToArray)(modelCapability.input),
875
- output_modalities: (0, core_1.modelModalitiesToArray)(modelCapability.output),
876
- tool_support: modelCapability.tool_support,
877
- };
878
- aiModels.push(model);
879
- this.validateConnection;
880
- });
881
- }
882
- //add inference profiles
883
- if (inferenceProfilesList?.inferenceProfileSummaries) {
884
- inferenceProfilesList.inferenceProfileSummaries.forEach((p) => {
885
- if (!p.inferenceProfileArn) {
886
- throw new Error("Profile ARN not found");
887
- }
888
- // Apply the same filtering logic to inference profiles based on their name
889
- const profileId = p.inferenceProfileId || "";
890
- const profileName = p.inferenceProfileName || "";
891
- // Extract provider name from profile name or ID
892
- let providerName = "";
893
- for (const provider of supportedPublishers) {
894
- if (profileName.toLowerCase().includes(provider) || profileId.toLowerCase().includes(provider)) {
895
- providerName = provider;
896
- break;
897
- }
898
- }
899
- const modelCapability = (0, core_1.getModelCapabilities)(p.inferenceProfileArn ?? p.inferenceProfileId, this.provider);
900
- if (providerName && shouldIncludeModel(profileId, providerName)) {
901
- const model = {
902
- id: p.inferenceProfileArn ?? p.inferenceProfileId,
903
- name: p.inferenceProfileName ?? p.inferenceProfileArn,
904
- provider: this.provider,
905
- owner: providerName,
906
- input_modalities: (0, core_1.modelModalitiesToArray)(modelCapability.input),
907
- output_modalities: (0, core_1.modelModalitiesToArray)(modelCapability.output),
908
- tool_support: modelCapability.tool_support,
909
- };
910
- aiModels.push(model);
911
- }
912
- });
913
- }
914
- return aiModels;
915
- }
916
- async generateEmbeddings({ text, image, model }) {
917
- this.logger.info("[Bedrock] Generating embeddings with model " + model);
918
- // Handle TwelveLabs Marengo models
919
- if (model?.includes("twelvelabs.marengo")) {
920
- return this.generateTwelvelabsMarengoEmbeddings({ text, image, model });
921
- }
922
- // Handle other Bedrock embedding models
923
- const defaultModel = image ? "amazon.titan-embed-image-v1" : "amazon.titan-embed-text-v2:0";
924
- const modelID = model ?? defaultModel;
925
- const invokeBody = {
926
- inputText: text,
927
- inputImage: image
928
- };
929
- const executor = this.getExecutor();
930
- const res = await executor.invokeModel({
931
- modelId: modelID,
932
- contentType: "application/json",
933
- body: JSON.stringify(invokeBody),
934
- });
935
- const decoder = new TextDecoder();
936
- const body = decoder.decode(res.body);
937
- const result = JSON.parse(body);
938
- if (!result.embedding) {
939
- throw new Error("Embeddings not found");
940
- }
941
- return {
942
- values: result.embedding,
943
- model: modelID,
944
- token_count: result.inputTextTokenCount
945
- };
946
- }
947
- async generateTwelvelabsMarengoEmbeddings({ text, image, model }) {
948
- const executor = this.getExecutor();
949
- // Prepare the request payload for TwelveLabs Marengo
950
- let invokeBody = {
951
- inputType: "text"
952
- };
953
- if (text) {
954
- invokeBody.inputText = text;
955
- invokeBody.inputType = "text";
956
- }
957
- if (image) {
958
- // For the embeddings interface, image is expected to be base64
959
- invokeBody.mediaSource = {
960
- base64String: image
961
- };
962
- invokeBody.inputType = "image";
963
- }
964
- const res = await executor.invokeModel({
965
- modelId: model,
966
- contentType: "application/json",
967
- accept: "application/json",
968
- body: JSON.stringify(invokeBody),
969
- });
970
- const decoder = new TextDecoder();
971
- const body = decoder.decode(res.body);
972
- const result = JSON.parse(body);
973
- // TwelveLabs Marengo returns embedding data
974
- if (!result.embedding) {
975
- throw new Error("Embeddings not found in TwelveLabs Marengo response");
976
- }
977
- return {
978
- values: result.embedding,
979
- model: model,
980
- // TwelveLabs Marengo doesn't return token count in the same way
981
- token_count: undefined
982
- };
983
- }
984
- /**
985
- * Cleanup AWS SDK clients when the driver is evicted from the cache.
986
- */
987
- destroy() {
988
- this._executor?.destroy();
989
- this._service?.destroy();
990
- }
991
- }
992
- exports.BedrockDriver = BedrockDriver;
993
- function jobInfo(job, jobId) {
994
- const jobStatus = job.status;
995
- let status = core_1.TrainingJobStatus.running;
996
- let details;
997
- if (jobStatus === client_bedrock_1.ModelCustomizationJobStatus.COMPLETED) {
998
- status = core_1.TrainingJobStatus.succeeded;
999
- }
1000
- else if (jobStatus === client_bedrock_1.ModelCustomizationJobStatus.FAILED) {
1001
- status = core_1.TrainingJobStatus.failed;
1002
- details = job.failureMessage || "error";
1003
- }
1004
- else if (jobStatus === client_bedrock_1.ModelCustomizationJobStatus.STOPPED) {
1005
- status = core_1.TrainingJobStatus.cancelled;
1006
- }
1007
- else {
1008
- status = core_1.TrainingJobStatus.running;
1009
- details = jobStatus;
1010
- }
1011
- job.baseModelArn;
1012
- return {
1013
- id: jobId,
1014
- model: job.outputModelArn,
1015
- status,
1016
- details
1017
- };
1018
- }
1019
- function getToolDefinitions(tools) {
1020
- return tools ? tools.map(getToolDefinition) : undefined;
1021
- }
1022
- function getToolDefinition(tool) {
1023
- return {
1024
- toolSpec: {
1025
- name: tool.name,
1026
- description: tool.description,
1027
- inputSchema: {
1028
- json: tool.input_schema,
1029
- }
1030
- }
1031
- };
1032
- }
1033
- /**
1034
- * Recursively removes undefined values from an object.
1035
- * AWS Bedrock's additionalModelRequestFields must be valid JSON, and undefined is not valid JSON.
1036
- * Any unrecognized parameters will cause an exception.
1037
- */
1038
- function removeUndefinedValues(obj) {
1039
- if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) {
1040
- return obj;
1041
- }
1042
- const cleaned = {};
1043
- for (const [key, value] of Object.entries(obj)) {
1044
- if (value !== undefined) {
1045
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
1046
- const cleanedNested = removeUndefinedValues(value);
1047
- // Only include nested objects if they have properties after cleaning
1048
- if (Object.keys(cleanedNested).length > 0) {
1049
- cleaned[key] = cleanedNested;
1050
- }
1051
- }
1052
- else {
1053
- cleaned[key] = value;
1054
- }
1055
- }
1056
- }
1057
- return cleaned;
1058
- }
1059
- /**
1060
- * Update the conversation messages
1061
- * @param prompt
1062
- * @param response
1063
- * @returns
1064
- */
1065
- function updateConversation(conversation, prompt) {
1066
- const combinedMessages = [...(conversation?.messages || []), ...(prompt.messages || [])];
1067
- const combinedSystem = prompt.system || conversation?.system;
1068
- // Fix orphaned toolUse blocks before returning
1069
- const fixedMessages = fixOrphanedToolUse(combinedMessages);
1070
- return {
1071
- modelId: prompt?.modelId || conversation?.modelId,
1072
- messages: fixedMessages.length > 0 ? fixedMessages : [],
1073
- system: combinedSystem && combinedSystem.length > 0 ? combinedSystem : undefined,
1074
- };
1075
- }
1076
- /**
1077
- * Fix orphaned toolUse blocks in the conversation.
1078
- *
1079
- * When an agent is stopped mid-tool-execution, the assistant message contains toolUse blocks
1080
- * but no corresponding toolResult was added. The AWS Converse API requires that every toolUse
1081
- * must be followed by a toolResult in the next user message.
1082
- *
1083
- * This function detects such cases and injects synthetic toolResult blocks indicating
1084
- * the tools were interrupted, allowing the conversation to continue.
1085
- */
1086
- function fixOrphanedToolUse(messages) {
1087
- if (messages.length < 2)
1088
- return messages;
1089
- const result = [];
1090
- for (let i = 0; i < messages.length; i++) {
1091
- const current = messages[i];
1092
- result.push(current);
1093
- // Check if this is an assistant message with toolUse blocks
1094
- if (current.role === 'assistant' && current.content) {
1095
- // Extract toolUse blocks using simple property check (same pattern as existing Bedrock code)
1096
- const toolUseBlocks = [];
1097
- for (const block of current.content) {
1098
- if (block.toolUse?.toolUseId) {
1099
- toolUseBlocks.push({
1100
- toolUseId: block.toolUse.toolUseId,
1101
- name: block.toolUse.name ?? 'unknown'
1102
- });
1103
- }
1104
- }
1105
- if (toolUseBlocks.length > 0) {
1106
- // Check if the next message is a user message with matching toolResults
1107
- const nextMessage = messages[i + 1];
1108
- if (nextMessage && nextMessage.role === 'user' && nextMessage.content) {
1109
- // Get toolResult IDs from the next message using simple property check
1110
- const toolResultIds = new Set();
1111
- for (const block of nextMessage.content) {
1112
- if (block.toolResult?.toolUseId) {
1113
- toolResultIds.add(block.toolResult.toolUseId);
1114
- }
1115
- }
1116
- // Find orphaned toolUse blocks (no matching toolResult)
1117
- const orphanedToolUse = toolUseBlocks.filter(tu => !toolResultIds.has(tu.toolUseId));
1118
- if (orphanedToolUse.length > 0) {
1119
- // Inject synthetic toolResults for orphaned toolUse
1120
- const syntheticResults = orphanedToolUse.map(tu => ({
1121
- toolResult: {
1122
- toolUseId: tu.toolUseId,
1123
- content: [{
1124
- text: `[Tool interrupted: The user stopped the operation before "${tu.name}" could execute.]`
1125
- }]
1126
- }
1127
- }));
1128
- // Prepend synthetic results to the next user message
1129
- const updatedNextMessage = {
1130
- ...nextMessage,
1131
- content: [...syntheticResults, ...nextMessage.content]
1132
- };
1133
- // Replace the next message in our iteration
1134
- messages[i + 1] = updatedNextMessage;
1135
- }
1136
- }
1137
- else if (nextMessage && nextMessage.role === 'user' && !nextMessage.content) {
1138
- // Next message is a user message but has no content
1139
- // We need to add toolResults
1140
- const syntheticResults = toolUseBlocks.map(tu => ({
1141
- toolResult: {
1142
- toolUseId: tu.toolUseId,
1143
- content: [{
1144
- text: `[Tool interrupted: The user stopped the operation before "${tu.name}" could execute.]`
1145
- }]
1146
- }
1147
- }));
1148
- const updatedNextMessage = {
1149
- role: 'user',
1150
- content: syntheticResults
1151
- };
1152
- messages[i + 1] = updatedNextMessage;
1153
- }
1154
- // Note: If there's no nextMessage, we leave the conversation as-is.
1155
- // The toolUse blocks are expected to be there - the next turn will provide toolResults.
1156
- }
1157
- }
1158
- }
1159
- return result;
1160
- }
1161
- function formatAmazonModalities(modalities) {
1162
- const standardizedModalities = [];
1163
- for (const modality of modalities) {
1164
- if (modality === client_bedrock_1.ModelModality.TEXT) {
1165
- standardizedModalities.push("text");
1166
- }
1167
- else if (modality === client_bedrock_1.ModelModality.IMAGE) {
1168
- standardizedModalities.push("image");
1169
- }
1170
- else if (modality === client_bedrock_1.ModelModality.EMBEDDING) {
1171
- standardizedModalities.push("embedding");
1172
- }
1173
- else if (modality == "SPEECH") {
1174
- standardizedModalities.push("audio");
1175
- }
1176
- else if (modality == "VIDEO") {
1177
- standardizedModalities.push("video");
1178
- }
1179
- else {
1180
- // Handle other modalities as needed
1181
- standardizedModalities.push(modality.toString().toLowerCase());
1182
- }
1183
- }
1184
- return standardizedModalities;
1185
- }
1186
- //# sourceMappingURL=index.js.map