Can't use GPT for fixing my API issue

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
const response = await openai.chat.completions.create({
  model: "gpt-3.5-turbo",

Oh I changed these lines and now I get a 429

“Error with OpenAI API: RateLimitError: 429”

Is that a good sign?! :smiley:

1 Like

Looks like a good start! Did you get it to work?

Sometimes you have to include the necessary documentation to get your code running, and sometimes GPT gets it wrong - but you should get better at working with this tool over time as long as you stick with it!

Thanks Diet! For reaching out.

I received the 429 afterwards – but this was only because I used a backup of my project in which was the old deprecated API Key used … (just for the records if anyone else ever has the issue :smiley: *stupid)

Now I get this message in the Console:
“DropField.js:72 Error: SyntaxError: Unexpected end of JSON input”

Not sure how to handle this …

perfect time to learn how to use the debugger! what’s the json input?

Success!! I made it work at 3:33 am :smiley: :muscle:

Now I need to go with the next features

1 Like