use aws_sdk_bedrockruntime::config::http::HttpResponse;
use aws_sdk_bedrockruntime::error::{ProvideErrorMetadata, SdkError};
use aws_sdk_bedrockruntime::operation::RequestId;
use rig_core::catalog::{ModelFacts, ModelSpec};
use rig_core::completion::options::FinalBody;
use rig_core::completion::{Accepts, CompletionRequest, Media, Pairing, ReplayTarget};
use rig_core::driver::{Exchange, Opened, Opening, Transport};
use rig_core::error::{EncodeError, ProviderError};
use rig_core::json_utils::Lenient;
use rig_core::message::{Api, DocumentData, DocumentSourceKind, Origin, ToolChoice};
use rig_core::operation::Completion;
use rig_core::wire::{Descriptor, Mode, Wire};
use serde_json::Value;
use crate::capture::{self, Capture, Events};
use crate::client::BedrockRuntime;
use crate::request;
use crate::streaming::StreamState;
use crate::types::errors::sdk_error;
pub const PROVIDER_NAME: &str = "aws_bedrock";
pub const AMAZON_NOVA_LITE: &str = "amazon.nova-lite-v1:0";
pub const AMAZON_NOVA_MICRO: &str = "amazon.nova-micro-v1:0";
pub const AMAZON_NOVA_PRO: &str = "amazon.nova-pro-v1:0";
pub const ANTHROPIC_CLAUDE_HAIKU_4_5: &str = "us.anthropic.claude-haiku-4-5-20251001-v1:0";
pub const ANTHROPIC_CLAUDE_SONNET_4_5: &str = "us.anthropic.claude-sonnet-4-5-20250929-v1:0";
pub const ANTHROPIC_CLAUDE_OPUS_4_5: &str = "us.anthropic.claude-opus-4-5-20251101-v1:0";
pub const ANTHROPIC_CLAUDE_SONNET_4_6: &str = "us.anthropic.claude-sonnet-4-6";
pub const ANTHROPIC_CLAUDE_SONNET_5: &str = "us.anthropic.claude-sonnet-5";
pub const ANTHROPIC_CLAUDE_OPUS_5: &str = "us.anthropic.claude-opus-5";
pub const DEEPSEEK_R1: &str = "us.deepseek.r1-v1:0";
pub const LLAMA_3_8B_INSTRUCT: &str = "meta.llama3-8b-instruct-v1:0";
pub const LLAMA_3_70B_INSTRUCT: &str = "meta.llama3-70b-instruct-v1:0";
pub const LLAMA_3_1_8B_INSTRUCT: &str = "meta.llama3-1-8b-instruct-v1:0";
pub const LLAMA_3_1_70B_INSTRUCT: &str = "meta.llama3-1-70b-instruct-v1:0";
pub const META_LLAMA_3_3_70B_INSTRUCT: &str = "us.meta.llama3-3-70b-instruct-v1:0";
pub const META_LLAMA_4_MAVERICK_17B_INSTRUCT: &str = "us.meta.llama4-maverick-17b-instruct-v1:0";
pub const META_LLAMA_4_SCOUT_17B_INSTRUCT: &str = "us.meta.llama4-scout-17b-instruct-v1:0";
pub const MISTRAL_7B_INSTRUCT: &str = "mistral.mistral-7b-instruct-v0:2";
pub const MISTRAL_LARGE_24_02: &str = "mistral.mistral-large-2402-v1:0";
pub const MISTRAL_SMALL_24_02: &str = "mistral.mistral-small-2402-v1:0";
pub const MISTRAL_MIXTRAL_8X7B_INSTRUCT_V0: &str = "mistral.mixtral-8x7b-instruct-v0:1";
pub const MISTRAL_PIXTRAL_LARGE_2502: &str = "us.mistral.pixtral-large-2502-v1:0";
pub const WRITER_PALMYRA_X4: &str = "us.writer.palmyra-x4-v1:0";
pub const WRITER_PALMYRA_X5: &str = "us.writer.palmyra-x5-v1:0";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Family {
Claude,
Nova,
Other,
}
impl Family {
pub fn of(model: &str) -> Self {
let id = model.rsplit('/').next().unwrap_or(model);
let mut parts = id.rsplit('.');
match (parts.next(), parts.next()) {
(_, Some("anthropic")) => Self::Claude,
(Some(name), Some("amazon")) if name.starts_with("nova") => Self::Nova,
_ => Self::Other,
}
}
}
#[derive(Clone, Debug)]
pub struct Converse {
pub model: String,
pub family: Option<Family>,
pub facts: ModelFacts,
}
impl Converse {
pub fn new(model: impl Into<String>) -> Self {
Self {
model: model.into(),
family: None,
facts: ModelFacts::default(),
}
}
pub fn with_facts(mut self, facts: ModelFacts) -> Self {
self.facts = facts;
self
}
pub fn with_family(mut self, family: Family) -> Self {
self.family = Some(family);
self
}
pub fn family(&self, model: &str) -> Family {
match self.family {
Some(family) if model == self.model => family,
_ => Family::of(model),
}
}
}
#[derive(Clone, Debug)]
pub struct ConverseRequest {
pub model: String,
pub body: FinalBody,
}
#[derive(Clone, Debug)]
pub enum ConverseFrame {
Whole(Value),
Event(Value),
}
impl Wire for Converse {
type Op = Completion;
type Payload = ConverseRequest;
type Frame = ConverseFrame;
type Event = ConverseFrame;
type Decoder<'id> = StreamState;
type Reassembler = crate::streaming::document::ConverseOutput;
fn describe(&self) -> Descriptor<'_> {
Descriptor::new(PROVIDER_NAME)
.model(self.model.as_str())
.facts(&self.facts)
.replay(self)
}
fn encode(
&self,
request: CompletionRequest,
_mode: Mode,
) -> Result<ConverseRequest, EncodeError> {
let model = request.model.clone().unwrap_or_else(|| self.model.clone());
let body = request::body(self, &request, &model)?;
Ok(ConverseRequest { model, body })
}
fn decoder<'id>(&self) -> Self::Decoder<'id> {
StreamState::default()
}
}
const TEXT_ONLY: &str = "amazon.nova-micro deepseek. meta.llama3-8b meta.llama3-70b \
meta.llama3-1- meta.llama3-3- minimax. mistral.devstral mistral.mistral-7b \
mistral.mistral-large-2402 mistral.mistral-small-2402 mistral.mixtral mistral.voxtral \
moonshot.kimi-k2-thinking nvidia.nemotron-nano-3 nvidia.nemotron-nano-9b \
nvidia.nemotron-super openai.gpt-oss qwen.qwen3-2 qwen.qwen3-3 qwen.qwen3-coder \
qwen.qwen3-next writer.palmyra zai.glm";
impl Converse {
pub fn spec(&self, model: &str) -> Option<&ModelSpec> {
spec_in(&self.facts, model)
}
}
fn spec_in<'f>(facts: &'f ModelFacts, model: &str) -> Option<&'f ModelSpec> {
let id = model.rsplit('/').next().unwrap_or(model);
let base = id
.split_once('.')
.filter(|(geo, base)| {
!geo.is_empty()
&& geo.bytes().all(|byte| byte.is_ascii_lowercase())
&& base.contains('.')
})
.map(|(_, base)| base);
[Some(id), base]
.into_iter()
.flatten()
.flat_map(|id| [Some(id), unrevised(id)])
.flatten()
.find_map(|id| facts.for_model(PROVIDER_NAME, id))
}
fn unrevised(id: &str) -> Option<&str> {
let (model, revision) = id.rsplit_once("-v")?;
let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
let (major, minor) = revision.split_once(':').unwrap_or((revision, "0"));
(digits(major) && digits(minor)).then_some(model)
}
impl ReplayTarget for Converse {
fn map_options(
&self,
request: &CompletionRequest,
fields: rig_core::completion::options::OptionFields<'_>,
) -> rig_core::completion::options::OptionMap {
let model = request.model.as_deref().unwrap_or(&self.model);
crate::options::converse(self, self.family(model), model, request, fields)
}
fn facts(&self) -> Option<&ModelFacts> {
Some(&self.facts)
}
fn api(&self) -> Api {
Api::from_static("bedrock.converse")
}
fn provider(&self) -> &str {
PROVIDER_NAME
}
fn model(&self) -> &str {
&self.model
}
fn accepts(&self, model: &str) -> Accepts {
let images = self.family(model) == Family::Claude
|| self.spec(model).map_or_else(
|| {
!TEXT_ONLY
.split_whitespace()
.any(|family| model.contains(family))
},
|spec| spec.input.image,
);
Accepts {
user_images: images,
assistant_images: false,
tool_result_images: images,
tools: true,
foreign_reasoning: false,
}
}
fn binds_context(&self, model: &str) -> bool {
self.family(model) == Family::Claude
&& self
.spec(model)
.is_some_and(|spec| spec.compat.binds_context)
}
fn starts_with_user(&self) -> bool {
true
}
fn later_system(&self, _model: &str) -> rig_core::completion::LaterSystem {
rig_core::completion::LaterSystem::UserText
}
fn alternates_roles(&self) -> bool {
true
}
fn hosted_needs_tools(&self) -> bool {
true
}
fn declares_tools(&self, request: &CompletionRequest) -> bool {
!request.tools.is_empty() && !matches!(request.tool_choice, Some(ToolChoice::None))
}
fn sends_alone(&self, block: &rig_core::message::AssistantContent) -> bool {
crate::request::sends(block, self)
}
fn encodes(&self, model: &str, media: Media<'_>) -> bool {
let nova = self.family(model) == Family::Nova;
let stored = |data: &DocumentSourceKind| {
nova || !matches!(data, DocumentSourceKind::Url(url) if url.starts_with("s3://"))
};
match media {
Media::Image(image, _) => stored(&image.data) && request::image(image).is_ok(),
Media::Document(document) => {
matches!(&document.data, DocumentData::File(data) if stored(data))
&& request::document(document).is_ok()
}
Media::Video(video) => {
nova && self.accepts(model).user_images && request::video(video).is_ok()
}
Media::Audio(_) => false,
}
}
fn normalize_tool_call_id(&self, id: &str, _model: &str, _source: Option<&Origin>) -> String {
rig_core::providers::internal::wire_ids::legal_call_id(id, 64)
}
fn call_id_slot(&self) -> Option<&'static str> {
Some("/toolUse/toolUseId")
}
fn blob_slots(&self) -> &'static [&'static str] {
&[
"/reasoningContent/reasoningText/signature",
"/reasoningContent/redactedContent",
]
}
fn hosted_pair(&self, item: &Value) -> Option<(Pairing, String)> {
let (side, body) = match item.get("toolUse") {
Some(body) => (Pairing::Use, body),
None => (Pairing::Result, item.get("toolResult")?),
};
Some((side, body.str("toolUseId")?.to_owned()))
}
}
fn sent<O: RequestId, E: ProvideErrorMetadata>(
sent: Result<O, SdkError<E, HttpResponse>>,
) -> (Option<String>, Option<ProviderError>) {
match sent {
Ok(output) => (output.request_id().map(str::to_owned), None),
Err(error) => (
error.request_id().map(str::to_owned),
Some(sdk_error(error)),
),
}
}
impl Transport<Converse> for BedrockRuntime {
fn send(&self, payload: ConverseRequest, exchange: Exchange) -> Opening<ConverseFrame> {
let ConverseRequest { model, body } = payload;
let capture = match serde_json::to_vec(&body) {
Ok(body) => Capture::new(body),
Err(error) => return Opening::failed(ProviderError::request(error)),
};
let runtime = self.clone();
Opening::new(async move {
let client = runtime.inner().await;
let unary = exchange.mode == Mode::Unary;
let interceptor = capture.clone();
let (request_id, failure) = if unary {
let call = client.converse().model_id(model).customize();
sent(call.interceptor(interceptor).send().await)
} else {
let call = client.converse_stream().model_id(model).customize();
sent(call.interceptor(interceptor).send().await)
};
let Some(mut body) = capture.reply() else {
let failure = failure.unwrap_or_else(|| {
ProviderError::Response("Converse sent no reply".to_owned())
});
return Ok(Opened::failed(failure));
};
if unary {
let mut bytes = Vec::new();
while let Some(chunk) = capture::chunk(&mut body).await {
bytes.extend(chunk?);
}
let document: Value = serde_json::from_slice(&bytes)
.map_err(|error| ProviderError::Json(error.into()))?;
let frames = futures::stream::iter([Ok(ConverseFrame::Whole(document.clone()))]);
return Ok(Opened::new(frames)
.with_request_id(request_id)
.with_document(document));
}
let frames = async_stream::stream! {
let mut events = Events::default();
while let Some(chunk) = capture::chunk(&mut body).await {
match chunk {
Ok(chunk) => {
for event in events.read(&chunk) {
yield Ok(ConverseFrame::Event(event));
}
}
Err(error) => {
yield Err(error);
break;
}
}
}
};
Ok(Opened::new(frames).with_request_id(request_id))
})
}
}
#[cfg(test)]
mod tests;