Hi friends,
I created a basic code via chatgpt. My problem is – the hints I receive from ChatGPT are not working because ChatGPT Version is older than the SDK so the hints I get don’t work.
Could anyone help me and let me know what I need to change in my code?
const path = require('path');
const fs = require('fs');
require('dotenv').config({ path: path.resolve(__dirname, './.env') });
const express = require('express');
const multer = require('multer');
const pdf = require('pdf-parse');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3001;
// Initialize OpenAI API
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '../client/build')));
const uploadDir = path.join(__dirname, 'uploads');
fs.existsSync(uploadDir) || fs.mkdirSync(uploadDir);
let storedPdfText = ""; // Variable to store the extracted text from the PDF
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadDir);
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
},
});
const upload = multer({ storage: storage });
app.post('/uploads', upload.single('file'), async (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
try {
const pdfData = fs.readFileSync(req.file.path);
const data = await pdf(pdfData);
storedPdfText = data.text; // Store the extracted text
res.status(200).send(storedPdfText);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Error while extracting text from the PDF.');
}
});
app.post('/chatgpt', async (req, res) => {
try {
const userPrompt = req.body.prompt;
const combinedContent = storedPdfText + "\n" + userPrompt; // Combine the PDF text with the user's prompt
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: combinedContent }
],
});
res.json(response.data);
} catch (error) {
console.error('Error with OpenAI API:', error);
res.status(500).send('Error while interacting with OpenAI API.');
}
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build', 'index.html'));
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
type or paste code here