subx_cli/services/ai/
factory.rs

1//! AI 客戶端工廠,用於根據配置建立對應提供商實例
2use crate::config::AIConfig;
3use crate::error::SubXError;
4use crate::services::ai::{AIProvider, OpenAIClient};
5
6/// AI 客戶端工廠
7pub struct AIClientFactory;
8
9impl AIClientFactory {
10    /// 根據 AIConfig 建立對應的 AIProvider 實例
11    pub fn create_client(config: &AIConfig) -> crate::Result<Box<dyn AIProvider>> {
12        match config.provider.as_str() {
13            "openai" => Ok(Box::new(OpenAIClient::from_config(config)?)),
14            other => Err(SubXError::config(format!("不支援的 AI 提供商: {}", other))),
15        }
16    }
17}
18
19#[cfg(test)]
20mod tests {
21    use super::*;
22    use crate::config::AIConfig;
23
24    #[test]
25    fn test_ai_factory_openai_provider() {
26        let config = AIConfig {
27            provider: "openai".to_string(),
28            api_key: Some("key".to_string()),
29            model: "m".to_string(),
30            base_url: "https://api.openai.com/v1".to_string(),
31            max_sample_length: 100,
32            temperature: 0.1,
33            retry_attempts: 1,
34            retry_delay_ms: 10,
35        };
36        // 應成功建立 OpenAIClient 實例
37        let res = AIClientFactory::create_client(&config);
38        assert!(res.is_ok());
39    }
40
41    #[test]
42    fn test_ai_factory_invalid_provider() {
43        let config = AIConfig {
44            provider: "unknown".to_string(),
45            api_key: Some("key".to_string()),
46            model: "m".to_string(),
47            base_url: "https://api.openai.com/v1".to_string(),
48            max_sample_length: 100,
49            temperature: 0.1,
50            retry_attempts: 1,
51            retry_delay_ms: 10,
52        };
53        // 不支援的提供商應返回錯誤
54        let res = AIClientFactory::create_client(&config);
55        assert!(res.is_err());
56    }
57}