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