use crate::models::*;
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
use serde_json;
pub async fn make_api_request(
client: &reqwest::Client,
api_url: &str,
access_token: &str,
request_body: &str,
) -> Result<reqwest::Response, Box<dyn std::error::Error>> {
Ok(client
.post(api_url)
.header(CONTENT_TYPE, "application/json")
.header(AUTHORIZATION, format!("Bearer {}", access_token))
.body(request_body.to_string())
.send()
.await?)
}
pub fn process_response_chunks(responses: Vec<StreamResponse>) -> String {
let mut final_text = String::new();
for response_chunk in responses {
if let Some(candidates) = response_chunk.candidates {
if let Some(candidate) = candidates.first() {
if let Some(part) = candidate.content.parts.first() {
final_text.push_str(&part.text);
}
}
}
}
final_text
}
pub fn parse_final_response(final_text: &str) -> Result<String, Box<dyn std::error::Error>> {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(final_text) {
if let Some(response_str) = response_json.get("response").and_then(|v| v.as_str()) {
Ok(format!("\nGenerated Python Code:\n{}", response_str))
} else {
Ok(format!("\nRaw Combined Response:\n{}", final_text))
}
} else {
Ok(format!(
"\nCouldn't parse combined response as JSON:\n{}",
final_text
))
}
}