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