if !response.status().is_success() {
let error_text = response.text().await?;
println!(" 请求失败:{}", error_text);
return Ok(());
}
println!(" AI 开始回答:\n");
let mut stream = response.bytes_stream();
let mut full_response = String::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
let text = String::from_utf8_lossy(&chunk);
//解析SSE
for line in text.lines() {
if line.starts_with("data: ") {
let data = &line[6..];
if data.trim() == "[DONE]" {
break;
}
if let Ok(resp) = serde_json::from_str::<StreamResponse>(data) {
if let Some(choice) = resp.choices.first() {
if let Some(content) = &choice.delta.content {
print!("{}", content);
full_response.push_str(content);
use std::io::Write;
std::io::stdout().flush().unwrap();
}
}
}
}
}
}