Skip to content

fix(amazon-bedrock): trimIfLast must not be applied to reasoning blocks with a signature #13583

@wonjun3991

Description

@wonjun3991

Bug Report

Summary

In packages/amazon-bedrock/src/convert-to-bedrock-chat-messages.ts, trimIfLast() is applied to reasoning block text even when a cryptographic signature is present. This corrupts the text/signature pair, causing Bedrock to reject the request.

Error

ValidationException: The model returned the following errors:
messages.N.content.M: `thinking` or `redacted_thinking` blocks in the latest assistant message 
cannot be modified. These blocks must remain as they were in the original response.

Root Cause

// packages/amazon-bedrock/src/convert-to-bedrock-chat-messages.ts (line ~298)
case 'reasoning': {
  if (reasoningMetadata.signature != null) {
    bedrockContent.push({
      reasoningContent: {
        reasoningText: {
          text: trimIfLast(        // ← BUG: trims text even when signature is present
            isLastBlock,
            isLastMessage,
            isLastContentPart,
            part.text,
          ),
          signature: reasoningMetadata.signature,  // signature is for ORIGINAL (untrimmed) text
        },
      },
    });
  }
}

The trimIfLast() function trims trailing whitespace from the reasoning text when it's the last content part of the last message. However, the signature was computed by Anthropic over the exact original bytes of the reasoning text. Trimming even a single trailing newline invalidates the signature, causing Bedrock to reject with "cannot be modified".

Fix

// Never trim reasoning text when a signature is present — the signature validates exact bytes
text: reasoningMetadata.signature != null
  ? part.text
  : trimIfLast(isLastBlock, isLastMessage, isLastContentPart, part.text),
signature: reasoningMetadata.signature,

Why trimIfLast Exists

The trimming was added to handle Bedrock's restriction on trailing whitespace in pre-filled assistant responses. However, this restriction does not apply to reasoning blocks in conversation history — they must be returned verbatim with their original signature.

Affected Versions

  • @ai-sdk/amazon-bedrock: 3.0.82 (current at time of filing)
  • Reproducible with Claude Opus 4 on Amazon Bedrock with extended thinking (reasoning: { type: 'enabled' })

Related

Metadata

Metadata

Assignees

Labels

ai/providerrelated to a provider package. Must be assigned together with at least one `provider/*` labelbugSomething isn't working as documentedprovider/amazon-bedrockIssues related to the @ai-sdk/amazon-bedrock providerreproduction provided

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions