1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use aws_sdk_bedrockruntime::types as aws_bedrock;
use base64::{Engine, prelude::BASE64_STANDARD};
use rig_core::error::ProviderError;
use rig_core::message::{AssistantContent, Issuer, Text, ToolName};
use super::{
converse_output::{ContentBlock, ReasoningContentBlock, StopReason, TokenUsage},
json::AwsDocument,
};
use rig_core::completion;
/// Rig's input is Bedrock's `inputTokens` plus its cache reads and writes,
/// and its total input plus output, which is `totalTokens`. Shared by the
/// unary response path and the streaming terminal record.
pub(crate) fn normalize_usage(usage: &TokenUsage) -> completion::Usage {
let cache_read = usage.cache_read_input_tokens.map(|n| n as u64);
let cache_write = usage.cache_write_input_tokens.map(|n| n as u64);
let input = usage.input_tokens as u64 + cache_read.unwrap_or(0) + cache_write.unwrap_or(0);
let output = usage.output_tokens as u64;
completion::Usage {
input_tokens: Some(input),
output_tokens: Some(output),
total_tokens: Some(input + output),
cached_input_tokens: cache_read,
cache_creation_input_tokens: cache_write,
tool_use_prompt_tokens: None,
reasoning_tokens: None,
}
}
/// Stable descriptor name reported on normalized Bedrock responses.
pub const PROVIDER_NAME: &str = "aws_bedrock";
/// The issuer Bedrock's reasoning records for `model`. Anthropic documents
/// Claude thinking signatures as valid across the Claude API, Bedrock and
/// Vertex AI, so Claude reasoning records `anthropic`; other models' reasoning
/// records [`PROVIDER_NAME`]. An inference-profile ARN that does not name the
/// model counts as another model.
pub fn reasoning_issuer(model: &str) -> &'static str {
if model.contains("anthropic.claude") {
"anthropic"
} else {
PROVIDER_NAME
}
}
/// Normalizes stop reasons, preserving unknown values in `Other`.
/// Stop sequences map to `Stop`; guardrail intervention maps to `ContentFilter`.
pub fn map_stop_reason(stop_reason: &StopReason) -> completion::FinishReason {
match stop_reason {
StopReason::EndTurn | StopReason::StopSequence => completion::FinishReason::Stop,
StopReason::MaxTokens => completion::FinishReason::Length,
StopReason::ToolUse => completion::FinishReason::ToolCalls,
StopReason::ContentFiltered | StopReason::GuardrailIntervened => {
completion::FinishReason::ContentFilter
}
StopReason::Unknown(value) => completion::FinishReason::Other(value.to_string()),
}
}
pub struct RigAssistantContent(pub AssistantContent);
impl TryFrom<ContentBlock> for RigAssistantContent {
type Error = ProviderError;
fn try_from(value: ContentBlock) -> Result<Self, Self::Error> {
match value {
ContentBlock::Text(text) => {
Ok(RigAssistantContent(AssistantContent::Text(Text::new(text))))
}
ContentBlock::ToolUse(call) => Ok(RigAssistantContent(
completion::AssistantContent::tool_call(
&call.tool_use_id,
ToolName::new(call.name).map_err(|error| {
ProviderError::Response(format!(
"AWS Bedrock returned a tool call: {error}"
))
})?,
call.input,
),
)),
ContentBlock::ReasoningContent(reasoning_block) => match reasoning_block {
ReasoningContentBlock::ReasoningText(reasoning_text) => {
Ok(RigAssistantContent(AssistantContent::Reasoning(
// The issuer depends on the model, which the Converse
// output does not name: the completion fold seals it.
rig_core::message::Reasoning::new_with_signature(
&reasoning_text.text,
reasoning_text.signature,
)
.sealed(PROVIDER_NAME),
)))
}
// Base64 preserves opaque redacted bytes for request replay.
ReasoningContentBlock::RedactedContent(blob) => {
Ok(RigAssistantContent(AssistantContent::Reasoning(
rig_core::message::Reasoning::redacted(BASE64_STANDARD.encode(blob.inner))
.sealed(PROVIDER_NAME),
)))
}
_ => Err(ProviderError::Provider(
"AWS Bedrock returned unsupported ReasoningContentBlock variant".into(),
)),
},
_ => Err(ProviderError::Provider(
"AWS Bedrock returned unsupported ContentBlock".into(),
)),
}
}
}
impl RigAssistantContent {
/// Converts assistant content for a Converse request.
/// Returns `Ok(None)` after dropping unsupported ciphertext or invalid base64
/// with a warning. Rejects images and unrepresentable signed reasoning.
pub(crate) fn into_content_block(
self,
issuer: &Issuer,
) -> Result<Option<aws_bedrock::ContentBlock>, ProviderError> {
match self.0 {
AssistantContent::Text(text) => Ok(Some(aws_bedrock::ContentBlock::Text(text.text))),
AssistantContent::ToolCall(tool_call) => {
// Calls and results must use the same provider-issued identity,
// not a potentially different local assembly handle.
let tool_use_id = tool_call.id.wire().into_owned();
let doc: AwsDocument = tool_call.function.arguments.into();
Ok(Some(aws_bedrock::ContentBlock::ToolUse(
aws_bedrock::ToolUseBlock::builder()
.tool_use_id(tool_use_id)
.name(tool_call.function.name)
.input(doc.0)
.build()
.map_err(|e| ProviderError::Provider(e.to_string()))?,
)))
}
AssistantContent::Reasoning(reasoning) => {
// Reasoning another service issued is not replayed.
let Some(reasoning) = reasoning.open(issuer) else {
return Ok(None);
};
let mut reasoning = reasoning.clone();
// Only Redacted payloads represent base64-encoded Converse bytes.
// Drop Encrypted payloads rather than reinterpret foreign ciphertext.
let foreign = reasoning
.content
.iter()
.filter(|content| {
matches!(content, rig_core::message::ReasoningContent::Encrypted(_))
})
.count();
if foreign > 0 {
tracing::warn!(
dropped = foreign,
"dropping foreign encrypted reasoning payload(s); Bedrock cannot \
verify another provider's ciphertext"
);
reasoning.content.retain(|content| {
!matches!(content, rig_core::message::ReasoningContent::Encrypted(_))
});
if reasoning.content.is_empty() {
return Ok(None);
}
}
let redacted: Vec<&str> = reasoning
.content
.iter()
.filter_map(|content| match content {
rig_core::message::ReasoningContent::Redacted { data } => {
Some(data.as_str())
}
_ => None,
})
.collect();
if !redacted.is_empty() {
if redacted.len() != reasoning.content.len() {
// Converse cannot mix redacted bytes and text in one
// block; retain only the representable text.
tracing::warn!(
dropped = redacted.len(),
"dropping redacted reasoning payloads Bedrock cannot carry \
alongside reasoning text; replaying the text only"
);
reasoning.content.retain(|content| {
!matches!(
content,
rig_core::message::ReasoningContent::Redacted { .. }
)
});
} else {
if redacted.len() > 1 {
tracing::warn!(
dropped = redacted.len() - 1,
"dropping extra redacted reasoning payloads; Bedrock carries \
one redactedContent blob per block"
);
}
// Invalid base64 cannot reconstruct wire bytes; omit it
// rather than fail the whole history conversion.
let data = redacted.first().copied().unwrap_or_default();
return match BASE64_STANDARD.decode(data) {
Ok(bytes) => Ok(Some(aws_bedrock::ContentBlock::ReasoningContent(
aws_bedrock::ReasoningContentBlock::RedactedContent(
aws_smithy_types::Blob::new(bytes),
),
))),
Err(error) => {
tracing::warn!(
%error,
"dropping redacted reasoning content that is not valid \
base64"
);
Ok(None)
}
};
}
}
let signed_text_count = reasoning
.content
.iter()
.filter(|content| {
matches!(
content,
rig_core::message::ReasoningContent::Text {
signature: Some(_),
..
}
)
})
.count();
if signed_text_count > 1 {
return Err(ProviderError::Provider(
"AWS Bedrock does not support multiple signed reasoning text blocks"
.to_owned(),
));
}
if signed_text_count == 1 && reasoning.content.len() > 1 {
return Err(ProviderError::Provider(
"AWS Bedrock requires a single signed reasoning text block without additional reasoning parts"
.to_owned(),
));
}
let flattened_text = reasoning.display_text();
let has_signature = reasoning.first_signature().is_some();
// Signature-only reasoning must survive tool-call replay even
// when its plaintext is empty.
if flattened_text.is_empty() && !has_signature {
return Err(ProviderError::Provider(
"AWS Bedrock reasoning conversion requires at least one text or summary block"
.to_owned(),
));
}
let mut reasoning_block =
aws_bedrock::ReasoningTextBlock::builder().text(flattened_text);
if let Some(sig) = reasoning.first_signature().map(str::to_owned) {
reasoning_block = reasoning_block.signature(sig);
}
let reasoning_text_block = reasoning_block.build().map_err(|e| {
ProviderError::Provider(format!("Failed to build reasoning block: {e}"))
})?;
Ok(Some(aws_bedrock::ContentBlock::ReasoningContent(
aws_bedrock::ReasoningContentBlock::ReasoningText(reasoning_text_block),
)))
}
AssistantContent::Image(_) => Err(ProviderError::Provider(
"AWS Bedrock does not support image content in assistant messages".to_owned(),
)),
}
}
}
#[cfg(test)]
pub(crate) mod tests;