import { GoogleGenerativeAI } from "@google/generative-ai"; const GEMINI_API_KEY = process.env.GEMINI_API_KEY; if (!GEMINI_API_KEY) { console.error("[Gemini] GEMINI_API_KEY environment variable is not set."); throw new Error("GEMINI_API_KEY environment variable is not set."); } const genAI = new GoogleGenerativeAI(GEMINI_API_KEY); export async function isSpamWithGemini(message: string): Promise { try { console.log('[Gemini] Attempting spam check...'); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const prompt = `Is the following message spam? Reply with only 'yes' or 'no'.\n\nMessage:\n${message}`; const result = await model.generateContent(prompt); const response = result.response.text().trim().toLowerCase(); console.log(`[Gemini] Spam check result: ${response}`); return response.startsWith("yes"); } catch (err: any) { if (err?.response?.status === 401) { console.error('[Gemini] API key expired or invalid.'); } else if (err?.code === 'ENOTFOUND' || err?.code === 'ECONNREFUSED') { console.error('[Gemini] Service not reachable:', err.message); } else { console.error('[Gemini] Error during spam check:', err); } // Fail open: if Gemini is not reachable, do not block the message as spam return false; } }