1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#![doc = include_str!("../README.md")]
use reqwest;
use lazy_static::lazy_static;
use anyhow::{anyhow, Result};
lazy_static! {
static ref BASE_URL: reqwest::Url = reqwest::Url::parse("https://api.openai.com/v1/models").unwrap();
}
pub struct Client {
req_client: reqwest::Client,
}
pub mod models;
pub mod chat;
impl Client {
pub fn new(api_key: &str) -> Client {
use reqwest::header;
let mut headers = header::HeaderMap::new();
let mut key_headervalue = header::HeaderValue::from_str(&format!("Bearer {api_key}")).unwrap();
key_headervalue.set_sensitive(true);
headers.insert(header::AUTHORIZATION, key_headervalue);
let req_client = reqwest::ClientBuilder::new().default_headers(headers).build().unwrap();
Client {
req_client,
}
}
pub async fn list_models(&self) -> Result<models::ListModelsResponse, anyhow::Error> {
let mut url = BASE_URL.clone();
url.set_path("/v1/models");
let res = self.req_client.get(url).send().await?;
if res.status() == 200 {
Ok(res.json::<models::ListModelsResponse>().await?)
} else {
Err(anyhow!(res.text().await?))
}
}
pub async fn create_chat(&self, args: chat::ChatArguments) -> Result<chat::ChatResponse, anyhow::Error> {
let mut url = BASE_URL.clone();
url.set_path("/v1/chat/completions");
let res = self.req_client.post(url).json(&args).send().await?;
if res.status() == 200 {
Ok(res.json::<chat::ChatResponse>().await?)
} else {
Err(anyhow!(res.text().await?))
}
}
}