| import express from 'express'; |
| import fetch from 'node-fetch'; |
| import cors from 'cors'; |
| import rateLimit from 'express-rate-limit'; |
| import dotenv from 'dotenv'; |
|
|
| dotenv.config(); |
|
|
| const app = express(); |
| app.use(cors()); |
| app.use(express.json({ limit: '1mb' })); |
|
|
| const limiter = rateLimit({ windowMs: 60*1000, max: 60 }); |
| app.use(limiter); |
|
|
| const OPENAI_KEY = process.env.OPENAI_API_KEY; |
| if(!OPENAI_KEY) console.warn('OPENAI_API_KEY not set in environment.'); |
|
|
| app.post('/api/ask', async (req, res) => { |
| try { |
| const { prompt, system, model } = req.body; |
| if(!prompt) return res.status(400).json({ ok:false, error: 'missing prompt' }); |
| const messages = [ |
| { role: 'system', content: system || 'You are a senior marketing expert with 20 years experience. Provide concise, tactical advice.' }, |
| { role: 'user', content: prompt } |
| ]; |
| const payload = { model: model || 'gpt-4o-mini', messages, max_tokens: 900, temperature: 0.2 }; |
| const r = await fetch('https://api.openai.com/v1/chat/completions', { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + OPENAI_KEY }, |
| body: JSON.stringify(payload) |
| }); |
| if(!r.ok) { |
| const text = await r.text(); |
| return res.status(502).json({ ok:false, error: 'OpenAI error', detail: text }); |
| } |
| const data = await r.json(); |
| const answer = data.choices && data.choices[0] && data.choices[0].message ? data.choices[0].message.content : JSON.stringify(data); |
| res.json({ ok:true, answer }); |
| } catch(err) { |
| console.error(err); |
| res.status(500).json({ ok:false, error: String(err) }); |
| } |
| }); |
|
|
| app.get('/', (req, res) => res.send('AI proxy running')); |
|
|
| const PORT = process.env.PORT || 5174; |
| app.listen(PORT, () => console.log('Server listening on', PORT)); |
|
|