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