-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (55 loc) · 1.97 KB
/
index.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
67
const express = require('express');
const fs = require('fs');
require('dotenv').config();
const dotenv = require('dotenv');
const path = require('path');
const openai = require('openai');
const app = express();
const port = 3000;
const HTML_FILE_PATH = path.join('public', 'index.html');
dotenv.config({ path: path.join(__dirname, 'env', '.env') });
// Read the API key from environment variables
app.use(express.static(path.join(__dirname, 'public')));
const openaiApiKey = process.env.OPENAI_API_KEY;
if (!openaiApiKey) {
console.error('OpenAI API key not found in environment variables.');
return;
}
// Read the HTML file
fs.readFile(HTML_FILE_PATH, 'utf8', (err, htmlContent) => {
if (err) {
console.error('Error reading HTML file:', err);
return;
}
// Replace placeholder with the OpenAI API key in the HTML content
const updatedHtmlContent = htmlContent.replace('{{OPENAI_API_KEY}}', openaiApiKey.trim());
// Write the updated HTML content back to the file
fs.writeFile(HTML_FILE_PATH, updatedHtmlContent, 'utf8', err => {
if (err) {
console.error('Error writing updated HTML file:', err);
return;
}
console.log('OpenAI API key injected into HTML file successfully.');
});
});
// Set up OpenAI API client
const ai = new openai.OpenAI(openaiApiKey);
// Endpoint to generate responses using ChatGPT
app.post('/generate-response', express.json(), (req, res) => {
const { prompt } = req.body;
// Use the OpenAI API to generate a response
ai.chat.completions.create({
prompt,
model: "gpt-3.5-turbo",
})
.then(response => {
res.json({ response: response.data.choices[0].text.trim() });
})
.catch(error => {
console.error('Error generating response:', error);
res.status(500).json({ error: 'An error occurred while generating the response.' });
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});