I’m getting a constructor error when trying to set up the OpenAI API in my Node.js project. I’m pretty new to this stuff so any help would be great.
Here’s what I’m trying to do:
require('dotenv').config();
const { OpenAIApi } = require('openai');
// Set up the OpenAI client using my API key from environment variables
const aiClient = new OpenAIApi(process.env.OPENAI_API_KEY);
/**
* Function to get AI response from user message
* @param {string} message - What the user wants to ask
* @returns {Promise<string>} - AI generated answer
*/
async function getAIResponse(message) {
try {
console.log('Asking AI:', message);
const result = await aiClient.createChatCompletion({
model: "gpt-4-turbo",
messages: [{
role: "user",
content: message
}],
});
if (result.data.choices && result.data.choices.length > 0) {
console.log('Got AI response');
return result.data.choices[0].message.content;
} else {
console.log('AI didnt respond');
throw new Error('No AI response received');
}
} catch (err) {
console.error('AI request failed:', err.message, err.stack);
throw err;
}
}
module.exports = { getAIResponse };
But I keep getting this error:
TypeError: OpenAIApi is not a constructor
at Object.<anonymous> (C:\my-project\aiService.js:5:18)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
I tried different ways to import it but nothing works. My environment file has the API key set up correctly. What am I doing wrong here?