use std::collections::BTreeMap;
use rig_core::completion::{ExtensionOptions, ProviderExtension, ReplyExtras};
use rig_core::message::Api;
use serde::de::DeserializeOwned;
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize, Serializer};
use serde_json::Value;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BedrockExt;
impl ProviderExtension for BedrockExt {
const PROVIDER: &'static str = crate::completion::PROVIDER_NAME;
type Options = BedrockOptions;
type Extras = BedrockExtras;
}
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct BedrockOptions {
#[serde(rename = "*")]
pub shared: BedrockShared,
}
impl ExtensionOptions for BedrockOptions {
type Ext = BedrockExt;
}
impl BedrockOptions {
pub fn guardrail(mut self, guardrail: Guardrail) -> Self {
self.shared.guardrail = Some(guardrail);
self
}
pub fn performance_latency(mut self, latency: PerformanceLatency) -> Self {
self.shared.performance_latency = Some(latency);
self
}
pub fn request_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.shared
.request_metadata
.insert(key.into(), value.into());
self
}
pub fn additional_response_field_path(mut self, path: impl Into<String>) -> Self {
self.shared
.additional_response_field_paths
.push(path.into());
self
}
pub fn anthropic_beta(mut self, beta: impl Into<String>) -> Self {
self.shared.anthropic_beta.push(beta.into());
self
}
pub fn top_k(mut self, top_k: u32) -> Self {
self.shared.top_k = Some(top_k);
self
}
}
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BedrockShared {
pub guardrail: Option<Guardrail>,
pub performance_latency: Option<PerformanceLatency>,
pub request_metadata: BTreeMap<String, String>,
pub additional_response_field_paths: Vec<String>,
pub anthropic_beta: Vec<String>,
pub top_k: Option<u32>,
}
#[derive(Serialize)]
struct ModelFields<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
top_k: Option<u32>,
#[serde(skip_serializing_if = "<[String]>::is_empty")]
anthropic_beta: &'a [String],
}
#[derive(Serialize)]
struct Performance {
latency: PerformanceLatency,
}
impl Serialize for BedrockShared {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(None)?;
if let Some(guardrail) = &self.guardrail {
map.serialize_entry("guardrailConfig", guardrail)?;
}
if let Some(latency) = self.performance_latency {
map.serialize_entry("performanceConfig", &Performance { latency })?;
}
if !self.request_metadata.is_empty() {
map.serialize_entry("requestMetadata", &self.request_metadata)?;
}
if !self.additional_response_field_paths.is_empty() {
map.serialize_entry(
"additionalModelResponseFieldPaths",
&self.additional_response_field_paths,
)?;
}
if self.top_k.is_some() || !self.anthropic_beta.is_empty() {
map.serialize_entry(
"additionalModelRequestFields",
&ModelFields {
top_k: self.top_k,
anthropic_beta: &self.anthropic_beta,
},
)?;
}
map.end()
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Guardrail {
#[serde(rename = "guardrailIdentifier")]
pub identifier: String,
#[serde(rename = "guardrailVersion")]
pub version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub trace: Option<GuardrailTrace>,
}
impl Guardrail {
pub fn new(identifier: impl Into<String>, version: impl Into<String>) -> Self {
Self {
identifier: identifier.into(),
version: version.into(),
trace: None,
}
}
pub fn trace(mut self, trace: GuardrailTrace) -> Self {
self.trace = Some(trace);
self
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GuardrailTrace {
Enabled,
Disabled,
EnabledFull,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PerformanceLatency {
Standard,
Optimized,
}
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BedrockExtras {
pub stop_reason: Option<String>,
pub latency_ms: Option<u64>,
pub cache_details: Option<Vec<CacheDetail>>,
pub service_tier: Option<String>,
pub performance_latency: Option<String>,
pub trace: Option<Value>,
pub invoked_model_id: Option<String>,
pub additional_model_response_fields: Option<Value>,
}
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CacheDetail {
pub input_tokens: Option<u64>,
pub ttl: Option<String>,
}
fn at<T: DeserializeOwned>(raw: &Value, pointer: &str) -> Result<Option<T>, serde_json::Error> {
match raw.pointer(pointer) {
None | Some(Value::Null) => Ok(None),
Some(value) => T::deserialize(value).map(Some),
}
}
impl ReplyExtras for BedrockExtras {
fn from_reply(_api: &Api, raw: &Value) -> Result<Self, serde_json::Error> {
Ok(Self {
stop_reason: at(raw, "/stopReason")?,
latency_ms: at(raw, "/metrics/latencyMs")?,
cache_details: at(raw, "/usage/cacheDetails")?,
service_tier: at(raw, "/serviceTier/type")?,
performance_latency: at(raw, "/performanceConfig/latency")?,
trace: at(raw, "/trace")?,
invoked_model_id: at(raw, "/trace/promptRouter/invokedModelId")?,
additional_model_response_fields: at(raw, "/additionalModelResponseFields")?,
})
}
}
#[cfg(test)]
mod tests;