// api/generate.js — Vercel serverless proxy for Anthropic API // The API key lives in Vercel's environment variables, never in the browser. export default async function handler(req, res) { // Only allow POST if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } // Basic rate-limit guard: reject if no body or missing required fields const { messages, system } = req.body || {}; if (!messages || !Array.isArray(messages) || messages.length === 0) { return res.status(400).json({ error: 'Missing or invalid messages' }); } const apiKey = process.env.ANTHROPIC_API_KEY; if (!apiKey) { console.error('ANTHROPIC_API_KEY not set in environment variables'); return res.status(500).json({ error: 'Server configuration error' }); } try { const anthropicBody = { model: 'claude-sonnet-4-6', max_tokens: 4096, messages: messages, }; // Pass through the system prompt if provided if (system) { anthropicBody.system = system; } const response = await fetch('https://api.anthropic.com/v1/messages', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', }, body: JSON.stringify(anthropicBody), }); const data = await response.json(); if (!response.ok) { console.error('Anthropic API error:', data); return res.status(response.status).json({ error: data.error?.message || 'Anthropic API error', }); } return res.status(200).json(data); } catch (err) { console.error('Proxy error:', err); return res.status(500).json({ error: 'Internal server error' }); } }