test_openai_specific/
test_openai_specific.rs

1use ai_lib::{AiClient, Provider, ChatCompletionRequest, Message, Role};
2
3#[tokio::main]
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    println!("🤖 OpenAI 专项测试");
6    println!("==================");
7    
8    // 检查OpenAI API密钥
9    match std::env::var("OPENAI_API_KEY") {
10        Ok(key) => {
11            let masked = format!("{}...{}", &key[..8], &key[key.len()-4..]);
12            println!("🔑 OpenAI API Key: {}", masked);
13        }
14        Err(_) => {
15            println!("❌ 未设置OPENAI_API_KEY");
16            return Ok(());
17        }
18    }
19    
20    // 创建OpenAI客户端
21    println!("\n📡 创建OpenAI客户端...");
22    let client = match AiClient::new(Provider::OpenAI) {
23        Ok(client) => {
24            println!("✅ 客户端创建成功");
25            client
26        }
27        Err(e) => {
28            println!("❌ 客户端创建失败: {}", e);
29            return Ok(());
30        }
31    };
32    
33    // 测试模型列表
34    println!("\n📋 获取模型列表...");
35    match client.list_models().await {
36        Ok(models) => {
37            println!("✅ 成功获取 {} 个模型", models.len());
38            
39            // 显示GPT模型
40            let gpt_models: Vec<_> = models.iter()
41                .filter(|m| m.contains("gpt"))
42                .take(5)
43                .collect();
44            println!("   GPT模型: {:?}", gpt_models);
45        }
46        Err(e) => {
47            println!("❌ 获取模型列表失败: {}", e);
48            return Ok(());
49        }
50    }
51    
52    // 测试聊天完成
53    println!("\n💬 测试聊天完成...");
54    let request = ChatCompletionRequest::new(
55        "gpt-3.5-turbo".to_string(),
56        vec![Message {
57            role: Role::User,
58            content: "Say 'Hello from OpenAI!' in exactly those words.".to_string(),
59        }],
60    ).with_max_tokens(20)
61     .with_temperature(0.0);  // 使用0温度确保一致性
62    
63    match client.chat_completion(request).await {
64        Ok(response) => {
65            println!("✅ 聊天完成成功!");
66            println!("   模型: {}", response.model);
67            println!("   响应: '{}'", response.choices[0].message.content);
68            println!("   Token使用: {} (prompt: {}, completion: {})", 
69                response.usage.total_tokens,
70                response.usage.prompt_tokens,
71                response.usage.completion_tokens
72            );
73            println!("   完成原因: {:?}", response.choices[0].finish_reason);
74        }
75        Err(e) => {
76            println!("❌ 聊天完成失败: {}", e);
77            
78            // 分析错误类型
79            let error_str = e.to_string();
80            if error_str.contains("400") {
81                println!("   → 这是请求格式错误");
82            } else if error_str.contains("401") {
83                println!("   → 这是认证错误,检查API密钥");
84            } else if error_str.contains("429") {
85                println!("   → 这是速率限制错误");
86            } else if error_str.contains("500") {
87                println!("   → 这是服务器错误");
88            }
89        }
90    }
91    
92    println!("\n🎯 OpenAI测试完成!");
93    
94    Ok(())
95}