|
| 1 | +use reqwest::Client; |
| 2 | +use serde::{Deserialize, Serialize}; |
| 3 | +use std::env; |
| 4 | +use std::error::Error; |
| 5 | + |
| 6 | +#[derive(Debug, Serialize)] |
| 7 | +struct GeminiRequest { |
| 8 | + contents: Vec<Content>, |
| 9 | +} |
| 10 | + |
| 11 | +#[derive(Debug, Serialize, Deserialize)] // Added Deserialize for request and response |
| 12 | +struct Content { |
| 13 | + parts: Vec<Part>, |
| 14 | +} |
| 15 | + |
| 16 | +#[derive(Debug, Serialize, Deserialize)] // Added Deserialize for request and response |
| 17 | +struct Part { |
| 18 | + text: String, |
| 19 | +} |
| 20 | + |
| 21 | +#[derive(Debug, Deserialize)] |
| 22 | +struct GeminiResponse { |
| 23 | + candidates: Vec<Candidate>, |
| 24 | +} |
| 25 | + |
| 26 | +#[derive(Debug, Deserialize)] |
| 27 | +struct Candidate { |
| 28 | + content: Content, |
| 29 | +} |
| 30 | + |
| 31 | +/// Sends a query to Gemini AI and returns the response. |
| 32 | +/// |
| 33 | +/// # Arguments |
| 34 | +/// * `prompt` - The prompt string to send to Gemini. |
| 35 | +/// |
| 36 | +/// # Returns |
| 37 | +/// A `Result` containing the response string, or an error if the request fails. |
| 38 | +pub async fn query_gemini(prompt: &str) -> Result<String, Box<dyn Error>> { |
| 39 | + // Retrieve the API key from the environment |
| 40 | + let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY must be set"); |
| 41 | + |
| 42 | + // API URL |
| 43 | + let base_url = format!( |
| 44 | + "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key={}", |
| 45 | + api_key |
| 46 | + ); |
| 47 | + |
| 48 | + // Prepare the request body |
| 49 | + let request_body = GeminiRequest { |
| 50 | + contents: vec![Content { |
| 51 | + parts: vec![Part { |
| 52 | + text: prompt.to_string(), |
| 53 | + }], |
| 54 | + }], |
| 55 | + }; |
| 56 | + |
| 57 | + // Initialize HTTP client |
| 58 | + let client = Client::new(); |
| 59 | + |
| 60 | + // Send the request |
| 61 | + let response = client |
| 62 | + .post(&base_url) |
| 63 | + .header("Content-Type", "application/json") |
| 64 | + .json(&request_body) |
| 65 | + .send() |
| 66 | + .await?; |
| 67 | + |
| 68 | + // Extract status and response text for debugging |
| 69 | + let status = response.status(); |
| 70 | + let response_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string()); |
| 71 | + |
| 72 | + if status.is_success() { |
| 73 | + // eprintln!("Successful response: {}", response_text); // Debugging raw response |
| 74 | + // Parse the response JSON |
| 75 | + let response_body: GeminiResponse = serde_json::from_str(&response_text)?; |
| 76 | + |
| 77 | + // Extract and concatenate text from the candidate's content parts |
| 78 | + let output = response_body |
| 79 | + .candidates |
| 80 | + .into_iter() |
| 81 | + .flat_map(|candidate| candidate.content.parts) |
| 82 | + .map(|part| part.text) |
| 83 | + .collect::<Vec<String>>() |
| 84 | + .join("\n"); |
| 85 | + |
| 86 | + Ok(output) |
| 87 | + } else { |
| 88 | + eprintln!("Failed response: {}", response_text); // Debugging raw error response |
| 89 | + Err(Box::new(std::io::Error::new( |
| 90 | + std::io::ErrorKind::Other, |
| 91 | + format!("Request failed with status: {} - {}", status, response_text), |
| 92 | + ))) |
| 93 | + } |
| 94 | +} |
0 commit comments