use aws_config::{BehaviorVersion, Region};
use std::sync::Arc;
use tokio::sync::OnceCell;
use crate::completion::Converse;
use crate::embedding::Embeddings;
use crate::image::Images;
use rig_core::Model;
pub const DEFAULT_AWS_REGION: &str = "us-east-1";
#[derive(Clone)]
pub struct Builder<'a> {
region: &'a str,
}
impl<'a> Builder<'a> {
pub fn region(mut self, region: &'a str) -> Self {
self.region = region;
self
}
pub async fn build(self) -> BedrockRuntime {
let sdk_config = aws_config::defaults(BehaviorVersion::latest())
.region(Region::new(String::from(self.region)))
.load()
.await;
BedrockRuntime::from(aws_sdk_bedrockruntime::Client::new(&sdk_config))
}
}
impl Default for Builder<'_> {
fn default() -> Self {
Self {
region: DEFAULT_AWS_REGION,
}
}
}
#[derive(Clone, Debug)]
pub struct BedrockRuntime {
profile_name: Option<String>,
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 {
profile_name: None,
aws_client: Arc::new(OnceCell::from(aws_client)),
}
}
}
impl BedrockRuntime {
pub fn builder<'a>() -> Builder<'a> {
Builder::default()
}
pub fn from_env() -> Self {
Self {
profile_name: None,
aws_client: Arc::new(OnceCell::new()),
}
}
pub fn with_profile_name(profile_name: &str) -> Self {
Self {
profile_name: Some(profile_name.into()),
aws_client: Arc::new(OnceCell::new()),
}
}
pub fn completion(&self, model: impl Into<String>) -> Model<Converse, Self> {
Model::new(Converse::new(model), self.clone())
}
pub fn embedding(
&self,
model: impl Into<String>,
ndims: Option<usize>,
) -> Model<Embeddings, Self> {
Model::new(Embeddings::new(model, ndims), self.clone())
}
pub fn image_generation(&self, model: impl Into<String>) -> Model<Images, Self> {
Model::new(Images::new(model), self.clone())
}
pub async fn inner(&self) -> &aws_sdk_bedrockruntime::Client {
self.aws_client
.get_or_init(|| async {
let config = if let Some(profile_name) = &self.profile_name {
aws_config::defaults(BehaviorVersion::latest())
.profile_name(profile_name)
.load()
.await
} else {
aws_config::load_from_env().await
};
aws_sdk_bedrockruntime::Client::new(&config)
})
.await
}
}