1use reqwest::Client;
2use serde_json::json;
3use crate::client::get_api_key;
4
5#[derive(Debug)]
6pub enum OpenAIError {
7 MissingApiKey,
8 RequestError(reqwest::Error),
9 InvalidResponse,
10}
11
12impl From<reqwest::Error> for OpenAIError {
13 fn from(err: reqwest::Error) -> Self {
14 OpenAIError::RequestError(err)
15 }
16}
17
18pub async fn openai_chat_with_model(prompt: &str, model: &str) -> Result<String, OpenAIError> {
20 let api_key = get_api_key().ok_or(OpenAIError::MissingApiKey)?;
21
22 let client = Client::new();
23 let response = client
24 .post("https://api.openai.com/v1/chat/completions")
25 .bearer_auth(api_key)
26 .json(&json!({
27 "model": model,
28 "messages": [
29 {
30 "role": "user",
31 "content": prompt
32 }
33 ]
34 }))
35 .send()
36 .await?;
37
38 let json: serde_json::Value = response.json().await?;
39 if let Some(content) = json["choices"][0]["message"]["content"].as_str() {
40 Ok(content.to_string())
41 } else {
42 Err(OpenAIError::InvalidResponse)
43 }
44}
45
46pub async fn openai_chat(prompt: &str) -> Result<String, OpenAIError> {
48 openai_chat_with_model(prompt, "gpt-3.5-turbo").await
49}