use async_trait::async_trait;
use tokio::sync::OnceCell;
use super::bedrock::BedrockChatClient;
use super::client::{LlmClient, LlmClientConfig};
use super::client_trait::LlmClientTrait;
use super::error::LlmError;
use super::request::ChatRequest;
use super::response::ChatResponse;
const BEDROCK_PROVIDER_NAME: &str = "bedrock";
#[derive(Debug)]
pub struct DispatchingLlmClient {
openrouter: Option<LlmClient>,
bedrock: OnceCell<BedrockChatClient>,
}
impl DispatchingLlmClient {
pub fn new(openrouter_config: Option<LlmClientConfig>) -> Result<Self, LlmError> {
let openrouter = openrouter_config.map(LlmClient::from_config).transpose()?;
Ok(Self {
openrouter,
bedrock: OnceCell::new(),
})
}
pub fn from_config(config: LlmClientConfig) -> Result<Self, LlmError> {
Self::new(Some(config))
}
pub fn from_env() -> Result<Self, LlmError> {
Self::from_config(LlmClientConfig::from_env()?)
}
async fn bedrock(&self) -> Result<&BedrockChatClient, LlmError> {
self.bedrock
.get_or_try_init(BedrockChatClient::from_env)
.await
}
fn routes_to_bedrock(model: &str) -> bool {
crate::provider::provider_for(model).name() == BEDROCK_PROVIDER_NAME
}
}
#[async_trait]
impl LlmClientTrait for DispatchingLlmClient {
async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
if Self::routes_to_bedrock(&req.model) {
self.bedrock().await?.chat(req).await
} else {
let client = self.openrouter.as_ref().ok_or_else(|| {
LlmError::MissingConfig(format!(
"OPENROUTER_API_KEY is required to reach model '{}' (not a bedrock/* \
slug). Export it before running, e.g. `export OPENROUTER_API_KEY=sk-or-...`.",
req.model
))
})?;
client.chat(req).await
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn routes_bedrock_prefix_true() {
assert!(DispatchingLlmClient::routes_to_bedrock(
"bedrock/us.anthropic.claude-sonnet-4-6"
));
}
#[test]
fn routes_non_bedrock_prefix_false() {
for slug in [
"anthropic/claude-sonnet-4-5",
"openai/gpt-4o-mini",
"qwen/qwen-2.5-coder-32b-instruct",
] {
assert!(
!DispatchingLlmClient::routes_to_bedrock(slug),
"slug {slug} must not route to Bedrock"
);
}
}
#[test]
fn openrouter_slug_never_touches_bedrock_cell() {
let config = LlmClientConfig::new("sk-or-test").expect("config");
let client = DispatchingLlmClient::from_config(config);
assert!(client.is_ok(), "expected Ok, got: {client:?}");
}
#[test]
fn construction_succeeds_with_no_openrouter_config() {
let client = DispatchingLlmClient::new(None);
assert!(client.is_ok(), "expected Ok, got: {client:?}");
}
#[tokio::test]
async fn openrouter_request_without_config_fails_at_chat_time() {
let client = DispatchingLlmClient::new(None).expect("construction succeeds");
let req = ChatRequest {
model: "anthropic/claude-sonnet-4-5".to_string(),
messages: vec![],
temperature: None,
max_tokens: None,
tools: None,
tool_choice: None,
usage: None,
};
let err = client.chat(&req).await.unwrap_err();
assert!(
matches!(err, LlmError::MissingConfig(_)),
"expected MissingConfig, got: {err:?}"
);
}
}