Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Tools/langtool/src/chatgpt.rs
3658 views
1
use anyhow::Context;
2
use serde::{Deserialize, Serialize};
3
use std::{error::Error, time::Duration};
4
5
#[derive(Serialize)]
6
pub struct ChatRequest<'a> {
7
pub model: &'a str,
8
pub messages: Vec<Message<'a>>,
9
}
10
11
#[derive(Serialize)]
12
pub struct Message<'a> {
13
pub role: &'a str,
14
pub content: &'a str,
15
}
16
17
#[derive(Deserialize)]
18
pub struct ChatResponse {
19
pub choices: Vec<Choice>,
20
}
21
22
#[derive(Deserialize)]
23
pub struct Choice {
24
pub message: MessageResponse,
25
}
26
27
#[allow(dead_code)]
28
#[derive(Deserialize)]
29
pub struct MessageResponse {
30
pub content: String,
31
pub role: String, // unused
32
}
33
34
pub struct ChatGPT {
35
api_key: String,
36
model: String,
37
}
38
39
impl ChatGPT {
40
pub fn new(api_key: String, model: String) -> Self {
41
ChatGPT { api_key, model }
42
}
43
44
pub fn chat(&self, request: &str) -> Result<String, Box<dyn Error>> {
45
let client = reqwest::blocking::Client::builder()
46
.timeout(Duration::from_secs(300))
47
.build()?;
48
49
let req_body = ChatRequest {
50
model: &self.model,
51
messages: vec![Message {
52
role: "user",
53
content: request,
54
}],
55
};
56
57
let res: ChatResponse = client
58
.post("https://api.openai.com/v1/chat/completions")
59
.bearer_auth(&self.api_key)
60
.json(&req_body)
61
.send()
62
.context("response")?
63
.json()
64
.context("json")?;
65
66
Ok(res.choices[0].message.content.clone())
67
}
68
}
69
70