|
| 1 | +use reqwest::Client; |
| 2 | +use serde::{Serialize}; |
| 3 | +use serde_json::Value; |
| 4 | +use std::error::Error; |
| 5 | +use std::fmt; |
| 6 | + |
| 7 | +#[derive(Debug)] |
| 8 | +struct SuggestionError(String); |
| 9 | + |
| 10 | +impl fmt::Display for SuggestionError { |
| 11 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 12 | + write!(f, "{}", self.0) |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +impl Error for SuggestionError {} |
| 17 | + |
| 18 | +#[tokio::main] |
| 19 | +async fn main() -> Result<(), Box<dyn Error>> { |
| 20 | + let review = review_text().await?; |
| 21 | + println!("{}", review); |
| 22 | + |
| 23 | + Ok(()) |
| 24 | +} |
| 25 | + |
| 26 | +#[derive(Serialize)] |
| 27 | +struct Prompt { |
| 28 | + prompt: String, |
| 29 | + max_tokens: u32, |
| 30 | +} |
| 31 | + |
| 32 | +// Review text for potentially discriminatory language |
| 33 | +async fn review_text() -> Result<String, Box<dyn Error>> { |
| 34 | + // Get the path to the markdown file from the command line |
| 35 | + let args: Vec<String> = std::env::args().collect(); |
| 36 | + // Check that the user provided a path to a markdown file |
| 37 | + if args.len() != 2 { |
| 38 | + println!("Usage: {} <path_to_markdown_file>", args[0]); |
| 39 | + std::process::exit(1); |
| 40 | + } |
| 41 | + // Read the markdown file |
| 42 | + let file_path = &args[1]; |
| 43 | + let text = std::fs::read_to_string(file_path)?; |
| 44 | + // Get the OpenAI API key from the environment |
| 45 | + let api_key = std::env::var("OPENAI_API_KEY")?; |
| 46 | + // Call the OpenAI API |
| 47 | + let review = call_openai_api(&api_key, &text, "https://api.openai.com").await?; |
| 48 | + println!("{}", review); |
| 49 | + |
| 50 | + Ok(review) |
| 51 | +} |
| 52 | + |
| 53 | +async fn call_openai_api(api_key: &str, text: &str, base_url: &str) -> Result<String, Box<dyn Error>> { |
| 54 | + // Create a new HTTP client |
| 55 | + let client = Client::new(); |
| 56 | + // Define the prompt text |
| 57 | + let prompt = format!( |
| 58 | + "Review the following text for potentially discriminatory language, including but not limited to ableism, ageism, racism, antisemitism, islamophobia, and likewise: {}", |
| 59 | + text |
| 60 | + ); |
| 61 | + |
| 62 | + // Define the request body with the model parameter and prompt text |
| 63 | + let request_body = serde_json::json!({ |
| 64 | + "model": "gpt-3.5-turbo", |
| 65 | + "messages": [{"role": "user", "content": prompt}], |
| 66 | + "max_tokens": 100 |
| 67 | + }); |
| 68 | + |
| 69 | + // Send the request to the OpenAI API |
| 70 | + let response = client |
| 71 | + .post(&format!("{}/v1/chat/completions", base_url)) |
| 72 | + .header("Authorization", format!("Bearer {}", api_key)) |
| 73 | + .json(&request_body) |
| 74 | + .send() |
| 75 | + .await? |
| 76 | + .json::<Value>() |
| 77 | + .await?; |
| 78 | + |
| 79 | + // Extract the suggestion from the response |
| 80 | + let choices = response["choices"].as_array().ok_or(SuggestionError("Missing choices field".to_string()))?; |
| 81 | + let suggestion = choices |
| 82 | + .get(0) |
| 83 | + .and_then(|choice| choice["message"]["content"].as_str()) // Updated path to extract content |
| 84 | + .ok_or(SuggestionError("Missing suggestion text".to_string()))? |
| 85 | + .trim() |
| 86 | + .to_owned(); |
| 87 | + |
| 88 | + Ok(suggestion) |
| 89 | +} |
| 90 | + |
| 91 | +#[cfg(test)] |
| 92 | +mod tests { |
| 93 | + use super::call_openai_api; |
| 94 | + use mockito::{mock, server_url}; |
| 95 | + |
| 96 | + #[tokio::test] |
| 97 | + async fn test_review_without_discriminatory_language() { |
| 98 | + let _m = mock("POST", "/v1/chat/completions") |
| 99 | + .with_status(200) |
| 100 | + .with_body(r#"{ |
| 101 | + "choices": [ |
| 102 | + { |
| 103 | + "finish_reason": "stop", |
| 104 | + "index": 0, |
| 105 | + "message": { |
| 106 | + "content": "There does not appear to be any discriminatory language in this text.", |
| 107 | + "role": "assistant" |
| 108 | + } |
| 109 | + } |
| 110 | + ] |
| 111 | + }"#) |
| 112 | + .create(); |
| 113 | + |
| 114 | + let api_key = "fake_api_key"; |
| 115 | + let text = "This is a normal sentence without any discriminatory language."; |
| 116 | + let review = call_openai_api(api_key, text, &server_url()).await.expect("API call failed"); |
| 117 | + assert_eq!(review, "There does not appear to be any discriminatory language in this text."); |
| 118 | + } |
| 119 | + |
| 120 | + #[tokio::test] |
| 121 | + async fn test_review_with_discriminatory_language() { |
| 122 | + let _m = mock("POST", "/v1/chat/completions") |
| 123 | + .with_status(200) |
| 124 | + .with_body(r#"{ |
| 125 | + "choices": [ |
| 126 | + { |
| 127 | + "finish_reason": "stop", |
| 128 | + "index": 0, |
| 129 | + "message": { |
| 130 | + "content": "The text contains discriminatory language. Suggested alternative: newcomers", |
| 131 | + "role": "assistant" |
| 132 | + } |
| 133 | + } |
| 134 | + ] |
| 135 | + }"#) |
| 136 | + .create(); |
| 137 | + |
| 138 | + let api_key = "fake_api_key"; |
| 139 | + let text = "This is an example sentence with discriminatory language: stupid beginners"; |
| 140 | + let review = call_openai_api(api_key, text, &server_url()).await.expect("API call failed"); |
| 141 | + let expected_result = "The text contains discriminatory language. Suggested alternative: newcomers"; |
| 142 | + assert_eq!(review, expected_result); |
| 143 | + } |
| 144 | +} |
| 145 | + |
0 commit comments