extern crate reqwest;
extern crate serde;
extern crate serde_json;
extern crate serde_derive;
use serde::{Deserialize, Serialize};
use serde_derive::{Deserialize, Serialize};
use reqwest::blocking::Client;
use std::thread::sleep;
use std::time::Duration;
#[derive(Debug, Serialize, Deserialize)]
struct RequestData {
inputs: serde_json::Value,
query: String,
response_mode: String,
conversation_id: String,
user: String,
}
#[derive(Debug, Deserialize)]
struct ApiResponse {
// 根据API的响应结构来定义字段
event: String,
task_id: String,
id: String,
answer: String,
created_at: i64,
conversation_id: String,
}
fn main() {
let client = Client::new();
let data = RequestData {
inputs: serde_json::Value::Object(serde_json::Map::new()),
query: "世界上面积最大的国家是哪个国家?".to_string(),
response_mode: "streaming".to_string(),
conversation_id: "".to_string(),
user: "abc-123".to_string(),
};
let response = client.post("https://api.dify.ai/v1/chat-messages")
.header("Authorization", "Bearer app-ymZW0myntxVFDd5VYIW0FGFd")
.header("Content-Type", "application/json")
.json(&data)
.send()
.expect("Failed to send request");
if response.status().is_success() {
let content = response.text().expect("Failed to read response body");
// Split the content by newlines
for line in content.lines() {
if line.starts_with("data:") {
// Deserialize the line to get the `answer` field
let api_response: ApiResponse = serde_json::from_str(&line[5..]).expect("Failed to deserialize line");
// Print the answer character by character
for ch in api_response.answer.chars() {
print!("{}", ch);
sleep(Duration::from_millis(100)); // Adjust this for desired speed
}
println!(); // Newline after each answer
}
}
} else {
println!("Error: {}", response.status());
if let Ok(err_body) = response.text() {
println!("Error details: {}", err_body);
}
}
}