-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
66 lines (54 loc) · 1.98 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import fetch from 'node-fetch';
import { config } from 'dotenv';
config();
// Setup __filename and __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3000;
// Replace with your OpenAI API key
const apiKey = process.env.API_KEY;
// Serve static files from the public directory
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
// Handle the /api/chat endpoint
app.post('/api/chat', async (req, res) => {
const messages = req.body.messages;
const data = {
model: 'gpt-4',
messages: messages,
max_tokens: 1024
};
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const responseData = await response.json();
// Check for errors in the response
if (responseData.error) {
console.error('API Error:', responseData.error.message);
return res.status(500).json({ error: responseData.error.message });
}
// Ensure choices are present
if (responseData.choices && responseData.choices[0] && responseData.choices[0].message) {
return res.json({ message: responseData.choices[0].message.content });
} else {
console.error('Unexpected API response structure:', responseData);
return res.status(500).json({ error: 'Unexpected API response structure' });
}
} catch (error) {
console.error('Fetch Error:', error);
return res.status(500).json({ error: 'Fetch Error' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});