| 1 | import { |
| 2 | BedrockRuntimeClient, |
| 3 | ContentBlock, |
| 4 | ContentBlockDelta, |
| 5 | ContentBlockStart, |
| 6 | ContentBlockStartEvent, |
| 7 | ConversationRole, |
| 8 | ConverseStreamCommand, |
| 9 | ConverseStreamCommandOutput, |
| 10 | ImageFormat, |
| 11 | InvokeModelCommand, |
| 12 | Message, |
| 13 | ReasoningContentBlockDelta, |
| 14 | ToolConfiguration, |
| 15 | ToolUseBlock, |
| 16 | ToolUseBlockDelta, |
| 17 | } from "@aws-sdk/client-bedrock-runtime"; |
| 18 | import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; |
| 19 | |
| 20 | import type { CompletionOptions } from "../../index.js"; |
| 21 | import { ChatMessage, Chunk, LLMOptions, MessageContent } from "../../index.js"; |
| 22 | import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; |
| 23 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 24 | import { BaseLLM } from "../index.js"; |
| 25 | import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js"; |
| 26 | import { getSecureID } from "../utils/getSecureID.js"; |
| 27 | import { withLLMRetry } from "../utils/retry.js"; |
| 28 | |
| 29 | interface ModelConfig { |
| 30 | formatPayload: (text: string) => any; |
| 31 | extractEmbeddings: (responseBody: any) => number[][]; |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Interface for prompt caching metrics |
| 36 | */ |
| 37 | interface PromptCachingMetrics { |
| 38 | cacheReadInputTokens: number; |
| 39 | cacheWriteInputTokens: number; |
| 40 | } |
| 41 | |
| 42 | class Bedrock extends BaseLLM { |
| 43 | static providerName = "bedrock"; |
| 44 | static defaultOptions: Partial<LLMOptions> = { |
| 45 | region: "us-east-1", |
| 46 | model: "anthropic.claude-3-sonnet-20240229-v1:0", |
| 47 | profile: "bedrock", |
| 48 | }; |
| 49 | |
| 50 | private _promptCachingMetrics: PromptCachingMetrics = { |
| 51 | cacheReadInputTokens: 0, |
| 52 | cacheWriteInputTokens: 0, |
| 53 | }; |
| 54 | |
| 55 | public requestOptions: { |
| 56 | region?: string; |
| 57 | credentials?: any; |
| 58 | headers?: Record<string, string>; |
| 59 | }; |
| 60 | |
| 61 | constructor(options: LLMOptions) { |
| 62 | super(options); |
| 63 | if (!options.apiBase) { |
| 64 | this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; |
| 65 | } |
| 66 | |
| 67 | this.requestOptions = { |
| 68 | region: options.region, |
| 69 | headers: {}, |
| 70 | }; |
| 71 | } |
| 72 | |
| 73 | protected async *_streamComplete( |
| 74 | prompt: string, |
| 75 | signal: AbortSignal, |
| 76 | options: CompletionOptions, |
| 77 | ): AsyncGenerator<string> { |
| 78 | const messages = [{ role: "user" as const, content: prompt }]; |
| 79 | for await (const update of this._streamChat(messages, signal, options)) { |
| 80 | yield renderChatMessage(update); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | @withLLMRetry() |
| 85 | protected async *_streamChat( |
| 86 | messages: ChatMessage[], |
| 87 | signal: AbortSignal, |
| 88 | options: CompletionOptions, |
| 89 | ): AsyncGenerator<ChatMessage> { |
| 90 | const credentials = await this._getCredentials(); |
| 91 | const client = new BedrockRuntimeClient({ |
| 92 | region: this.region, |
| 93 | endpoint: this.apiBase, |
| 94 | credentials: { |
| 95 | accessKeyId: credentials.accessKeyId, |
| 96 | secretAccessKey: credentials.secretAccessKey, |
| 97 | sessionToken: credentials.sessionToken || "", |
| 98 | }, |
| 99 | }); |
| 100 | |
| 101 | let config_headers = |
| 102 | this.requestOptions && this.requestOptions.headers |
| 103 | ? this.requestOptions.headers |
| 104 | : {}; |
| 105 | // AWS SigV4 requires strict canonicalization of headers. |
| 106 | // DO NOT USE "_" in your header name. It will return an error like below. |
| 107 | // "The request signature we calculated does not match the signature you provided." |
| 108 | |
| 109 | client.middlewareStack.add( |
| 110 | (next) => async (args: any) => { |
| 111 | args.request.headers = { |
| 112 | ...args.request.headers, |
| 113 | ...config_headers, |
| 114 | }; |
| 115 | return next(args); |
| 116 | }, |
| 117 | { |
| 118 | step: "build", |
| 119 | }, |
| 120 | ); |
| 121 | |
| 122 | const input = this._generateConverseInput(messages, { |
| 123 | ...options, |
| 124 | stream: true, |
| 125 | }); |
| 126 | const command = new ConverseStreamCommand(input); |
| 127 | |
| 128 | const response = (await client.send(command, { |
| 129 | abortSignal: signal, |
| 130 | })) as ConverseStreamCommandOutput; |
| 131 | |
| 132 | if (!response?.stream) { |
| 133 | throw new Error("No stream received from Bedrock API"); |
| 134 | } |
| 135 | |
| 136 | // Reset cache metrics for new request |
| 137 | this._promptCachingMetrics = { |
| 138 | cacheReadInputTokens: 0, |
| 139 | cacheWriteInputTokens: 0, |
| 140 | }; |
| 141 | |
| 142 | try { |
| 143 | for await (const chunk of response.stream) { |
| 144 | if (chunk.metadata?.usage) { |
| 145 | console.log(`${JSON.stringify(chunk.metadata.usage)}`); |
| 146 | } |
| 147 | |
| 148 | const contentBlockDelta: ContentBlockDelta | undefined = |
| 149 | chunk.contentBlockDelta?.delta; |
| 150 | if (contentBlockDelta) { |
| 151 | // Handle text content |
| 152 | if (contentBlockDelta.text) { |
| 153 | yield { |
| 154 | role: "assistant", |
| 155 | content: contentBlockDelta.text, |
| 156 | }; |
| 157 | continue; |
| 158 | } |
| 159 | if (contentBlockDelta.reasoningContent?.text) { |
| 160 | yield { |
| 161 | role: "thinking", |
| 162 | content: contentBlockDelta.reasoningContent.text, |
| 163 | }; |
| 164 | continue; |
| 165 | } |
| 166 | if (contentBlockDelta.reasoningContent?.signature) { |
| 167 | yield { |
| 168 | role: "thinking", |
| 169 | content: "", |
| 170 | signature: contentBlockDelta.reasoningContent.signature, |
| 171 | }; |
| 172 | continue; |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | const reasoningDelta: ReasoningContentBlockDelta | undefined = chunk |
| 177 | .contentBlockDelta?.delta as ReasoningContentBlockDelta; |
| 178 | if (reasoningDelta) { |
| 179 | if (reasoningDelta.redactedContent) { |
| 180 | yield { |
| 181 | role: "thinking", |
| 182 | content: "", |
| 183 | redactedThinking: reasoningDelta.text, |
| 184 | }; |
| 185 | continue; |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | const toolUseBlockDelta: ToolUseBlockDelta | undefined = chunk |
| 190 | .contentBlockDelta?.delta?.toolUse as ToolUseBlockDelta; |
| 191 | const toolUseBlock: ToolUseBlock | undefined = chunk.contentBlockDelta |
| 192 | ?.delta?.toolUse as ToolUseBlock; |
| 193 | if (toolUseBlockDelta && toolUseBlock) { |
| 194 | yield { |
| 195 | role: "assistant", |
| 196 | content: "", |
| 197 | toolCalls: [ |
| 198 | { |
| 199 | id: toolUseBlock.toolUseId, |
| 200 | type: "function", |
| 201 | function: { |
| 202 | name: toolUseBlock.name, |
| 203 | arguments: toolUseBlockDelta.input, |
| 204 | }, |
| 205 | }, |
| 206 | ], |
| 207 | }; |
| 208 | continue; |
| 209 | } |
| 210 | |
| 211 | const contentBlockStart: ContentBlockStartEvent | undefined = |
| 212 | chunk.contentBlockStart as ContentBlockStartEvent; |
| 213 | if (contentBlockStart) { |
| 214 | const start: ContentBlockStart | undefined = chunk.contentBlockStart |
| 215 | ?.start as ContentBlockStart; |
| 216 | if (start) { |
| 217 | const toolUseBlock: ToolUseBlock | undefined = |
| 218 | start.toolUse as ToolUseBlock; |
| 219 | if (toolUseBlock?.toolUseId && toolUseBlock?.name) { |
| 220 | yield { |
| 221 | role: "assistant", |
| 222 | content: "", |
| 223 | toolCalls: [ |
| 224 | { |
| 225 | id: toolUseBlock.toolUseId, |
| 226 | type: "function", |
| 227 | function: { |
| 228 | name: toolUseBlock.name, |
| 229 | arguments: "", |
| 230 | }, |
| 231 | }, |
| 232 | ], |
| 233 | }; |
| 234 | continue; |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | } catch (error: unknown) { |
| 240 | // Clean up state and let the original error bubble up to the retry decorator |
| 241 | throw error; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Generates the input payload for the Bedrock Converse API |
| 247 | * @param messages - Array of chat messages |
| 248 | * @param options - Completion options |
| 249 | * @returns Formatted input payload for the API |
| 250 | */ |
| 251 | private _generateConverseInput( |
| 252 | messages: ChatMessage[], |
| 253 | options: CompletionOptions, |
| 254 | ): any { |
| 255 | const systemMessage = stripImages( |
| 256 | messages.find((m) => m.role === "system")?.content ?? "", |
| 257 | ); |
| 258 | |
| 259 | // Prompt and system message caching settings |
| 260 | const shouldCacheSystemMessage = |
| 261 | (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) || |
| 262 | this.completionOptions.promptCaching; |
| 263 | const enablePromptCaching = |
| 264 | shouldCacheSystemMessage || |
| 265 | this.cacheBehavior?.cacheConversation || |
| 266 | this.completionOptions.promptCaching; |
| 267 | |
| 268 | if (enablePromptCaching) { |
| 269 | this.requestOptions.headers = { |
| 270 | ...this.requestOptions.headers, |
| 271 | "x-amzn-bedrock-enablepromptcaching": "true", |
| 272 | }; |
| 273 | } |
| 274 | |
| 275 | // First get tools |
| 276 | const supportsTools = |
| 277 | (this.capabilities?.tools || |
| 278 | PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? |
| 279 | false; |
| 280 | |
| 281 | let toolConfig: undefined | ToolConfiguration = undefined; |
| 282 | const availableTools = new Set<string>(); |
| 283 | if (supportsTools && options.tools && options.tools.length > 0) { |
| 284 | toolConfig = { |
| 285 | tools: options.tools.map((tool) => ({ |
| 286 | toolSpec: { |
| 287 | name: tool.function.name, |
| 288 | description: tool.function.description, |
| 289 | inputSchema: { |
| 290 | json: tool.function.parameters, |
| 291 | }, |
| 292 | }, |
| 293 | })), |
| 294 | } as ToolConfiguration; |
| 295 | const shouldCacheToolsConfig = this.completionOptions.promptCaching; |
| 296 | if (shouldCacheToolsConfig) { |
| 297 | toolConfig.tools!.push({ cachePoint: { type: "default" } }); |
| 298 | } |
| 299 | options.tools.forEach((tool) => { |
| 300 | availableTools.add(tool.function.name); |
| 301 | }); |
| 302 | } |
| 303 | |
| 304 | const convertedMessages = this._convertMessages(messages, availableTools); |
| 305 | |
| 306 | return { |
| 307 | modelId: options.model, |
| 308 | system: systemMessage |
| 309 | ? shouldCacheSystemMessage |
| 310 | ? [{ text: systemMessage }, { cachePoint: { type: "default" } }] |
| 311 | : [{ text: systemMessage }] |
| 312 | : undefined, |
| 313 | toolConfig: toolConfig, |
| 314 | messages: convertedMessages, |
| 315 | inferenceConfig: { |
| 316 | maxTokens: options.maxTokens, |
| 317 | temperature: options.temperature, |
| 318 | topP: options.topP, |
| 319 | // TODO: The current approach selects the first 4 items from the list to comply with Bedrock's requirement |
| 320 | // of having at most 4 stop sequences, as per the AWS documentation: |
| 321 | // https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_InferenceConfiguration.html |
| 322 | // However, it might be better to implement a strategy that dynamically selects the most appropriate stop sequences |
| 323 | // based on the context. |
| 324 | // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. |
| 325 | // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), |
| 326 | // providing meaningful error messages to improve the user experience. |
| 327 | stopSequences: options.stop |
| 328 | ?.filter((stop) => stop.trim() !== "") |
| 329 | .slice(0, 4), |
| 330 | }, |
| 331 | additionalModelRequestFields: { |
| 332 | thinking: options.reasoning |
| 333 | ? { |
| 334 | type: "enabled", |
| 335 | budget_tokens: options.reasoningBudgetTokens, |
| 336 | } |
| 337 | : undefined, |
| 338 | anthropic_beta: options.model.includes("claude") |
| 339 | ? ["fine-grained-tool-streaming-2025-05-14"] |
| 340 | : undefined, |
| 341 | }, |
| 342 | }; |
| 343 | } |
| 344 | |
| 345 | /* |
| 346 | Converts the messages to the format expected by the Bedrock API. |
| 347 | |
| 348 | */ |
| 349 | private _convertMessages( |
| 350 | messages: ChatMessage[], |
| 351 | availableTools: Set<string>, |
| 352 | ): Message[] { |
| 353 | let currentRole: "user" | "assistant" = "user"; |
| 354 | let currentBlocks: ContentBlock[] = []; |
| 355 | |
| 356 | const converted: Message[] = []; |
| 357 | const pushCurrentMessage = () => { |
| 358 | if (currentBlocks.length === 0 && converted.length > 1) { |
| 359 | throw new Error( |
| 360 | `Bedrock: no content in ${currentRole} message before conversational turn change`, |
| 361 | ); |
| 362 | } |
| 363 | if (currentBlocks.length > 0) { |
| 364 | converted.push({ |
| 365 | role: currentRole, |
| 366 | content: currentBlocks, |
| 367 | }); |
| 368 | } |
| 369 | currentBlocks = []; |
| 370 | }; |
| 371 | |
| 372 | const nonSystemMessages = messages.filter((m) => m.role !== "system"); |
| 373 | const hasAddedToolCallIds = new Set<string>(); |
| 374 | |
| 375 | for (let idx = 0; idx < nonSystemMessages.length; idx++) { |
| 376 | const message = nonSystemMessages[idx]; |
| 377 | |
| 378 | if (message.role === "user" || message.role === "tool") { |
| 379 | // Detect conversational turn change |
| 380 | if (currentRole !== ConversationRole.USER) { |
| 381 | pushCurrentMessage(); |
| 382 | currentRole = ConversationRole.USER; |
| 383 | } |
| 384 | |
| 385 | // USER messages: |
| 386 | // Non-empty user message content is converted to "text" and "image" blocks |
| 387 | // If ANY user message part is cached, we add a single cache point block when we push the message |
| 388 | if (message.role === "user") { |
| 389 | const trimmedContent = |
| 390 | typeof message.content === "string" |
| 391 | ? message.content.trim() |
| 392 | : message.content; |
| 393 | if (trimmedContent) { |
| 394 | currentBlocks.push( |
| 395 | ...this._convertMessageContentToBlocks(trimmedContent), |
| 396 | ); |
| 397 | } |
| 398 | } |
| 399 | // TOOL messages: |
| 400 | // Tool messages are represented by "toolResult" blocks |
| 401 | // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig) |
| 402 | // If it doesn't, we convert it to a text block |
| 403 | else if (message.role === "tool") { |
| 404 | const trimmedContent = message.content.trim() || "No tool output"; |
| 405 | if (hasAddedToolCallIds.has(message.toolCallId)) { |
| 406 | currentBlocks.push({ |
| 407 | toolResult: { |
| 408 | toolUseId: message.toolCallId, |
| 409 | content: [ |
| 410 | { |
| 411 | text: trimmedContent, |
| 412 | }, |
| 413 | ], |
| 414 | }, |
| 415 | }); |
| 416 | } else { |
| 417 | currentBlocks.push({ |
| 418 | text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`, |
| 419 | }); |
| 420 | } |
| 421 | } |
| 422 | } else if (message.role === "assistant" || message.role === "thinking") { |
| 423 | // Detect conversational turn change |
| 424 | if (currentRole !== ConversationRole.ASSISTANT) { |
| 425 | pushCurrentMessage(); |
| 426 | currentRole = ConversationRole.ASSISTANT; |
| 427 | } |
| 428 | |
| 429 | // ASSISTANT messages: |
| 430 | // Non-empty assistant message content is converted to "text" and "image" blocks |
| 431 | if (message.role === "assistant") { |
| 432 | const trimmedContent = |
| 433 | typeof message.content === "string" |
| 434 | ? message.content.trim() |
| 435 | : message.content; |
| 436 | if (trimmedContent) { |
| 437 | currentBlocks.push( |
| 438 | ...this._convertMessageContentToBlocks(trimmedContent), |
| 439 | ); |
| 440 | } |
| 441 | // TOOL CALLS: |
| 442 | // Tool calls are represented by "toolUse" blocks |
| 443 | // Each tool call must have an id and a function name |
| 444 | // The function name must match one of the available tools |
| 445 | // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools) |
| 446 | if (message.toolCalls) { |
| 447 | for (const toolCall of message.toolCalls) { |
| 448 | if (toolCall.id && toolCall.function?.name) { |
| 449 | if (availableTools.has(toolCall.function.name)) { |
| 450 | currentBlocks.push({ |
| 451 | toolUse: { |
| 452 | toolUseId: toolCall.id, |
| 453 | name: toolCall.function.name, |
| 454 | input: safeParseToolCallArgs(toolCall), |
| 455 | }, |
| 456 | }); |
| 457 | hasAddedToolCallIds.add(toolCall.id); |
| 458 | } else { |
| 459 | const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`; |
| 460 | currentBlocks.push({ |
| 461 | text: toolCallText, |
| 462 | }); |
| 463 | } |
| 464 | } else { |
| 465 | console.warn( |
| 466 | `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`, |
| 467 | ); |
| 468 | continue; |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | } else if (message.role === "thinking") { |
| 473 | // THINKING: |
| 474 | // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content |
| 475 | if (message.redactedThinking) { |
| 476 | const block: ContentBlock.ReasoningContentMember = { |
| 477 | reasoningContent: { |
| 478 | redactedContent: new Uint8Array( |
| 479 | Buffer.from(message.redactedThinking), |
| 480 | ), |
| 481 | }, |
| 482 | }; |
| 483 | currentBlocks.push(block); |
| 484 | } else { |
| 485 | const block: ContentBlock.ReasoningContentMember = { |
| 486 | reasoningContent: { |
| 487 | reasoningText: { |
| 488 | text: (message.content as string) || "", |
| 489 | signature: message.signature, |
| 490 | }, |
| 491 | }, |
| 492 | }; |
| 493 | currentBlocks.push(block); |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | if (currentBlocks.length > 0) { |
| 499 | pushCurrentMessage(); |
| 500 | } |
| 501 | |
| 502 | // If caching is enabled, we add cache_control parameter to the last two user messages |
| 503 | // The second-to-last because it retrieves potentially already cached contents, |
| 504 | // The last one because we want it cached for later retrieval. |
| 505 | // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html |
| 506 | if ( |
| 507 | this.cacheBehavior?.cacheConversation || |
| 508 | this.completionOptions.promptCaching |
| 509 | ) { |
| 510 | this._addCachingToLastTwoUserMessages(converted); |
| 511 | } |
| 512 | |
| 513 | return converted; |
| 514 | } |
| 515 | |
| 516 | private _addCachingToLastTwoUserMessages(converted: Message[]) { |
| 517 | let numCached = 0; |
| 518 | for (let i = converted.length - 1; i >= 0; i--) { |
| 519 | const message = converted[i]; |
| 520 | if (message.role === "user") { |
| 521 | message.content?.forEach((block) => { |
| 522 | if (block.text) { |
| 523 | block.text += getSecureID(); |
| 524 | } |
| 525 | }); |
| 526 | message.content?.push({ cachePoint: { type: "default" } }); |
| 527 | numCached++; |
| 528 | } |
| 529 | if (numCached === 2) { |
| 530 | break; |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | // Converts Continue message content (string/parts) to Bedrock ContentBlock format. |
| 536 | // Unsupported/problematic image formats are skipped with a warning. |
| 537 | private _convertMessageContentToBlocks( |
| 538 | content: MessageContent, |
| 539 | ): ContentBlock[] { |
| 540 | const blocks: ContentBlock[] = []; |
| 541 | if (typeof content === "string") { |
| 542 | blocks.push({ text: content }); |
| 543 | } else { |
| 544 | for (const part of content) { |
| 545 | if (part.type === "text") { |
| 546 | blocks.push({ text: part.text }); |
| 547 | } else if (part.type === "imageUrl" && part.imageUrl) { |
| 548 | try { |
| 549 | const [mimeType, base64Data] = part.imageUrl.url.split(","); |
| 550 | const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; |
| 551 | if ( |
| 552 | format === ImageFormat.JPEG || |
| 553 | format === ImageFormat.PNG || |
| 554 | format === ImageFormat.WEBP || |
| 555 | format === ImageFormat.GIF |
| 556 | ) { |
| 557 | blocks.push({ |
| 558 | image: { |
| 559 | format, |
| 560 | source: { |
| 561 | bytes: Uint8Array.from(Buffer.from(base64Data, "base64")), |
| 562 | }, |
| 563 | }, |
| 564 | }); |
| 565 | } else { |
| 566 | console.warn( |
| 567 | `Bedrock: skipping unsupported image part format: ${format}`, |
| 568 | part, |
| 569 | ); |
| 570 | } |
| 571 | } catch (error) { |
| 572 | console.warn("Bedrock: failed to process image part", error, part); |
| 573 | } |
| 574 | } |
| 575 | } |
| 576 | } |
| 577 | return blocks; |
| 578 | } |
| 579 | |
| 580 | private async _getCredentials() { |
| 581 | if (this.accessKeyId && this.secretAccessKey) { |
| 582 | return { |
| 583 | accessKeyId: this.accessKeyId, |
| 584 | secretAccessKey: this.secretAccessKey, |
| 585 | }; |
| 586 | } |
| 587 | const profile = this.profile ?? "bedrock"; |
| 588 | try { |
| 589 | return await fromNodeProviderChain({ |
| 590 | profile: profile, |
| 591 | ignoreCache: true, |
| 592 | })(); |
| 593 | } catch (e) { |
| 594 | console.warn( |
| 595 | `AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`, |
| 596 | ); |
| 597 | } |
| 598 | return await fromNodeProviderChain()(); |
| 599 | } |
| 600 | |
| 601 | // EMBED // |
| 602 | async _embed(chunks: string[]): Promise<number[][]> { |
| 603 | const credentials = await this._getCredentials(); |
| 604 | const client = new BedrockRuntimeClient({ |
| 605 | region: this.region, |
| 606 | credentials: { |
| 607 | accessKeyId: credentials.accessKeyId, |
| 608 | secretAccessKey: credentials.secretAccessKey, |
| 609 | sessionToken: credentials.sessionToken || "", |
| 610 | }, |
| 611 | }); |
| 612 | |
| 613 | return ( |
| 614 | await Promise.all( |
| 615 | chunks.map(async (chunk) => { |
| 616 | const input = this._generateInvokeModelCommandInput(chunk); |
| 617 | const command = new InvokeModelCommand(input); |
| 618 | const response = await client.send(command); |
| 619 | if (response.body) { |
| 620 | const decoder = new TextDecoder(); |
| 621 | const decoded = decoder.decode(response.body); |
| 622 | try { |
| 623 | const responseBody = JSON.parse(decoded); |
| 624 | return this._extractEmbeddings(responseBody); |
| 625 | } catch (e) { |
| 626 | console.error(`Error parsing response body from:\n${decoded}`, e); |
| 627 | } |
| 628 | } |
| 629 | return []; |
| 630 | }), |
| 631 | ) |
| 632 | ).flat(); |
| 633 | } |
| 634 | |
| 635 | private _generateInvokeModelCommandInput(text: string): any { |
| 636 | const modelConfig = this._getModelConfig(); |
| 637 | const payload = modelConfig.formatPayload(text); |
| 638 | |
| 639 | return { |
| 640 | body: JSON.stringify(payload), |
| 641 | modelId: this.model, |
| 642 | accept: "*/*", |
| 643 | contentType: "application/json", |
| 644 | }; |
| 645 | } |
| 646 | |
| 647 | private _extractEmbeddings(responseBody: any): number[][] { |
| 648 | const modelConfig = this._getModelConfig(); |
| 649 | return modelConfig.extractEmbeddings(responseBody); |
| 650 | } |
| 651 | |
| 652 | private _getModelConfig() { |
| 653 | const modelConfigs: { [key: string]: ModelConfig } = { |
| 654 | cohere: { |
| 655 | formatPayload: (text: string) => ({ |
| 656 | texts: [text], |
| 657 | input_type: "search_document", |
| 658 | truncate: "END", |
| 659 | }), |
| 660 | extractEmbeddings: (responseBody: any) => responseBody.embeddings || [], |
| 661 | }, |
| 662 | "amazon.titan-embed": { |
| 663 | formatPayload: (text: string) => ({ |
| 664 | inputText: text, |
| 665 | }), |
| 666 | extractEmbeddings: (responseBody: any) => |
| 667 | responseBody.embedding ? [responseBody.embedding] : [], |
| 668 | }, |
| 669 | }; |
| 670 | |
| 671 | const modelPrefix = Object.keys(modelConfigs).find((prefix) => |
| 672 | this.model!.startsWith(prefix), |
| 673 | ); |
| 674 | if (!modelPrefix) { |
| 675 | throw new Error(`Unsupported model: ${this.model}`); |
| 676 | } |
| 677 | return modelConfigs[modelPrefix]; |
| 678 | } |
| 679 | |
| 680 | async rerank(query: string, chunks: Chunk[]): Promise<number[]> { |
| 681 | if (!query || !chunks.length) { |
| 682 | throw new Error("Query and chunks must not be empty"); |
| 683 | } |
| 684 | |
| 685 | try { |
| 686 | const credentials = await this._getCredentials(); |
| 687 | const client = new BedrockRuntimeClient({ |
| 688 | region: this.region, |
| 689 | credentials: { |
| 690 | accessKeyId: credentials.accessKeyId, |
| 691 | secretAccessKey: credentials.secretAccessKey, |
| 692 | sessionToken: credentials.sessionToken || "", |
| 693 | }, |
| 694 | }); |
| 695 | |
| 696 | // Base payload for both models |
| 697 | const payload: any = { |
| 698 | query: query, |
| 699 | documents: chunks.map((chunk) => chunk.content), |
| 700 | top_n: chunks.length, |
| 701 | }; |
| 702 | |
| 703 | // Add api_version for Cohere model |
| 704 | if (this.model.startsWith("cohere.rerank")) { |
| 705 | payload.api_version = 2; |
| 706 | } |
| 707 | |
| 708 | const input = { |
| 709 | body: JSON.stringify(payload), |
| 710 | modelId: this.model, |
| 711 | accept: "*/*", |
| 712 | contentType: "application/json", |
| 713 | }; |
| 714 | |
| 715 | const command = new InvokeModelCommand(input); |
| 716 | const response = await client.send(command); |
| 717 | |
| 718 | if (!response.body) { |
| 719 | throw new Error("Empty response received from Bedrock"); |
| 720 | } |
| 721 | |
| 722 | const decoder = new TextDecoder(); |
| 723 | const decoded = decoder.decode(response.body); |
| 724 | try { |
| 725 | const responseBody = JSON.parse(decoded); |
| 726 | // Sort results by index to maintain original order |
| 727 | return responseBody.results |
| 728 | .sort((a: any, b: any) => a.index - b.index) |
| 729 | .map((result: any) => result.relevance_score); |
| 730 | } catch (e) { |
| 731 | throw new Error( |
| 732 | `Error parsing JSON from Bedrock response body:\n${decoded}, ${JSON.stringify(e)}`, |
| 733 | ); |
| 734 | } |
| 735 | } catch (error: unknown) { |
| 736 | if (error instanceof Error) { |
| 737 | if ("code" in error) { |
| 738 | // AWS SDK specific errors |
| 739 | throw new Error( |
| 740 | `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`, |
| 741 | ); |
| 742 | } |
| 743 | throw new Error(`Error in BedrockReranker.rerank: ${error.message}`); |
| 744 | } |
| 745 | throw new Error( |
| 746 | "Error in BedrockReranker.rerank: Unknown error occurred", |
| 747 | ); |
| 748 | } |
| 749 | } |
| 750 | } |
| 751 | |
| 752 | export default Bedrock; |