Changesets · Branches · Tags · Compare
| Changeset | 693d0df2720692ca634a1cbeed2d54af29d3e7daf945c0d7769493b7cabbe3e4 |
|---|---|
| Author | Dallin Romney <dallinromney@gmail.com> · 2025-07-01 17:31 -07:00 |
| Committer | Dallin Romney <dallinromney@gmail.com> · 2025-07-01 17:31 -07:00 |
| Parents | 3c39a014374a |
1 file changed
modified core/llm/llms/Bedrock.ts +182 −149
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | BedrockRuntimeClient, |
| 3 | 3 | ContentBlock, |
| 4 | + ConversationRole, | |
| 4 | 5 | ConverseStreamCommand, |
| 5 | 6 | ConverseStreamCommandOutput, |
| 7 | + ImageFormat, | |
| 6 | 8 | InvokeModelCommand, |
| 7 | 9 | Message, |
| 8 | 10 | ToolConfiguration, |
| @@ -14,6 +16,7 @@ | ||
| 14 | 16 | Chunk, |
| 15 | 17 | CompletionOptions, |
| 16 | 18 | LLMOptions, |
| 19 | + MessageContent, | |
| 17 | 20 | } from "../../index.js"; |
| 18 | 21 | import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; |
| 19 | 22 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| @@ -289,8 +292,8 @@ | ||
| 289 | 292 | const systemMessage = stripImages( |
| 290 | 293 | messages.find((m) => m.role === "system")?.content ?? "", |
| 291 | 294 | ); |
| 292 | - const convertedMessages = this._convertMessages(messages); | |
| 293 | 295 | |
| 296 | + // Prompt and system message caching settings | |
| 294 | 297 | const shouldCacheSystemMessage = |
| 295 | 298 | (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) || |
| 296 | 299 | this.completionOptions.promptCaching; |
| @@ -298,9 +301,7 @@ | ||
| 298 | 301 | shouldCacheSystemMessage || |
| 299 | 302 | this.cacheBehavior?.cacheConversation || |
| 300 | 303 | this.completionOptions.promptCaching; |
| 301 | - const shouldCacheToolsConfig = this.completionOptions.promptCaching; | |
| 302 | 304 | |
| 303 | - // Add header for prompt caching | |
| 304 | 305 | if (enablePromptCaching) { |
| 305 | 306 | this.requestOptions.headers = { |
| 306 | 307 | ...this.requestOptions.headers, |
| @@ -308,30 +309,37 @@ | ||
| 308 | 309 | }; |
| 309 | 310 | } |
| 310 | 311 | |
| 312 | + // First get tools | |
| 311 | 313 | const supportsTools = |
| 312 | 314 | (this.capabilities?.tools || |
| 313 | 315 | PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? |
| 314 | 316 | false; |
| 315 | 317 | |
| 316 | - let toolConfig = | |
| 317 | - supportsTools && options.tools | |
| 318 | - ? ({ | |
| 319 | - tools: options.tools.map((tool) => ({ | |
| 320 | - toolSpec: { | |
| 321 | - name: tool.function.name, | |
| 322 | - description: tool.function.description, | |
| 323 | - inputSchema: { | |
| 324 | - json: tool.function.parameters, | |
| 325 | - }, | |
| 326 | - }, | |
| 327 | - })), | |
| 328 | - } as ToolConfiguration) | |
| 329 | - : undefined; | |
| 330 | - | |
| 331 | - if (toolConfig?.tools && shouldCacheToolsConfig) { | |
| 332 | - toolConfig.tools.push({ cachePoint: { type: "default" } }); | |
| 318 | + let toolConfig: undefined | ToolConfiguration = undefined; | |
| 319 | + const availableTools = new Set<string>(); | |
| 320 | + if (supportsTools && options.tools && options.tools.length > 0) { | |
| 321 | + toolConfig = { | |
| 322 | + tools: options.tools.map((tool) => ({ | |
| 323 | + toolSpec: { | |
| 324 | + name: tool.function.name, | |
| 325 | + description: tool.function.description, | |
| 326 | + inputSchema: { | |
| 327 | + json: tool.function.parameters, | |
| 328 | + }, | |
| 329 | + }, | |
| 330 | + })), | |
| 331 | + } as ToolConfiguration; | |
| 332 | + const shouldCacheToolsConfig = this.completionOptions.promptCaching; | |
| 333 | + if (shouldCacheToolsConfig) { | |
| 334 | + toolConfig.tools!.push({ cachePoint: { type: "default" } }); | |
| 335 | + } | |
| 336 | + options.tools.forEach((tool) => { | |
| 337 | + availableTools.add(tool.function.name); | |
| 338 | + }); | |
| 333 | 339 | } |
| 334 | 340 | |
| 341 | + const convertedMessages = this._convertMessages(messages, availableTools); | |
| 342 | + | |
| 335 | 343 | return { |
| 336 | 344 | modelId: options.model, |
| 337 | 345 | system: systemMessage |
| @@ -368,25 +376,75 @@ | ||
| 368 | 376 | }; |
| 369 | 377 | } |
| 370 | 378 | |
| 371 | - private _convertMessage( | |
| 372 | - message: ChatMessage, | |
| 373 | - addCaching: boolean = false, | |
| 374 | - ): Message | null { | |
| 375 | - // Handle system messages explicitly | |
| 376 | - if (message.role === "system") { | |
| 377 | - return null; | |
| 379 | + private _convertMessages( | |
| 380 | + messages: ChatMessage[], | |
| 381 | + availableTools: Set<string>, | |
| 382 | + ): Message[] { | |
| 383 | + const nonSystemMessages = messages.filter((m) => m.role !== "system"); | |
| 384 | + | |
| 385 | + const lastTwoUserMsgIndices: number[] = []; | |
| 386 | + for (let i = nonSystemMessages.length - 1; i >= 0; i--) { | |
| 387 | + if (nonSystemMessages[i].role === "user") { | |
| 388 | + lastTwoUserMsgIndices.push(i); | |
| 389 | + if (lastTwoUserMsgIndices.length === 2) { | |
| 390 | + break; | |
| 391 | + } | |
| 392 | + } | |
| 378 | 393 | } |
| 379 | 394 | |
| 380 | - const cachePoint = addCaching | |
| 381 | - ? { cachePoint: { type: "default" } } | |
| 382 | - : undefined; | |
| 383 | - | |
| 384 | - // Tool response handling | |
| 385 | - if (message.role === "tool") { | |
| 386 | - return { | |
| 387 | - role: "user", | |
| 388 | - content: [ | |
| 389 | - { | |
| 395 | + let currentRole: "user" | "assistant" = "user"; | |
| 396 | + let currentBlocks: ContentBlock[] = []; | |
| 397 | + let addCachePoint = false; | |
| 398 | + | |
| 399 | + const converted: Message[] = []; | |
| 400 | + const pushCurrentMessage = () => { | |
| 401 | + if (currentBlocks.length === 0 && converted.length > 1) { | |
| 402 | + throw new Error( | |
| 403 | + `Bedrock: no content in ${currentRole} message before conversational turn change`, | |
| 404 | + ); | |
| 405 | + } | |
| 406 | + if (currentBlocks.length > 0) { | |
| 407 | + if (addCachePoint) { | |
| 408 | + currentBlocks.push({ cachePoint: { type: "default" } }); | |
| 409 | + } | |
| 410 | + converted.push({ | |
| 411 | + role: currentRole, | |
| 412 | + content: currentBlocks, | |
| 413 | + }); | |
| 414 | + } | |
| 415 | + // Change roles and reset | |
| 416 | + currentBlocks = []; | |
| 417 | + addCachePoint = false; | |
| 418 | + }; | |
| 419 | + | |
| 420 | + for (let idx = 0; idx < nonSystemMessages.length; idx++) { | |
| 421 | + const message = nonSystemMessages[idx]; | |
| 422 | + if (message.role === "user" || message.role === "tool") { | |
| 423 | + pushCurrentMessage(); | |
| 424 | + currentRole = ConversationRole.USER; | |
| 425 | + | |
| 426 | + if (message.role === "user") { | |
| 427 | + if (message.content) { | |
| 428 | + // Add cache_control parameter to the last two user messages | |
| 429 | + // The second-to-last because it retrieves potentially already cached contents, | |
| 430 | + // The last one because we want it cached for later retrieval. | |
| 431 | + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html | |
| 432 | + const messageIsCached = !!( | |
| 433 | + this.cacheBehavior?.cacheConversation && | |
| 434 | + lastTwoUserMsgIndices.includes(idx) | |
| 435 | + ); | |
| 436 | + if (messageIsCached) { | |
| 437 | + addCachePoint = true; | |
| 438 | + } | |
| 439 | + currentBlocks.push( | |
| 440 | + ...this._convertMessageContentToBlocks( | |
| 441 | + message.content, | |
| 442 | + messageIsCached, | |
| 443 | + ), | |
| 444 | + ); | |
| 445 | + } | |
| 446 | + } else if (message.role === "tool") { | |
| 447 | + currentBlocks.push({ | |
| 390 | 448 | toolResult: { |
| 391 | 449 | toolUseId: message.toolCallId, |
| 392 | 450 | content: [ |
| @@ -395,140 +453,115 @@ | ||
| 395 | 453 | }, |
| 396 | 454 | ], |
| 397 | 455 | }, |
| 398 | - }, | |
| 399 | - ], | |
| 400 | - }; | |
| 401 | - } | |
| 402 | - | |
| 403 | - // Tool calls handling | |
| 404 | - if (message.role === "assistant" && message.toolCalls) { | |
| 405 | - return { | |
| 406 | - role: "assistant", | |
| 407 | - content: message.toolCalls.map((toolCall) => ({ | |
| 408 | - toolUse: { | |
| 409 | - toolUseId: toolCall.id, | |
| 410 | - name: toolCall.function?.name, | |
| 411 | - input: safeParseToolCallArgs(toolCall), | |
| 412 | - }, | |
| 413 | - })), | |
| 414 | - }; | |
| 415 | - } | |
| 416 | - | |
| 417 | - if (message.role === "thinking") { | |
| 418 | - if (message.redactedThinking) { | |
| 419 | - const content: ContentBlock.ReasoningContentMember = { | |
| 420 | - reasoningContent: { | |
| 421 | - redactedContent: new Uint8Array( | |
| 422 | - Buffer.from(message.redactedThinking), | |
| 423 | - ), | |
| 424 | - }, | |
| 425 | - }; | |
| 426 | - return { | |
| 427 | - role: "assistant", | |
| 428 | - content: [content], | |
| 429 | - }; | |
| 456 | + }); | |
| 457 | + } | |
| 430 | 458 | } else { |
| 431 | - const content: ContentBlock.ReasoningContentMember = { | |
| 432 | - reasoningContent: { | |
| 433 | - reasoningText: { | |
| 434 | - text: (message.content as string) || "", | |
| 435 | - signature: message.signature, | |
| 436 | - }, | |
| 437 | - }, | |
| 438 | - }; | |
| 439 | - return { | |
| 440 | - role: "assistant", | |
| 441 | - content: [content], | |
| 442 | - }; | |
| 459 | + pushCurrentMessage(); | |
| 460 | + currentRole = ConversationRole.ASSISTANT; | |
| 461 | + | |
| 462 | + if (message.role === "assistant") { | |
| 463 | + if (message.content) { | |
| 464 | + currentBlocks.push( | |
| 465 | + ...this._convertMessageContentToBlocks(message.content, false), | |
| 466 | + ); | |
| 467 | + } | |
| 468 | + if (message.toolCalls) { | |
| 469 | + for (const toolCall of message.toolCalls) { | |
| 470 | + if (availableTools.has(toolCall.function?.name || "")) { | |
| 471 | + currentBlocks.push({ | |
| 472 | + toolUse: { | |
| 473 | + toolUseId: toolCall.id, | |
| 474 | + name: toolCall.function?.name, | |
| 475 | + input: safeParseToolCallArgs(toolCall), | |
| 476 | + }, | |
| 477 | + }); | |
| 478 | + } else { | |
| 479 | + console.warn( | |
| 480 | + `Tool ${toolCall.function?.name} is not available for this model.`, | |
| 481 | + ); | |
| 482 | + } | |
| 483 | + } | |
| 484 | + } | |
| 485 | + } else if (message.role === "thinking") { | |
| 486 | + if (message.redactedThinking) { | |
| 487 | + const block: ContentBlock.ReasoningContentMember = { | |
| 488 | + reasoningContent: { | |
| 489 | + redactedContent: new Uint8Array( | |
| 490 | + Buffer.from(message.redactedThinking), | |
| 491 | + ), | |
| 492 | + }, | |
| 493 | + }; | |
| 494 | + currentBlocks.push(block); | |
| 495 | + } else { | |
| 496 | + const block: ContentBlock.ReasoningContentMember = { | |
| 497 | + reasoningContent: { | |
| 498 | + reasoningText: { | |
| 499 | + text: (message.content as string) || "", | |
| 500 | + signature: message.signature, | |
| 501 | + }, | |
| 502 | + }, | |
| 503 | + }; | |
| 504 | + currentBlocks.push(block); | |
| 505 | + } | |
| 506 | + } | |
| 443 | 507 | } |
| 444 | 508 | } |
| 445 | 509 | |
| 446 | - // Standard text message | |
| 447 | - if (typeof message.content === "string") { | |
| 510 | + return converted; | |
| 511 | + } | |
| 512 | + | |
| 513 | + private _convertMessageContentToBlocks( | |
| 514 | + content: MessageContent, | |
| 515 | + addCaching: boolean, | |
| 516 | + ): ContentBlock[] { | |
| 517 | + const blocks: ContentBlock[] = []; | |
| 518 | + if (typeof content === "string") { | |
| 519 | + let contentText = content; | |
| 448 | 520 | if (addCaching) { |
| 449 | - message.content += getSecureID(); | |
| 521 | + contentText += getSecureID(); | |
| 450 | 522 | } |
| 451 | - const content: any[] = [{ text: message.content }]; | |
| 523 | + blocks.push({ text: contentText }); | |
| 452 | 524 | if (addCaching) { |
| 453 | - content.push({ cachePoint: { type: "default" } }); | |
| 525 | + blocks.push({ cachePoint: { type: "default" } }); | |
| 454 | 526 | } |
| 455 | - return { | |
| 456 | - role: message.role, | |
| 457 | - content, | |
| 458 | - }; | |
| 459 | - } | |
| 460 | - | |
| 461 | - // Improved multimodal content handling | |
| 462 | - if (Array.isArray(message.content)) { | |
| 463 | - const content: any[] = []; | |
| 464 | - | |
| 465 | - // Process all parts first | |
| 466 | - message.content.forEach((part) => { | |
| 527 | + } else { | |
| 528 | + for (const part of content) { | |
| 467 | 529 | if (part.type === "text") { |
| 468 | 530 | if (addCaching) { |
| 469 | 531 | part.text += getSecureID(); |
| 470 | 532 | } |
| 471 | - content.push({ text: part.text }); | |
| 533 | + blocks.push({ text: part.text }); | |
| 472 | 534 | } else if (part.type === "imageUrl" && part.imageUrl) { |
| 473 | 535 | try { |
| 474 | 536 | const [mimeType, base64Data] = part.imageUrl.url.split(","); |
| 475 | 537 | const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; |
| 476 | - content.push({ | |
| 477 | - image: { | |
| 478 | - format, | |
| 479 | - source: { | |
| 480 | - bytes: Buffer.from(base64Data, "base64"), | |
| 538 | + if ( | |
| 539 | + format === ImageFormat.JPEG || | |
| 540 | + format === ImageFormat.PNG || | |
| 541 | + format === ImageFormat.WEBP || | |
| 542 | + format === ImageFormat.GIF | |
| 543 | + ) { | |
| 544 | + blocks.push({ | |
| 545 | + image: { | |
| 546 | + format, | |
| 547 | + source: { | |
| 548 | + bytes: Uint8Array.from(Buffer.from(base64Data, "base64")), | |
| 549 | + }, | |
| 481 | 550 | }, |
| 482 | - }, | |
| 483 | - }); | |
| 551 | + }); | |
| 552 | + } else { | |
| 553 | + console.warn( | |
| 554 | + `Bedrock: skipping unsupported image part format: ${format}`, | |
| 555 | + part, | |
| 556 | + ); | |
| 557 | + } | |
| 484 | 558 | } catch (error) { |
| 485 | - console.warn(`Failed to process image: ${error}`); | |
| 559 | + console.warn("Bedrock: failed to process image part", error, part); | |
| 486 | 560 | } |
| 487 | 561 | } |
| 488 | - }); | |
| 489 | - | |
| 490 | - // Add cache point as a separate block at the end if needed | |
| 491 | - if (addCaching && content.length > 0) { | |
| 492 | - content.push({ cachePoint: { type: "default" } }); | |
| 493 | 562 | } |
| 494 | - | |
| 495 | - return { | |
| 496 | - role: message.role, | |
| 497 | - content, | |
| 498 | - } as Message; | |
| 499 | 563 | } |
| 500 | - return null; | |
| 501 | - } | |
| 502 | - | |
| 503 | - private _convertMessages(messages: ChatMessage[]): any[] { | |
| 504 | - const filteredmessages = messages.filter( | |
| 505 | - (m) => m.role !== "system" && !!m.content, | |
| 506 | - ); | |
| 507 | - const lastTwoUserMsgIndices = filteredmessages | |
| 508 | - .map((msg, index) => (msg.role === "user" ? index : -1)) | |
| 509 | - .filter((index) => index !== -1) | |
| 510 | - .slice(-2); | |
| 511 | - | |
| 512 | - const converted = filteredmessages | |
| 513 | - .map((message, filteredMsgIdx) => { | |
| 514 | - // Add cache_control parameter to the last two user messages | |
| 515 | - // The second-to-last because it retrieves potentially already cached contents, | |
| 516 | - // The last one because we want it cached for later retrieval. | |
| 517 | - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html | |
| 518 | - const addCaching = | |
| 519 | - this.cacheBehavior?.cacheConversation && | |
| 520 | - lastTwoUserMsgIndices.includes(filteredMsgIdx); | |
| 521 | - | |
| 522 | - try { | |
| 523 | - return this._convertMessage(message, addCaching); | |
| 524 | - } catch (error) { | |
| 525 | - console.error(`Failed to convert message: ${error}`); | |
| 526 | - return null; | |
| 527 | - } | |
| 528 | - }) | |
| 529 | - .filter(Boolean); | |
| 530 | - | |
| 531 | - return converted; | |
| 564 | + return blocks; | |
| 532 | 565 | } |
| 533 | 566 | |
| 534 | 567 | private async _getCredentials() { |