Description
The generateCompetitors function in backend/models/competitorsModel.js is failing due to several issues with the Gemini API integration. The primary issue appears to be an incorrect model version reference.
Current Behavior
- API calls to Gemini are failing
- Function throws errors when attempting to generate competitor analysis
- JSON parsing may fail intermittently
Expected Behavior
- Successfully connect to Gemini API
- Generate competitor analysis based on startup data
- Return properly formatted JSON response
Root Cause Analysis
- Invalid Model Version (Critical)
Issue: Using non-existent model gemini-2.5-flash
// ❌ Current (incorrect)
const MODEL_URL = 'https://generativelanguage.googleapis.com/v1/models/gemini-2.5-flash:generateContent';
// ✅ Should be
const MODEL_URL = 'https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent';
- Insufficient Error Handling (High)
- No validation for empty API responses
- JSON parsing lacks try-catch protection
- Could crash application on malformed responses
- Response Validation Missing (Medium)
- No checks for required response structure
- Assumes AI always returns valid JSON format
Proposed Solution
const generateCompetitors = async (data) => {
const prompt = `...`; // existing prompt
try {
const response = await axios.post(
MODEL_URL + `?key=${GEMINI_API_KEY}`,
{
contents: [{ parts: [{ text: prompt }] }]
},
{
headers: {
'Content-Type': 'application/json'
}
}
);
let rawText = response.data.candidates?.[0]?.content?.parts?.[0]?.text;
// Validate response exists
if (!rawText) {
throw new Error('Empty response from Gemini API');
}
// Clean markdown formatting
rawText = rawText.replace(/```json|```/g, '').trim();
if (!rawText) {
throw new Error('No content after cleaning response');
}
// Safe JSON parsing
try {
const parsedData = JSON.parse(rawText);
// Validate expected structure
if (!parsedData.competitors || !Array.isArray(parsedData.competitors)) {
throw new Error('Invalid response structure from Gemini');
}
return parsedData;
} catch (parseError) {
console.error('JSON parsing failed:', parseError.message);
console.error('Raw response:', rawText);
throw new Error('Failed to parse Gemini response as JSON');
}
} catch (error) {
if (error.response) {
console.error('Gemini API Error:', {
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data
});
} else {
console.error('Gemini Competitors Model Error:', error.message);
}
throw new Error('Failed to generate competitors from Gemini');
}
};
Additional Context
This issue was discovered during code review. The function is currently non-functional due to the incorrect model version, and even if that's fixed, the lack of proper error handling could cause application crashes.
Description
The generateCompetitors function in backend/models/competitorsModel.js is failing due to several issues with the Gemini API integration. The primary issue appears to be an incorrect model version reference.
Current Behavior
Expected Behavior
Root Cause Analysis
Issue: Using non-existent model gemini-2.5-flash
Proposed Solution
const generateCompetitors = async (data) => { const prompt = `...`; // existing prompt try { const response = await axios.post( MODEL_URL + `?key=${GEMINI_API_KEY}`, { contents: [{ parts: [{ text: prompt }] }] }, { headers: { 'Content-Type': 'application/json' } } ); let rawText = response.data.candidates?.[0]?.content?.parts?.[0]?.text; // Validate response exists if (!rawText) { throw new Error('Empty response from Gemini API'); } // Clean markdown formatting rawText = rawText.replace(/```json|```/g, '').trim(); if (!rawText) { throw new Error('No content after cleaning response'); } // Safe JSON parsing try { const parsedData = JSON.parse(rawText); // Validate expected structure if (!parsedData.competitors || !Array.isArray(parsedData.competitors)) { throw new Error('Invalid response structure from Gemini'); } return parsedData; } catch (parseError) { console.error('JSON parsing failed:', parseError.message); console.error('Raw response:', rawText); throw new Error('Failed to parse Gemini response as JSON'); } } catch (error) { if (error.response) { console.error('Gemini API Error:', { status: error.response.status, statusText: error.response.statusText, data: error.response.data }); } else { console.error('Gemini Competitors Model Error:', error.message); } throw new Error('Failed to generate competitors from Gemini'); } };Additional Context
This issue was discovered during code review. The function is currently non-functional due to the incorrect model version, and even if that's fixed, the lack of proper error handling could cause application crashes.