-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
42 lines (36 loc) · 1.23 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
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
// Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY';
// Endpoint for ChatGPT response
app.post('/chatgpt-response', async (req, res) => {
try {
const { query } = req.body;
const response = await axios.post(
'https://api.openai.com/v1/completions',
{
model: 'text-davinci-003', // Or other models like 'gpt-3.5-turbo'
prompt: query,
max_tokens: 100
},
{
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
const answer = response.data.choices[0].text;
res.json({ response: answer });
} catch (error) {
console.error('Error fetching ChatGPT response:', error);
res.status(500).json({ error: 'Error fetching response' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});