| use axum::{extract::State, Json}; |
| use serde_json::json; |
| use std::sync::Arc; |
| use crate::AppState; |
|
|
| pub async fn chat_handler( |
| State(state): State<Arc<AppState>>, |
| Json(payload): Json<serde_json::Value> |
| ) -> Json<serde_json::Value> { |
| let user_msg = payload["message"].as_str().unwrap_or(""); |
| let api_key = std::env::var("GEMINI_API_KEY").expect("Missing GEMINI_API_KEY"); |
|
|
| let client = reqwest::Client::new(); |
| let response = client.post(format!("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key={}", api_key)) |
| .json(&json!({ |
| "contents": [{ "parts": [{ "text": user_msg }] }] |
| })) |
| .send() |
| .await; |
|
|
| if let Ok(res) = response { |
| let body: serde_json::Value = res.json().await.unwrap(); |
| let ai_text = body["candidates"][0]["content"]["parts"][0]["text"].as_str().unwrap_or("Error"); |
| |
| |
| let _ = state.tx.send(json!({"type": "log", "data": ai_text}).to_string()); |
| } |
|
|
| Json(json!({"status": "sent"})) |
| } |