Skip to content

Commit

Permalink
Fix #2: Print more information on failed requests (#20)
Browse files Browse the repository at this point in the history
* Fix #2: Print more information on failed requests

* cs

Co-authored-by: Miguel Piedrafita <[email protected]>
  • Loading branch information
soerface and m1guelpf authored Jan 19, 2023
1 parent 540a014 commit e9551cb
Showing 1 changed file with 33 additions and 21 deletions.
54 changes: 33 additions & 21 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,6 @@ fn main() {
let client = Client::new();
let mut spinner = Spinner::new(Spinners::BouncingBar, "Generating your command...".into());

let os_hint = if cfg!(target_os = "macos") {
" (on macOS)"
} else if cfg!(target_os = "linux") {
" (on Linux)"
} else {
""
};

let response = client
.post("https://api.openai.com/v1/completions")
.json(&json!({
Expand All @@ -49,21 +41,30 @@ fn main() {
"presence_penalty": 0,
"frequency_penalty": 0,
"model": "text-davinci-003",
"prompt": format!("{}{}:\n```bash\n#!/bin/bash\n", cli.prompt.join(" "), os_hint),
"prompt": build_prompt(&cli.prompt.join(" ")),
}))
.header("Authorization", format!("Bearer {}", config.api_key))
.send()
.unwrap()
.error_for_status()
.unwrap_or_else(|_| {
spinner.stop_and_persist(
"✖".red().to_string().as_str(),
"Failed to get a response. Have you set the OPENAI_API_KEY variable?"
.red()
.to_string(),
);
std::process::exit(1);
});
.unwrap();

let status_code = response.status();
if status_code.is_client_error() {
let response_body = response.json::<serde_json::Value>().unwrap();
let error_message = response_body["error"]["message"].as_str().unwrap();
spinner.stop_and_persist(
"✖".red().to_string().as_str(),
format!("API error: \"{error_message}\"").red().to_string(),
);
std::process::exit(1);
} else if status_code.is_server_error() {
spinner.stop_and_persist(
"✖".red().to_string().as_str(),
format!("OpenAI is currently experiencing problems. Status code: {status_code}")
.red()
.to_string(),
);
std::process::exit(1);
}

let code = response.json::<serde_json::Value>().unwrap()["choices"][0]["text"]
.as_str()
Expand Down Expand Up @@ -104,7 +105,6 @@ fn main() {
config.write_to_history(code.as_str());
spinner = Spinner::new(Spinners::BouncingBar, "Executing...".into());

// run command and print output and error
let output = Command::new("bash")
.arg("-c")
.arg(code.as_str())
Expand Down Expand Up @@ -134,3 +134,15 @@ fn main() {
println!("{}", String::from_utf8_lossy(&output.stdout));
}
}

fn build_prompt(prompt: &str) -> String {
let os_hint = if cfg!(target_os = "macos") {
" (on macOS)"
} else if cfg!(target_os = "linux") {
" (on Linux)"
} else {
""
};

format!("{prompt}{os_hint}:\n```bash\n#!/bin/bash\n")
}

0 comments on commit e9551cb

Please sign in to comment.