Skip to main content

llm_stack_anthropic/
factory.rs

1//! Factory for building Anthropic providers from configuration.
2
3use llm_stack::registry::{ProviderConfig, ProviderFactory};
4use llm_stack::{DynProvider, LlmError};
5
6use crate::{AnthropicConfig, AnthropicProvider};
7
8/// Factory for creating [`AnthropicProvider`] instances from configuration.
9///
10/// Register this factory with the global registry to enable config-driven
11/// provider instantiation:
12///
13/// ```rust,no_run
14/// use llm_stack::ProviderRegistry;
15/// use llm_stack_anthropic::AnthropicFactory;
16///
17/// ProviderRegistry::global().register(Box::new(AnthropicFactory));
18/// ```
19///
20/// # Configuration
21///
22/// | Field | Required | Description |
23/// |-------|----------|-------------|
24/// | `provider` | Yes | Must be `"anthropic"` |
25/// | `api_key` | Yes | Anthropic API key |
26/// | `model` | Yes | Model identifier (e.g., `"claude-sonnet-4-20250514"`) |
27/// | `base_url` | No | Custom API endpoint |
28/// | `timeout` | No | Request timeout |
29/// | `extra.max_tokens` | No | Default max tokens (default: 4096) |
30/// | `extra.api_version` | No | API version header |
31#[derive(Debug, Clone, Copy, Default)]
32pub struct AnthropicFactory;
33
34impl ProviderFactory for AnthropicFactory {
35    fn name(&self) -> &'static str {
36        "anthropic"
37    }
38
39    fn build(&self, config: &ProviderConfig) -> Result<Box<dyn DynProvider>, LlmError> {
40        let api_key = config.api_key.clone().ok_or_else(|| {
41            LlmError::InvalidRequest("anthropic provider requires api_key".into())
42        })?;
43
44        if config.model.is_empty() {
45            return Err(LlmError::InvalidRequest(
46                "anthropic provider requires model".into(),
47            ));
48        }
49
50        let mut anthropic_config = AnthropicConfig {
51            api_key,
52            model: config.model.clone(),
53            ..Default::default()
54        };
55
56        if let Some(base_url) = &config.base_url {
57            anthropic_config.base_url.clone_from(base_url);
58        }
59
60        if let Some(timeout) = config.timeout {
61            anthropic_config.timeout = Some(timeout);
62        }
63
64        if let Some(max_tokens) = config.get_extra_i64("max_tokens") {
65            anthropic_config.max_tokens =
66                u32::try_from(max_tokens).unwrap_or(anthropic_config.max_tokens);
67        }
68
69        if let Some(api_version) = config.get_extra_str("api_version") {
70            anthropic_config.api_version = api_version.to_string();
71        }
72
73        Ok(Box::new(AnthropicProvider::new(anthropic_config)))
74    }
75}
76
77/// Registers the Anthropic factory with the global registry.
78///
79/// Call this once at application startup to enable config-driven
80/// Anthropic provider creation.
81pub fn register_global() {
82    llm_stack::ProviderRegistry::global().register(Box::new(AnthropicFactory));
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use std::time::Duration;
89
90    #[test]
91    fn test_factory_name() {
92        let factory = AnthropicFactory;
93        assert_eq!(factory.name(), "anthropic");
94    }
95
96    #[test]
97    fn test_factory_build_success() {
98        let factory = AnthropicFactory;
99        let config = ProviderConfig::new("anthropic", "claude-3")
100            .api_key("sk-test")
101            .timeout(Duration::from_secs(30))
102            .extra("max_tokens", 2048i64);
103
104        let provider = factory.build(&config).unwrap();
105        assert_eq!(provider.metadata().name, "anthropic");
106        assert_eq!(provider.metadata().model, "claude-3");
107    }
108
109    #[test]
110    fn test_factory_missing_api_key() {
111        let factory = AnthropicFactory;
112        let config = ProviderConfig::new("anthropic", "claude-3");
113
114        let err = factory.build(&config).err().unwrap();
115        assert!(matches!(err, LlmError::InvalidRequest(_)));
116    }
117
118    #[test]
119    fn test_factory_empty_model() {
120        let factory = AnthropicFactory;
121        let config = ProviderConfig::new("anthropic", "").api_key("sk-test");
122
123        let err = factory.build(&config).err().unwrap();
124        assert!(matches!(err, LlmError::InvalidRequest(_)));
125    }
126}