use std::collections::HashMap;
use base64::Engine as _;
use base64::alphabet::STANDARD;
use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
use base64::prelude::BASE64_STANDARD;
use rig_core::completion::options::{BaseInput, FinalBody, RawAt, request_params};
use rig_core::completion::{CacheRetention, CompletionRequest, Message, Replay};
use rig_core::error::EncodeError;
use rig_core::message::{
AssistantContent, Document, DocumentData, DocumentMediaType, DocumentSourceKind, Image,
MimeType, ToolChoice, ToolResultContent, UserContent, Video,
};
use rig_core::providers::internal::wire_ids::WireIds;
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use crate::completion::{Converse, Family};
const BASE64: GeneralPurpose = GeneralPurpose::new(
&STANDARD,
GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
);
const EMPTY_TEXT: &str = "<empty>";
pub(crate) fn body(
wire: &Converse,
request: &CompletionRequest,
model: &str,
) -> Result<FinalBody, EncodeError> {
request_params(
wire,
request,
|input| base(wire, request, model, input),
RawAt::Under("/additionalModelRequestFields"),
&[],
)
}
fn checkpoint(cache: CacheRetention) -> Value {
match cache {
CacheRetention::Long => json!({ "cachePoint": { "type": "default", "ttl": "1h" } }),
_ => json!({ "cachePoint": { "type": "default" } }),
}
}
fn base(
wire: &Converse,
request: &CompletionRequest,
model: &str,
input: &mut BaseInput<'_>,
) -> Result<Map<String, Value>, EncodeError> {
let family = wire.family(model);
let cache = input.cache().filter(|cache| *cache != CacheRetention::None);
let leading = request
.chat_history
.iter()
.take_while(|message| matches!(&***message, Message::System { .. }))
.count();
let (system, history) = request
.chat_history
.split_at_checked(leading)
.unwrap_or_default();
let mut system: Vec<Value> = system
.iter()
.filter_map(|message| match &**message {
Message::System { content } if !content.is_empty() => Some(json!({ "text": content })),
_ => None,
})
.collect();
if let Some(cache) = cache
&& !system.is_empty()
{
system.push(checkpoint(cache));
}
let ids = WireIds::for_target(history, wire, model);
let mut messages: Vec<Value> = Vec::new();
for message in history {
let mut content = Vec::new();
let role = match &**message {
Message::System { content: text } => {
content.push(json!({ "text": text }));
"user"
}
Message::User { content: parts } => {
for part in parts {
content.extend(user(part, family, &ids)?);
}
if content.is_empty() {
content.push(json!({ "text": EMPTY_TEXT }));
}
"user"
}
Message::Assistant(turn) => {
for block in &turn.content {
content.extend(assistant(block, wire, family, &ids)?);
}
"assistant"
}
};
messages.push(json!({ "role": role, "content": content }));
}
let mut seen = HashMap::<String, usize>::new();
for name in blocks(&mut messages).filter_map(|block| block.pointer_mut("/document/name")) {
if let Value::String(name) = name {
let count = seen.entry(name.clone()).or_default();
*count += 1;
if *count > 1 {
*name = format!("{name}-{count}");
}
}
}
if let Some(cache) = cache {
let reasoning = blocks(&mut messages).any(|block| block.get("reasoningContent").is_some());
if reasoning {
input.refuse_cache(
"Bedrock rejects a message cache checkpoint after a reasoning turn",
)?;
} else if let Some(Value::Array(last)) =
messages.last_mut().and_then(|last| last.get_mut("content"))
{
last.push(checkpoint(cache));
}
}
let output = match &request.output_schema {
Some(schema) => Some(
json!({ "textFormat": { "type": "json_schema", "structure": { "jsonSchema": {
"schema": serde_json::to_string(schema.as_value())?,
"name": request.output_schema_name(),
} } } }),
),
None => None,
};
let inference = json!({
"temperature": request.temperature.map(|temperature| f64::from(temperature as f32)),
"maxTokens": request.max_tokens.map(|max_tokens| max_tokens as i32),
});
let body = present(json!({
"system": (!system.is_empty()).then_some(system),
"inferenceConfig": present(inference),
"toolConfig": tool_config(request)?,
"outputConfig": output,
"messages": messages,
}));
Ok(match body {
Value::Object(body) => body,
_ => Map::new(),
})
}
fn present(mut value: Value) -> Value {
if let Value::Object(fields) = &mut value {
fields.retain(|_, field| !field.is_null());
}
value
}
fn blocks(messages: &mut [Value]) -> impl Iterator<Item = &mut Value> {
messages
.iter_mut()
.filter_map(|message| message.get_mut("content")?.as_array_mut())
.flatten()
}
fn tool_config(request: &CompletionRequest) -> Result<Option<Value>, EncodeError> {
let choice = match &request.tool_choice {
Some(ToolChoice::None) => return Ok(None),
Some(ToolChoice::Auto) => Some(json!({ "auto": {} })),
Some(ToolChoice::Required) => Some(json!({ "any": {} })),
Some(ToolChoice::Specific { function_names }) => {
let [name] = function_names.as_slice() else {
return Err(EncodeError::request(
"Bedrock only supports forcing exactly one specific tool",
));
};
Some(json!({ "tool": { "name": name.as_str() } }))
}
None => None,
};
let tools: Vec<Value> = request
.tools
.iter()
.map(|tool| {
json!({ "toolSpec": {
"name": tool.name.as_str(),
"description": tool.description,
"inputSchema": { "json": tool.parameters },
} })
})
.collect();
Ok((!tools.is_empty()).then(|| present(json!({ "tools": tools, "toolChoice": choice }))))
}
fn assistant(
block: &AssistantContent,
wire: &Converse,
family: Family,
ids: &WireIds,
) -> Result<Option<Value>, EncodeError> {
if let AssistantContent::Opaque(opaque) = block {
return Ok(opaque.replay.then(|| whole_numbers(opaque.item.clone())));
}
if let Replay::Item(item) = block.replay(wire, ids) {
return Ok(Some(whole_numbers(item.into_owned())));
}
Ok(match block {
AssistantContent::Text(text) => Some(json!({ "text": text.text })),
AssistantContent::ToolCall(call) => Some(json!({ "toolUse": {
"toolUseId": ids.spell(&call.id),
"name": call.function.name.as_str(),
"input": call.function.arguments,
} })),
AssistantContent::Reasoning(reasoning)
if reasoning.redacted || reasoning.text.trim().is_empty() =>
{
None
}
AssistantContent::Reasoning(reasoning) if family == Family::Claude => {
Some(json!({ "text": reasoning.text }))
}
AssistantContent::Reasoning(reasoning) => {
Some(json!({ "reasoningContent": { "reasoningText": { "text": reasoning.text } } }))
}
AssistantContent::Image(image) => Some(json!({ "image": self::image(image)? })),
AssistantContent::Opaque(_) => None,
_ => {
return Err(EncodeError::request(
"Converse has no form for this assistant block",
));
}
})
}
pub(crate) fn sends(block: &AssistantContent, wire: &Converse) -> bool {
let family = wire.family(&wire.model);
assistant(block, wire, family, &WireIds::default()).is_ok_and(|block| block.is_some())
}
fn whole_numbers(value: Value) -> Value {
match value {
Value::Number(number) => match number.as_f64() {
Some(float) if number.is_f64() && float.fract() == 0.0 && float.abs() < 1e15 => {
json!(float as i64)
}
_ => Value::Number(number),
},
Value::Array(values) => Value::Array(values.into_iter().map(whole_numbers).collect()),
Value::Object(fields) => Value::Object(
fields
.into_iter()
.map(|(key, value)| (key, whole_numbers(value)))
.collect(),
),
value => value,
}
}
fn user(content: &UserContent, family: Family, ids: &WireIds) -> Result<Vec<Value>, EncodeError> {
let text = |text: &str| (!text.trim().is_empty()).then(|| json!({ "text": text }));
Ok(match content {
UserContent::Text(part) => text(&part.text).into_iter().collect(),
UserContent::ToolResult(result) => {
let mut parts = Vec::new();
for part in &result.content {
parts.extend(match part {
ToolResultContent::Text(part) => text(&part.text),
ToolResultContent::Image(part) => Some(json!({ "image": image(part)? })),
ToolResultContent::Json { value } if value.is_object() => {
Some(json!({ "json": value }))
}
ToolResultContent::Json { value } => {
Some(json!({ "json": { "result": value } }))
}
});
}
let failed = result.is_error && family != Family::Other;
let block = present(json!({
"toolUseId": ids.spell(&result.call),
"content": parts,
"status": failed.then_some("error"),
}));
vec![json!({ "toolResult": block })]
}
UserContent::Image(part) => vec![json!({ "image": image(part)? })],
UserContent::Document(part) => vec![
json!({ "text": "Use provided document" }),
json!({ "document": document(part)? }),
],
UserContent::Video(part) => vec![json!({ "video": video(part)? })],
UserContent::Audio(_) => return Err(EncodeError::request("Converse takes no audio")),
})
}
fn source(data: &DocumentSourceKind) -> Result<(Value, Vec<u8>), EncodeError> {
let bytes = match data {
DocumentSourceKind::Base64(data) => BASE64.decode(data).map_err(EncodeError::request)?,
DocumentSourceKind::Raw(bytes) => bytes.clone(),
DocumentSourceKind::Url(uri) if uri.starts_with("s3://") => {
return Ok((
json!({ "s3Location": { "uri": uri } }),
uri.as_bytes().to_vec(),
));
}
data => {
return Err(EncodeError::request(format!(
"Converse takes base64 data or an s3:// URL, not {data}"
)));
}
};
Ok((json!({ "bytes": BASE64_STANDARD.encode(&bytes) }), bytes))
}
fn media(
mime: Option<&str>,
listed: &[&str],
data: &DocumentSourceKind,
) -> Result<Value, EncodeError> {
let format = mime
.and_then(|mime| mime.split_once('/'))
.map(|(_, format)| format)
.filter(|format| listed.contains(format))
.ok_or_else(|| EncodeError::request("Converse takes no media in this format"))?;
Ok(json!({ "format": format, "source": source(data)?.0 }))
}
pub(crate) fn image(image: &Image) -> Result<Value, EncodeError> {
let mime = image.media_type.as_ref().map(MimeType::to_mime_type);
media(mime, &["jpeg", "png", "gif", "webp"], &image.data)
}
pub(crate) fn video(video: &Video) -> Result<Value, EncodeError> {
let mime = video.media_type.as_ref().map(MimeType::to_mime_type);
media(mime, &["mp4", "mpeg", "mov", "webm"], &video.data)
}
pub(crate) fn document(document: &Document) -> Result<Value, EncodeError> {
let mime = document
.media_type
.as_ref()
.map(|media_type| match media_type {
DocumentMediaType::PDF | DocumentMediaType::HTML | DocumentMediaType::CSV => {
media_type.to_mime_type()
}
DocumentMediaType::MARKDOWN => "text/md",
_ => "text/txt",
});
let DocumentData::File(data) = &document.data else {
return Err(EncodeError::request("a text document goes as text"));
};
let mut block = media(mime, &["pdf", "html", "csv", "md", "txt"], data)?;
let (_, bytes) = source(data)?;
let digest: String = Sha256::digest(&bytes)
.iter()
.take(8)
.map(|byte| format!("{byte:02x}"))
.collect();
if let Value::Object(fields) = &mut block {
fields.insert("name".to_owned(), json!(format!("document-{digest}")));
}
Ok(block)
}
#[cfg(test)]
mod tests;