llm_stack_anthropic/
factory.rs1use llm_stack_core::registry::{ProviderConfig, ProviderFactory};
4use llm_stack_core::{DynProvider, LlmError};
5
6use crate::{AnthropicConfig, AnthropicProvider};
7
8#[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
77pub fn register_global() {
82 llm_stack_core::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}