fix(bedrock): Fall back to default inference for Bedrock provider models without document block support (#12932)

This commit is contained in:
Dan Wuensch
2026-10-28 04:10:19 +00:00
committed by GitHub
parent 58732e22ed
commit ee8500d5e0
2 changed files with 132 additions and 33 deletions
+67 -4
View File
@@ -1,4 +1,6 @@
use std::collections::HashMap;
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use super::base::{
model_info_for_provider_model, ConfigKey, MessageStream, ModelInfo, Provider, ProviderDef,
@@ -190,6 +192,8 @@ pub struct BedrockProvider {
http_client: reqwest::Client,
#[serde(skip)]
mantle_base_url: Option<String>,
#[serde(skip)]
documents_unsupported: AtomicBool,
}
/// Request inputs shared by the `Converse` and `ConverseStream` APIs.
@@ -309,6 +313,7 @@ impl BedrockProvider {
))
.build()?,
mantle_base_url: None,
documents_unsupported: AtomicBool::new(false),
})
}
@@ -447,8 +452,12 @@ impl BedrockProvider {
let mut bedrock_messages: Vec<bedrock::Message> = Vec::new();
for message in visible_messages {
let formatted =
to_bedrock_message_with_caching(message, false, Some(&model.model_name))?;
let formatted = to_bedrock_message_with_caching(
message,
false,
Some(&model.model_name),
self.documents_supported(),
)?;
if formatted.content().is_empty() {
continue;
}
@@ -487,6 +496,26 @@ impl BedrockProvider {
})
}
fn documents_supported(&self) -> bool {
!self.documents_unsupported.load(Ordering::Relaxed)
}
async fn send_with_document_fallback<T, Fut>(
&self,
request: impl Fn() -> Fut,
) -> Result<T, ProviderError>
where
Fut: Future<Output = Result<T, ProviderError>>,
{
match request().await {
Err(err) if is_documents_unsupported_error(&err) => {
self.documents_unsupported.store(true, Ordering::Relaxed);
request().await
}
result => result,
}
}
async fn converse(
&self,
model: &ModelConfig,
@@ -638,7 +667,11 @@ impl BedrockProvider {
model_name: &str,
) -> Result<MessageStream, ProviderError> {
let (bedrock_message, bedrock_usage) = self
.with_retry(|| self.converse(model, session_id, system, messages, tools))
.with_retry(|| {
self.send_with_document_fallback(|| {
self.converse(model, session_id, system, messages, tools)
})
})
.await?;
let usage = bedrock_usage
@@ -1023,7 +1056,9 @@ impl Provider for BedrockProvider {
// the Anthropic provider's behaviour).
let response = self
.with_retry(|| {
self.converse_stream(model_config, session_id_opt, system, messages, tools)
self.send_with_document_fallback(|| {
self.converse_stream(model_config, session_id_opt, system, messages, tools)
})
})
.await?;
@@ -1139,6 +1174,13 @@ impl Provider for BedrockProvider {
}
}
fn is_documents_unsupported_error(err: &ProviderError) -> bool {
matches!(
err,
ProviderError::ExecutionError(details) if details.contains("doesn't support documents")
)
}
fn map_converse_stream_error(err: ConverseStreamError) -> ProviderError {
match err {
ConverseStreamError::ThrottlingException(throttle_err) => {
@@ -1184,6 +1226,7 @@ mod tests {
(
BedrockProvider {
documents_unsupported: AtomicBool::new(false),
client,
retry_config: RetryConfig::default(),
name: "aws_bedrock".to_string(),
@@ -1207,6 +1250,23 @@ mod tests {
)
}
#[test]
fn documents_unsupported_error_is_detected() {
let err = ProviderError::ExecutionError(
"Bedrock validation error: ValidationException { message: Some(\"This model doesn't support documents.\") }"
.to_string(),
);
assert!(is_documents_unsupported_error(&err));
assert!(!is_documents_unsupported_error(&ProviderError::ExecutionError(
"Bedrock validation error: ValidationException { message: Some(\"Input is too long.\") }"
.to_string(),
)));
assert!(!is_documents_unsupported_error(
&ProviderError::ServerError("doesn't support documents".to_string(),)
));
}
#[test]
fn stream_validation_error_is_not_retried() {
let err = ConverseStreamError::ValidationException(
@@ -1451,6 +1511,7 @@ mod tests {
let model = ModelConfig::new("openai.gpt-5.5");
let provider = BedrockProvider {
documents_unsupported: AtomicBool::new(false),
client: Client::new(&sdk_config),
retry_config: RetryConfig::default(),
name: "aws_bedrock".to_string(),
@@ -1515,6 +1576,7 @@ mod tests {
let model = ModelConfig::new("openai.gpt-5.6-terra");
let provider = BedrockProvider {
documents_unsupported: AtomicBool::new(false),
client: Client::new(&sdk_config),
retry_config: RetryConfig::default(),
name: "aws_bedrock".to_string(),
@@ -2047,6 +2109,7 @@ mod tests {
let model = ModelConfig::new("google.gemma-4-31b");
let provider = BedrockProvider {
documents_unsupported: AtomicBool::new(false),
client: Client::new(&sdk_config),
retry_config: RetryConfig::default(),
name: "aws_bedrock".to_string(),
+65 -29
View File
@@ -166,6 +166,7 @@ pub fn to_bedrock_message_with_caching(
message: &Message,
enable_caching: bool,
current_model: Option<&str>,
documents_supported: bool,
) -> Result<bedrock::Message> {
let thinking_is_stale = thinking_block_is_stale(message, current_model);
let mut content_blocks: Vec<bedrock::ContentBlock> = message
@@ -187,7 +188,7 @@ pub fn to_bedrock_message_with_caching(
_ => true,
}
})
.map(to_bedrock_message_content)
.map(|content| to_bedrock_message_content(content, documents_supported))
.collect::<Result<_>>()?;
if enable_caching && !content_blocks.is_empty() {
@@ -206,7 +207,10 @@ pub fn to_bedrock_message_with_caching(
.map_err(|err| anyhow!("Failed to construct Bedrock message: {}", err))
}
pub fn to_bedrock_message_content(content: &MessageContent) -> Result<bedrock::ContentBlock> {
pub fn to_bedrock_message_content(
content: &MessageContent,
documents_supported: bool,
) -> Result<bedrock::ContentBlock> {
Ok(match content {
MessageContent::Text(text) => bedrock::ContentBlock::Text(text.text.to_string()),
MessageContent::ToolConfirmationRequest(_) => {
@@ -273,7 +277,13 @@ pub fn to_bedrock_message_content(content: &MessageContent) -> Result<bedrock::C
result
.content
.iter()
.map(|c| to_bedrock_tool_result_content_block(&tool_res.id, c.clone()))
.map(|c| {
to_bedrock_tool_result_content_block(
&tool_res.id,
c.clone(),
documents_supported,
)
})
.collect::<Result<_>>()?,
),
Err(error) => {
@@ -305,6 +315,7 @@ pub fn to_bedrock_message_content(content: &MessageContent) -> Result<bedrock::C
pub fn to_bedrock_tool_result_content_block(
tool_use_id: &str,
content: ContentBlock,
documents_supported: bool,
) -> Result<bedrock::ToolResultContentBlock> {
Ok(match content {
ContentBlock::Text(text) => bedrock::ToolResultContentBlock::Text(text.text),
@@ -315,7 +326,7 @@ pub fn to_bedrock_tool_result_content_block(
bedrock::ToolResultContentBlock::Text("[Resource link]".to_string())
}
ContentBlock::Resource(resource) => match &resource.resource {
ResourceContents::TextResourceContents { text, .. } => {
ResourceContents::TextResourceContents { text, .. } if documents_supported => {
match to_bedrock_document(tool_use_id, &resource.resource)? {
Some(doc) => bedrock::ToolResultContentBlock::Document(doc),
None => {
@@ -323,6 +334,9 @@ pub fn to_bedrock_tool_result_content_block(
}
}
}
ResourceContents::TextResourceContents { text, .. } => {
bedrock::ToolResultContentBlock::Text(sanitize_unicode_tags(text.as_str()))
}
ResourceContents::BlobResourceContents { .. } => {
bail!("Blob resource content is not supported by Bedrock provider yet")
}
@@ -931,7 +945,7 @@ mod tests {
let image = ImageContent::new(TEST_IMAGE_B64.to_string(), "image/png".to_string());
let message_content = MessageContent::Image(image);
let result = to_bedrock_message_content(&message_content)?;
let result = to_bedrock_message_content(&message_content, true)?;
// Verify we get an Image content block
assert!(matches!(result, bedrock::ContentBlock::Image(_)));
@@ -997,7 +1011,7 @@ mod tests {
#[test]
fn test_to_bedrock_tool_result_content_block_image() -> Result<()> {
let content = ContentBlock::image(TEST_IMAGE_B64.to_string(), "image/png".to_string());
let result = to_bedrock_tool_result_content_block("test_id", content)?;
let result = to_bedrock_tool_result_content_block("test_id", content, true)?;
// Verify the wrapper correctly converts ContentBlock::Image to ToolResultContentBlock::Image
assert!(matches!(result, bedrock::ToolResultContentBlock::Image(_)));
@@ -1008,7 +1022,21 @@ mod tests {
#[test]
fn test_to_bedrock_tool_result_sanitizes_text_resource_fallback() -> Result<()> {
let content = ContentBlock::embedded_text("file:///result.bin", "visible\u{E0041}text");
let result = to_bedrock_tool_result_content_block("test_id", content)?;
let result = to_bedrock_tool_result_content_block("test_id", content, true)?;
let bedrock::ToolResultContentBlock::Text(text) = result else {
panic!("expected text fallback");
};
assert_eq!(text, "visibletext");
Ok(())
}
#[test]
fn test_to_bedrock_tool_result_demotes_document_resource_when_unsupported() -> Result<()> {
let content =
ContentBlock::embedded_text("file:///repro/sample.md", "visible\u{E0041}text");
let result = to_bedrock_tool_result_content_block("test_id", content, false)?;
let bedrock::ToolResultContentBlock::Text(text) = result else {
panic!("expected text fallback");
@@ -1021,7 +1049,7 @@ mod tests {
#[test]
fn test_to_bedrock_tool_result_sanitizes_document_resource() -> Result<()> {
let content = ContentBlock::embedded_text("file:///result.txt", "visible\u{E0041}text");
let result = to_bedrock_tool_result_content_block("test_id", content)?;
let result = to_bedrock_tool_result_content_block("test_id", content, true)?;
let bedrock::ToolResultContentBlock::Document(document) = result else {
panic!("expected document");
@@ -1048,7 +1076,7 @@ mod tests {
MessageContent::text("Second text"),
],
);
let bedrock_message = to_bedrock_message_with_caching(&message, true, None)?;
let bedrock_message = to_bedrock_message_with_caching(&message, true, None, true)?;
assert_eq!(bedrock_message.content.len(), 3);
if let bedrock::ContentBlock::Text(text) = &bedrock_message.content[0] {
assert_eq!(text, "First text");
@@ -1066,7 +1094,7 @@ mod tests {
));
// Caching disabled: no cache point added
let no_cache = to_bedrock_message_with_caching(&message, false, None)?;
let no_cache = to_bedrock_message_with_caching(&message, false, None, true)?;
assert_eq!(no_cache.content.len(), 2);
for block in &no_cache.content {
assert!(!matches!(block, bedrock::ContentBlock::CachePoint(_)));
@@ -1074,7 +1102,7 @@ mod tests {
// Empty content: no cache point added even with caching enabled
let empty = Message::new(Role::User, Utc::now().timestamp(), vec![]);
let empty_msg = to_bedrock_message_with_caching(&empty, true, None)?;
let empty_msg = to_bedrock_message_with_caching(&empty, true, None, true)?;
assert_eq!(empty_msg.content.len(), 0);
Ok(())
@@ -1097,8 +1125,12 @@ mod tests {
#[test]
fn keeps_signed_thinking_from_the_same_model() -> Result<()> {
let message = signed_thinking_from_model("anthropic.claude-sonnet-4");
let formatted =
to_bedrock_message_with_caching(&message, false, Some("anthropic.claude-sonnet-4"))?;
let formatted = to_bedrock_message_with_caching(
&message,
false,
Some("anthropic.claude-sonnet-4"),
true,
)?;
assert!(matches!(
formatted.content[0],
@@ -1114,8 +1146,12 @@ mod tests {
#[test]
fn drops_signed_thinking_from_a_different_model() -> Result<()> {
let message = signed_thinking_from_model("anthropic.claude-opus-4");
let formatted =
to_bedrock_message_with_caching(&message, false, Some("anthropic.claude-sonnet-4"))?;
let formatted = to_bedrock_message_with_caching(
&message,
false,
Some("anthropic.claude-sonnet-4"),
true,
)?;
assert_eq!(formatted.content.len(), 1);
assert!(matches!(
@@ -1243,7 +1279,7 @@ mod tests {
#[test]
fn test_to_bedrock_message_content_thinking() -> Result<()> {
let message_content = MessageContent::thinking("because of X", "sig-abc");
let block = to_bedrock_message_content(&message_content)?;
let block = to_bedrock_message_content(&message_content, true)?;
match block {
bedrock::ContentBlock::ReasoningContent(
@@ -1263,7 +1299,7 @@ mod tests {
#[test]
fn test_to_bedrock_message_content_thinking_without_signature() -> Result<()> {
let message_content = MessageContent::thinking("silent reasoning", "");
let block = to_bedrock_message_content(&message_content)?;
let block = to_bedrock_message_content(&message_content, true)?;
match block {
bedrock::ContentBlock::ReasoningContent(
@@ -1286,7 +1322,7 @@ mod tests {
let encoded = base64::prelude::BASE64_STANDARD.encode(raw);
let message_content = MessageContent::redacted_thinking(encoded);
let block = to_bedrock_message_content(&message_content)?;
let block = to_bedrock_message_content(&message_content, true)?;
match block {
bedrock::ContentBlock::ReasoningContent(
bedrock::ReasoningContentBlock::RedactedContent(blob),
@@ -1305,7 +1341,7 @@ mod tests {
fn test_to_bedrock_message_content_redacted_thinking_opaque_payload() -> Result<()> {
let message_content = MessageContent::redacted_thinking("opaque_not_base64!@#".to_string());
let block = to_bedrock_message_content(&message_content)?;
let block = to_bedrock_message_content(&message_content, true)?;
match block {
bedrock::ContentBlock::Text(text) => assert_eq!(text, ""),
other => panic!(
@@ -1327,7 +1363,7 @@ mod tests {
));
let message_content = from_bedrock_content_block(&original)?;
let round_tripped = to_bedrock_message_content(&message_content)?;
let round_tripped = to_bedrock_message_content(&message_content, true)?;
match round_tripped {
bedrock::ContentBlock::ReasoningContent(
@@ -1354,7 +1390,7 @@ mod tests {
);
let message_content = from_bedrock_content_block(&original)?;
let round_tripped = to_bedrock_message_content(&message_content)?;
let round_tripped = to_bedrock_message_content(&message_content, true)?;
match round_tripped {
bedrock::ContentBlock::ReasoningContent(
@@ -1466,7 +1502,7 @@ mod tests {
],
);
let bedrock_message = to_bedrock_message_with_caching(&message, true, None)?;
let bedrock_message = to_bedrock_message_with_caching(&message, true, None, true)?;
// Verify cache point is added after all content blocks (text + tool request + cache point)
assert_eq!(bedrock_message.content.len(), 3);
@@ -1498,7 +1534,7 @@ mod tests {
None,
);
let content = MessageContent::tool_request("call_bad".to_string(), Err(err));
match to_bedrock_message_content(&content)? {
match to_bedrock_message_content(&content, true)? {
bedrock::ContentBlock::ToolUse(tu) => {
assert_eq!(tu.tool_use_id, "call_bad");
assert_eq!(tu.name, "unparseable_tool_call");
@@ -1517,7 +1553,7 @@ mod tests {
);
let content = MessageContent::tool_response("call_hidden".to_string(), Err(error));
let bedrock::ContentBlock::ToolResult(result) = to_bedrock_message_content(&content)?
let bedrock::ContentBlock::ToolResult(result) = to_bedrock_message_content(&content, true)?
else {
panic!("expected ToolResult");
};
@@ -1539,7 +1575,7 @@ mod tests {
);
let content = MessageContent::tool_response("call_error".to_string(), Err(error));
let bedrock::ContentBlock::ToolResult(result) = to_bedrock_message_content(&content)?
let bedrock::ContentBlock::ToolResult(result) = to_bedrock_message_content(&content, true)?
else {
panic!("expected ToolResult");
};
@@ -1567,7 +1603,7 @@ mod tests {
)],
);
let bedrock_message = to_bedrock_message_with_caching(&message, true, None)?;
let bedrock_message = to_bedrock_message_with_caching(&message, true, None, true)?;
// Verify cache point is added after tool response content
assert_eq!(bedrock_message.content.len(), 2);
@@ -1607,7 +1643,7 @@ mod tests {
],
);
let bedrock_message = to_bedrock_message_with_caching(&message, true, None)?;
let bedrock_message = to_bedrock_message_with_caching(&message, true, None, true)?;
// Verify cache point is added at the end after all tool requests
assert_eq!(bedrock_message.content.len(), 4);
@@ -1712,9 +1748,9 @@ mod tests {
);
let request_result =
to_bedrock_message_with_caching(&elicitation_request, false, None).unwrap();
to_bedrock_message_with_caching(&elicitation_request, false, None, true).unwrap();
let response_result =
to_bedrock_message_with_caching(&elicitation_response, false, None).unwrap();
to_bedrock_message_with_caching(&elicitation_response, false, None, true).unwrap();
assert!(request_result.content().is_empty());
assert!(response_result.content().is_empty());