base/interface/
model_factory.rs1use std::collections::HashMap;
27use std::sync::Arc;
28
29use crate::interface::credentials::{ConfigCredentials, CredentialSource, Secret};
30use crate::interface::exec::Network;
31use crate::interface::model::Model;
32use crate::provider::ProviderConfig;
33
34pub trait ModelFactory: Send + Sync {
36 fn api_type(&self) -> &str;
38
39 fn build(
54 &self,
55 provider_id: &str,
56 config: &ProviderConfig,
57 credentials: &dyn CredentialSource,
58 network: Option<&Arc<dyn Network>>,
59 ) -> Result<Arc<dyn Model>, String>;
60}
61
62#[derive(Clone)]
64pub struct ModelFactoryRegistry {
65 by_api_type: HashMap<String, Arc<dyn ModelFactory>>,
66 credentials: Arc<dyn CredentialSource>,
67 network: Option<Arc<dyn Network>>,
68}
69
70impl Default for ModelFactoryRegistry {
71 fn default() -> Self {
72 Self {
73 by_api_type: HashMap::new(),
74 credentials: Arc::new(ConfigCredentials),
75 network: None,
76 }
77 }
78}
79
80impl ModelFactoryRegistry {
81 pub fn new() -> Self {
82 Self::default()
83 }
84
85 pub fn register(&mut self, factory: Arc<dyn ModelFactory>) -> Option<Arc<dyn ModelFactory>> {
93 self.by_api_type
94 .insert(factory.api_type().to_string(), factory)
95 }
96
97 pub fn with_credentials(mut self, source: Arc<dyn CredentialSource>) -> Self {
104 self.credentials = source;
105 self
106 }
107
108 pub fn with_network(mut self, network: Arc<dyn Network>) -> Self {
111 self.network = Some(network);
112 self
113 }
114
115 pub fn get(&self, api_type: &str) -> Option<&Arc<dyn ModelFactory>> {
116 self.by_api_type.get(api_type)
117 }
118
119 pub fn api_types(&self) -> Vec<&str> {
122 let mut out: Vec<&str> = self.by_api_type.keys().map(String::as_str).collect();
123 out.sort_unstable();
124 out
125 }
126
127 pub fn is_empty(&self) -> bool {
128 self.by_api_type.is_empty()
129 }
130
131 pub fn missing_credential(&self, provider_id: &str, config: &ProviderConfig) -> Option<String> {
134 NonEmpty(self.credentials.as_ref())
135 .api_key(provider_id, config)
136 .err()
137 }
138
139 pub fn build(
145 &self,
146 provider_id: &str,
147 config: &ProviderConfig,
148 ) -> Result<Arc<dyn Model>, String> {
149 let api_type = config.api();
150 match self.by_api_type.get(api_type) {
151 Some(f) => f.build(
152 provider_id,
153 config,
154 &NonEmpty(self.credentials.as_ref()),
155 self.network.as_ref(),
156 ),
157 None => Err(format!(
158 "provider '{provider_id}': unrecognized api '{api_type}' (expected {})",
159 self.api_types()
160 .iter()
161 .map(|t| format!("'{t}'"))
162 .collect::<Vec<_>>()
163 .join(" or ")
164 )),
165 }
166 }
167}
168
169struct NonEmpty<'a>(&'a dyn CredentialSource);
170
171impl CredentialSource for NonEmpty<'_> {
172 fn api_key(&self, provider_id: &str, config: &ProviderConfig) -> Result<Secret, String> {
173 let key = self.0.api_key(provider_id, config)?;
174 if key.is_empty() {
175 return Err("its API key is empty".to_string());
176 }
177 Ok(key)
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 struct Stub(&'static str);
186
187 impl ModelFactory for Stub {
188 fn api_type(&self) -> &str {
189 self.0
190 }
191 fn build(
192 &self,
193 _id: &str,
194 _cfg: &ProviderConfig,
195 _credentials: &dyn CredentialSource,
196 _network: Option<&Arc<dyn Network>>,
197 ) -> Result<Arc<dyn Model>, String> {
198 Err("stub".into())
199 }
200 }
201
202 #[test]
203 fn an_unknown_api_type_names_the_provider_and_what_is_available() {
204 let mut registry = ModelFactoryRegistry::new();
205 registry.register(Arc::new(Stub("anthropic")));
206 registry.register(Arc::new(Stub("openai_chat")));
207
208 let Err(err) = registry.build(
209 "my-provider",
210 &ProviderConfig {
211 api: Some("gemini".into()),
212 ..Default::default()
213 },
214 ) else {
215 panic!("an unregistered api must not build");
216 };
217 assert!(err.contains("my-provider"), "{err}");
218 assert!(err.contains("'gemini'"), "{err}");
219 assert!(
220 err.contains("'anthropic' or 'openai_chat'"),
221 "the list of what works must come from what is registered: {err}"
222 );
223 }
224
225 #[test]
226 fn no_api_type_means_anthropic() {
227 let mut registry = ModelFactoryRegistry::new();
228 registry.register(Arc::new(Stub("anthropic")));
229 let Err(err) = registry.build("p", &ProviderConfig::default()) else {
230 panic!("the stub factory never succeeds");
231 };
232 assert_eq!(
233 err, "stub",
234 "an absent api must reach the anthropic factory"
235 );
236 }
237
238 #[test]
239 fn a_host_can_take_over_a_built_in_api_type() {
240 let mut registry = ModelFactoryRegistry::new();
241 registry.register(Arc::new(Stub("anthropic")));
242 let replaced = registry.register(Arc::new(Stub("anthropic")));
243 assert!(
244 replaced.is_some(),
245 "replacing must hand back what it replaced, not silently stack"
246 );
247 assert_eq!(registry.api_types(), ["anthropic"]);
248 }
249}