br_openai/chat.rs
1use br_http::Http;
2use json::{JsonValue, object};
3use crate::{OpenAi};
4
5const URL: &str = "https://api.openai.com/v1/chat/completions";
6
7/// 聊天
8#[derive(Clone, Debug)]
9pub struct Chat {
10 base: OpenAi,
11}
12
13impl Chat {
14 pub fn new(open_ai: OpenAi) -> Chat {
15 Self {
16 base: open_ai,
17 }
18 }
19 /// 请求
20 pub fn request(&mut self, mut history: JsonValue, prompt: &str, _file: &str) -> Result<JsonValue, String> {
21 history.push(object! {"role": "user","content": prompt}).expect("TODO: panic message");
22
23 let json_data = object! {
24 "model":self.base.model.clone(),
25 "messages":history
26 };
27 match Http::new()
28 .post(URL)
29 .raw_json(json_data)
30 .bearer_auth(self.base.token.as_str())
31 .header("Content-Type", "application/json")
32 .json() {
33 Ok(e) => Ok(e),
34 Err(e) => Err(e)
35 }
36 }
37}
38
39// /// 请求
40// #[derive(Debug)]
41// pub struct Request {
42// model: String,
43// messages: Vec<JsonValue>,
44// temperature: usize,
45// }
46//
47// impl Request {
48// pub fn set_message(&mut self, role: Role, content: &str) {
49// self.messages.push(object! {
50// "role":role.info(),
51// "content":content
52// })
53// }
54// }
55
56// /// 角色
57// pub enum Role {
58// System,
59// User,
60// }
61//
62// impl Role {
63// pub fn info(self) -> &'static str {
64// match self {
65// Role::System => "system",
66// Role::User => "user"
67// }
68// }
69// }