// netlify/functions/groq-proxy.js
// This serverless function securely forwards requests to Groq API
exports.handler = async (event) => {
// Only allow POST requests
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method Not Allowed' };
}
try {
const { question, apiKey, detailed, chapter } = JSON.parse(event.body);
if (!question || !apiKey) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Missing question or API key' })
};
}
// Build the system prompt based on mode and chapter
let systemPrompt = `You are MUTEC Math AI Tutor, an official educational product from MUTEC Company for Ugandan O-Level students (NCDC Curriculum, S1-S4).`;
if (detailed) {
systemPrompt += ` Solve the math problem step by step with clear explanations. Include motivation and real-world applications. Be friendly and encouraging.`;
} else {
systemPrompt += ` Give only the final answer, keep it brief.`;
}
if (chapter && chapter !== 'all') {
systemPrompt += ` The student is currently studying the ${chapter} chapter. Focus your explanation on ${chapter} concepts.`;
}
const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'llama-3.3-70b-versatile',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: question }
],
temperature: 0.7,
max_tokens: 1000
})
});
const data = await response.json();
if (!response.ok) {
return {
statusCode: response.status,
body: JSON.stringify({ error: data.error?.message || 'Groq API error' })
};
}
const answer = data.choices[0].message.content;
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ answer })
};
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({ error: err.message })
};
}
};