Getting "TypeError: OpenAIApi is not a constructor" when initializing OpenAI client

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?

Yeah, same thing happened to me. You’re using v3 syntax but probably have v4 installed. Try const OpenAI = require('openai') then const client = new OpenAI({apiKey: process.env.OPENAI_API_KEY}). Also swap createChatCompletion for chat.completions.create and drop the .data from your response.

The error you’re encountering is likely due to changes in the OpenAI library’s structure in recent versions. Instead of using the OpenAIApi constructor, you should modify your import to const OpenAI = require('openai'); and initialize the client with const aiClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });. Additionally, the method createChatCompletion has been updated to chat.completions.create, and it is no longer necessary to access the .data property in the result. Ensure your project is using version 4 or higher of the openai package.