use aws_config::{BehaviorVersion, Region};
use std::sync::Arc;
use tokio::sync::OnceCell;
use crate::completion::Converse;
use rig_core::Model;
#[derive(Clone, Debug, Default)]
pub struct Builder {
region: Option<String>,
profile_name: Option<String>,
}
impl Builder {
pub fn region(mut self, region: impl Into<String>) -> Self {
self.region = Some(region.into());
self
}
pub fn profile_name(mut self, profile_name: impl Into<String>) -> Self {
self.profile_name = Some(profile_name.into());
self
}
pub fn build(self) -> BedrockRuntime {
BedrockRuntime {
settings: self,
aws_client: Arc::new(OnceCell::new()),
}
}
}
#[derive(Clone, Debug)]
pub struct BedrockRuntime {
settings: Builder,
aws_client: Arc<OnceCell<aws_sdk_bedrockruntime::Client>>,
}
impl From<aws_sdk_bedrockruntime::Client> for BedrockRuntime {
fn from(aws_client: aws_sdk_bedrockruntime::Client) -> Self {
Self {
settings: Builder::default(),
aws_client: Arc::new(OnceCell::from(aws_client)),
}
}
}
impl BedrockRuntime {
pub fn builder() -> Builder {
Builder::default()
}
pub fn from_env() -> Self {
Builder::default().build()
}
pub fn completion(&self, model: impl Into<String>) -> Model<Converse, Self> {
Model::new(Converse::new(model), self.clone())
}
pub async fn inner(&self) -> &aws_sdk_bedrockruntime::Client {
self.aws_client
.get_or_init(|| async {
let mut loader = aws_config::defaults(BehaviorVersion::latest());
if let Some(profile_name) = &self.settings.profile_name {
loader = loader.profile_name(profile_name);
}
if let Some(region) = self.settings.region.clone() {
loader = loader.region(Region::new(region));
}
aws_sdk_bedrockruntime::Client::new(&loader.load().await)
})
.await
}
}
#[cfg(test)]
mod tests;