Skip to main content

base/interface/
model_factory.rs

1//! `ModelFactory` — how a wire protocol gets built from configuration.
2//!
3//! [`Model`] is open: anyone can implement another protocol. Constructing one
4//! was not. The composition root matched on the protocol name and knew exactly two
5//! answers, so a third protocol could be written but never reached — the only
6//! way to configure it was to edit the match, in the kernel, in a release.
7//!
8//! # What is registered, and by what key
9//!
10//! The key is a provider's `api` **string** from `settings.json`, not the
11//! [`ApiType`] enum. That enum names the protocols the engine itself
12//! implements and is what a [`Model`] reports about itself; the registry is
13//! about what a *host* can add, and a host adding a protocol has no way to
14//! add a variant to an enum in this crate. A third-party model reports
15//! whichever `ApiType` describes its wire shape most closely, which affects
16//! how it is labeled in telemetry and nothing else.
17//!
18//! # Unknown means unknown at startup
19//!
20//! [`ModelFactoryRegistry::build`] fails for an `api` nobody claimed,
21//! and it fails where provider config is read — at startup — rather than on
22//! the first call that happens to route there. A typo in a provider name
23//! should cost a clear error at launch, not a mid-conversation failure in
24//! whichever session first uses that task type.
25
26use 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
34/// Builds a live model from one provider's configuration.
35pub trait ModelFactory: Send + Sync {
36    /// The `api` value in `settings.json` this factory answers to.
37    fn api_type(&self) -> &str;
38
39    /// Construct the model, or say what is wrong with the config.
40    ///
41    /// `provider_id` is only for the error message — it is the name the user
42    /// wrote, and an error that does not name it makes them guess which of
43    /// their providers is broken.
44    ///
45    /// The credential comes from `credentials`, never from `config.api_key_env`
46    /// directly: a factory that reads the field itself silently opts its
47    /// protocol out of whatever the host arranged, which is exactly the bug
48    /// the source exists to prevent.
49    ///
50    /// `network`, when there is one, is the egress the model's requests go
51    /// out on — it carries the deployment's `User-Agent`; `None` leaves the
52    /// factory's own.
53    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/// Every wire protocol this process can construct.
63#[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    /// Add a factory, replacing any previous one for the same `api` and
86    /// returning it.
87    ///
88    /// Replacing is allowed on purpose: a host that wants its own client
89    /// behind `anthropic` — a proxy, a recording layer, a different retry
90    /// policy — should not have to invent a new `api` its users then
91    /// have to write in their settings.
92    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    /// Ask `source` for every credential instead of reading `settings.json`.
98    ///
99    /// One source for the whole registry, not one per protocol: "where do
100    /// this deployment's credentials come from" is a property of the
101    /// deployment, and letting it vary per protocol would mean a host could
102    /// secure one and forget the other.
103    pub fn with_credentials(mut self, source: Arc<dyn CredentialSource>) -> Self {
104        self.credentials = source;
105        self
106    }
107
108    /// Send every model's requests through `network`. One for the whole
109    /// registry, for the reason credentials are.
110    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    /// The registered `api` values, sorted — for error messages, so what
120    /// the user is told they may write is generated from what actually works.
121    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    /// Why the credential source has no usable key for this provider, when
132    /// it has none.
133    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    /// Build the model one provider config describes.
140    ///
141    /// An absent `api` means `anthropic`. An empty key from the source
142    /// is no key: the factory is not asked to build a client that would send
143    /// requests with it.
144    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}