Enhance Gemini spam check functionality with improved error handling and logging

- Added detailed logging for spam check attempts and results to aid in debugging.
- Implemented error handling for API key issues and service unavailability, ensuring the system fails open by returning false if Gemini is unreachable.
- Maintained existing spam detection logic while enhancing robustness and user feedback during the process.
This commit is contained in:
becarta
2025-06-12 23:54:36 +02:00
parent 954eaddc81
commit 16fec9166a

View File

@@ -2,14 +2,29 @@ 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<boolean> {
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();
return response.startsWith("yes");
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;
}
}