Running into issues calling the API and I am still learning here… The error I’m getting is (carat is under “new”)
const openai = new OpenAIApi({ apiKey: process.env.OPENAI_API_KEY });
^
TypeError: OpenAIApi is not a constructor
at Object. (C:\Users\pdavis\roleplay\rpbe\server.js:8:16)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions…js (node:internal/modules/cjs/loader:1435:10)
at Module.load (node:internal/modules/cjs/loader:1207:32)
at Module._load (node:internal/modules/cjs/loader:1023:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
at node:internal/main/run_main_module:28:49
My code is…
const express = require(‘express’);
const { OpenAIApi } = require(‘openai’);
require(‘dotenv’).config();
const app = express();
app.use(express.json());
const openai = new OpenAIApi({ apiKey: process.env.OPENAI_API_KEY });
app.post(‘/api/getAIResponse’, async (req, res) => {
const { prompt } = req.body;
try {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt,
max_tokens: 150,
});
res.json({ aiText: response.data.choices[0].text.trim() });
} catch (error) {
console.error("Error calling OpenAI:", error);
res.status(500).json({ message: "Error processing your request" });
}
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(Server running on port ${PORT}
);
});