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