use std::{ env, io::{BufRead, BufReader, Read, Write}, net::TcpStream, }; use dotenv::dotenv; use native_tls::TlsConnector; use serde::{Deserialize, Serialize}; pub fn gemini(content: String, env: &str, model: &str, mime_type: &str) -> String { let env = env::var(env).expect("Env"); let gemini = TlsConnector::new().unwrap(); let stream = TcpStream::connect("generativelanguage.googleapis.com:443").unwrap(); let mut stream = gemini .connect("generativelanguage.googleapis.com", stream) .unwrap(); let models = format!( "POST /v1beta/models/{}:generateContent?key={} HTTP/1.1\r\n\ Host: generativelanguage.googleapis.com\r\n\ Content-Type: {}\r\n\ Content-Length: {}\r\n\r\n{}", model, env, mime_type, content.len(), content ); // println!("{}", models); stream.write_all(models.as_bytes()); stream.flush(); let mut reader = BufReader::new(stream); let mut header = String::new(); loop { let mut line = String::new(); reader.read_line(&mut line); // println!("{}", line); if line == "\r\n" { break; } header.push_str(&line); } let mut body = String::new(); loop { let mut line = String::new(); reader.read_line(&mut line); // println!("{}", line); let size = usize::from_str_radix(&line.trim(), 16).unwrap(); if size == 0 { break; } let mut esponse = vec![0; size]; reader.read_exact(&mut esponse); let response = String::from_utf8_lossy(&esponse); body.push_str(&response); // println!("{}", response); let mut trail = vec![0; 2]; reader.read_exact(&mut trail); } body } #[derive(Serialize, Deserialize, Debug)] pub struct Candidate { pub content: Content, finishReason: String, avgLogprobs: f64, } #[derive(Serialize, Deserialize, Debug)] pub struct Content { pub parts: Vec, } #[derive(Serialize, Deserialize, Debug)] pub struct Part { pub text: String, } #[derive(Serialize, Deserialize, Debug)] pub struct UsageMetadata { promptTokenCount: u32, candidatesTokenCount: u32, totalTokenCount: u32, } #[derive(Serialize, Deserialize, Debug)] pub struct Responses { pub candidates: Vec, usageMetadata: UsageMetadata, modelVersion: String, } pub fn decode_gemini(response: &str) -> Result { let response = serde_json::from_str::(response); response }