use std::collections::HashMap;
use std::sync::Arc;
use crate::interface::credentials::{ConfigCredentials, CredentialSource, Secret};
use crate::interface::exec::Network;
use crate::interface::model::Model;
use crate::provider::ProviderConfig;
pub trait ModelFactory: Send + Sync {
fn api_type(&self) -> &str;
fn build(
&self,
provider_id: &str,
config: &ProviderConfig,
credentials: &dyn CredentialSource,
network: Option<&Arc<dyn Network>>,
) -> Result<Arc<dyn Model>, String>;
}
#[derive(Clone)]
pub struct ModelFactoryRegistry {
by_api_type: HashMap<String, Arc<dyn ModelFactory>>,
credentials: Arc<dyn CredentialSource>,
network: Option<Arc<dyn Network>>,
}
impl Default for ModelFactoryRegistry {
fn default() -> Self {
Self {
by_api_type: HashMap::new(),
credentials: Arc::new(ConfigCredentials),
network: None,
}
}
}
impl ModelFactoryRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, factory: Arc<dyn ModelFactory>) -> Option<Arc<dyn ModelFactory>> {
self.by_api_type
.insert(factory.api_type().to_string(), factory)
}
pub fn with_credentials(mut self, source: Arc<dyn CredentialSource>) -> Self {
self.credentials = source;
self
}
pub fn with_network(mut self, network: Arc<dyn Network>) -> Self {
self.network = Some(network);
self
}
pub fn get(&self, api_type: &str) -> Option<&Arc<dyn ModelFactory>> {
self.by_api_type.get(api_type)
}
pub fn api_types(&self) -> Vec<&str> {
let mut out: Vec<&str> = self.by_api_type.keys().map(String::as_str).collect();
out.sort_unstable();
out
}
pub fn is_empty(&self) -> bool {
self.by_api_type.is_empty()
}
pub fn missing_credential(&self, provider_id: &str, config: &ProviderConfig) -> Option<String> {
NonEmpty(self.credentials.as_ref())
.api_key(provider_id, config)
.err()
}
pub fn build(
&self,
provider_id: &str,
config: &ProviderConfig,
) -> Result<Arc<dyn Model>, String> {
let api_type = config.api();
match self.by_api_type.get(api_type) {
Some(f) => f.build(
provider_id,
config,
&NonEmpty(self.credentials.as_ref()),
self.network.as_ref(),
),
None => Err(format!(
"provider '{provider_id}': unrecognized api '{api_type}' (expected {})",
self.api_types()
.iter()
.map(|t| format!("'{t}'"))
.collect::<Vec<_>>()
.join(" or ")
)),
}
}
}
struct NonEmpty<'a>(&'a dyn CredentialSource);
impl CredentialSource for NonEmpty<'_> {
fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String> {
let key = self.0.api_key(provider_id, config)?;
if key.is_empty() {
return Err("its API key is empty".to_string());
}
Ok(key)
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Stub(&'static str);
impl ModelFactory for Stub {
fn api_type(&self) -> &str {
self.0
}
fn build(
&self,
_id: &str,
_cfg: &ProviderConfig,
_credentials: &dyn CredentialSource,
_network: Option<&Arc<dyn Network>>,
) -> Result<Arc<dyn Model>, String> {
Err("stub".into())
}
}
#[test]
fn an_unknown_api_type_names_the_provider_and_what_is_available() {
let mut registry = ModelFactoryRegistry::new();
registry.register(Arc::new(Stub("anthropic")));
registry.register(Arc::new(Stub("openai_chat")));
let Err(err) = registry.build(
"my-provider",
&ProviderConfig {
api: Some("gemini".into()),
..Default::default()
},
) else {
panic!("an unregistered api must not build");
};
assert!(err.contains("my-provider"), "{err}");
assert!(err.contains("'gemini'"), "{err}");
assert!(
err.contains("'anthropic' or 'openai_chat'"),
"the list of what works must come from what is registered: {err}"
);
}
#[test]
fn no_api_type_means_anthropic() {
let mut registry = ModelFactoryRegistry::new();
registry.register(Arc::new(Stub("anthropic")));
let Err(err) = registry.build("p", &ProviderConfig::default()) else {
panic!("the stub factory never succeeds");
};
assert_eq!(
err, "stub",
"an absent api must reach the anthropic factory"
);
}
#[test]
fn a_host_can_take_over_a_built_in_api_type() {
let mut registry = ModelFactoryRegistry::new();
registry.register(Arc::new(Stub("anthropic")));
let replaced = registry.register(Arc::new(Stub("anthropic")));
assert!(
replaced.is_some(),
"replacing must hand back what it replaced, not silently stack"
);
assert_eq!(registry.api_types(), ["anthropic"]);
}
}