Skip to content

Commit

Permalink
feat: add chatgpt request, response and send demo.
Browse files Browse the repository at this point in the history
  • Loading branch information
wangjiahan committed May 15, 2024
1 parent 63e6365 commit 2df3015
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
67 changes: 67 additions & 0 deletions src/chatgpt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize)]
pub struct Req {
model: String,
messages: Vec<Message>,
}

#[derive(Debug, Deserialize, Default)]
pub struct Resp {
pub id: String,
pub object: String,
pub created: i64,
pub model: String,
pub choices: Vec<Choice>,
}

#[derive(Debug, Deserialize, Default)]
pub struct Choice {
pub index: i64,
pub message: Message,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Message {
pub role: String,
pub content: String,
}

impl Req {
pub fn new(model: impl Into<String>, message: impl Into<String>) -> Self {
Self {
model: model.into(),
messages: vec![Message {
role: "user".into(),
content: message.into(),
}],
}
}
}

pub async fn send_request(req: &Req, key: impl Into<String>) -> Result<Resp, anyhow::Error> {
let client = reqwest::Client::new();
let resp: Resp = client
.post("https://api.openai.com/v1/chat/completions")
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", key.into()))
.json(req)
.send()
.await?
.json()
.await?;
Ok(resp)
}

// #[cfg(test)]
// mod tests {

// use super::*;

// #[tokio::test]
// async fn test_send_request() -> anyhow::Result<()> {
// let resp = send_request(&Req::new("gpt-3.5-turbo", "什么是Rust?"), "xxx").await?;
// println!("{:?}", resp.choices[0].message.content);
// Ok(())
// }
// }
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use regex::Regex;

pub mod chatgpt;
pub mod conf;
pub mod cron_task;
pub mod feishu_bot;
Expand Down

0 comments on commit 2df3015

Please sign in to comment.