fache 0.1.351

发车工具箱
Documentation
use reqwest::Client;
use std::time::Duration;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct YuanQi {
    pub appid: String,
    pub app_key: String,
    pub timeout: Option<u64>,
    pub timeout_connect: Option<u64>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ImageUrl {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MessageContent {
    pub r#type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_url: Option<ImageUrl>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Message {
    pub role: String,
    pub content: Vec<MessageContent>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ChatRequest {
    pub assistant_id: String,
    pub user_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chat_type: Option<String>,
    pub messages: Vec<Message>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_variables: Option<String>,
}
impl YuanQi {
    pub async fn call_yuanqi_api(
        &self,
        e: ChatRequest,
    ) -> Result<super::retype::YuanQiReResp, crate::json::Value> {
        // println!("打印密钥app_key信息{:#?}", e.assistanTid);
        let client = Client::builder()
            .timeout(Duration::from_secs(self.timeout.unwrap_or(30))) // 设置默认30秒总超时
            .connect_timeout(Duration::from_secs(self.timeout_connect.unwrap_or(10))) // 默认连接超时10秒
            .build()
            .expect("创建HTTP客户端失败");
        let response = client
            .post("https://yuanqi.tencent.com/openapi/v1/agent/chat/completions")
            .header("Content-Type", "application/json")
            .header("Authorization", format!("Bearer {}", self.app_key.trim()))
            .json(&e)
            .send()
            .await
            .expect("发送失败");
        if response.status().is_success() {
            let chat_response = response
                .json::<super::retype::YuanQiReResp>()
                .await
                .expect("解析失败");
            // println!("响应的结果信息{:#?}", chat_response);
            Ok(chat_response)
        } else {
            let error_text = response
                .json::<crate::json::Value>()
                .await
                .expect("响应失败");
            Err(error_text)
        }
    }
}