Search code examples
node.jsdiscordopenai-apigpt-4

OpenAI API error: "TypeError: OpenAIApi is not a constructor"


I am having an issue trying to get this code to call my OPENAI_API_KEY in the .env file. I am very new to Node.js, so please speak to me like I'm an idiot.

See the error at the bottom after the code.

Code:

require('dotenv').config();
const { OpenAIApi } = require('openai');

// Initialize OpenAI API client with the API key from your .env file
const openaiClient = new OpenAIApi(process.env.OPENAI_API_KEY);


/**
 * Generates a response using ChatGPT-4 Turbo based on the provided user input.
 * @param {string} userInput - The user's message input.
 * @returns {Promise<string>} - The generated response from ChatGPT-4 Turbo.
 */
async function generateResponse(userInput) {
  try {
    console.log('Sending input to OpenAI API:', userInput);
    const response = await openaiClient.createChatCompletion({
      model: "gpt-4-turbo",
      messages: [{
        role: "user",
        content: userInput
      }],
    });

    if (response.data.choices && response.data.choices.length > 0) {
      console.log('Received response from OpenAI API');
      return response.data.choices[0].message.content;
    } else {
      console.log('No response from OpenAI API.');
      throw new Error('No response from OpenAI API');
    }
  } catch (error) {
    console.error('Failed to generate response from OpenAI API:', error.message, error.stack);
    throw error; // Rethrow to handle it in the calling function
  }
}

module.exports = { generateResponse };

Error:

L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\chatService.js:5
const openaiClient = new OpenAIApi(process.env.OPENAI_API_KEY);
                     ^

TypeError: OpenAIApi is not a constructor
    at Object.<anonymous> (L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\chatService.js:5:22)
    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 Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Client.<anonymous> (L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\bot.js:34:30)
    at Client.emit (node:events:518:28)
    at MessageCreateAction.handle (L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:28:14)

Node.js v20.11.1

I also tried this but it's not working:

const { OpenAIApi } = require('openai');

Solution

  • Step 1: Install the most recent OpenAI Node.js SDK

    You said in the comment above that you would like to use the most recent syntax. So, first of all, make sure that you have the most recent OpenAI Node.js SDK installed. Run the following command:

    npm install openai@latest
    

    As of today, v4.29.0 is the most recent one. Before you proceed, check the version by running the following command:

    npm view openai version
    

    You should see 4.29.0 in the terminal.

    Step 2: Fix the code

    You have more than one mistake in your code, but you don't know about them yet because the initialization was the first error that was thrown. After you fix this error, only then will the next error be thrown.

    The OpenAI Node.js SDK >=v4 (i.e., including the newest one) has a lot of breaking changes compared to <v4. Among them, it's also the initialization that caused your error. But as I said, you have more mistakes in your code.

    The following is the correct initialization using the OpenAI Node.js SDK >=v4:

    const OpenAI = require("openai");
    
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });
    

    The following is the correct method name using the OpenAI Node.js SDK >=v4:

    openai.chat.completions.create
    

    The following is the correct message retrieval using the OpenAI Node.js SDK >=v4:

    response.choices[0].message.content
    

    Full code

    require('dotenv').config();
    const OpenAI = require("openai");
    
    // Initialization
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });
    
    async function generateResponse(userInput) {
      try {
        console.log('Sending input to OpenAI API:', userInput);
        const response = await openai.chat.completions.create({ // Method name
          model: "gpt-4-turbo",
          messages: [{
            role: "user",
            content: userInput
          }],
        });
    
        if (response.choices && response.choices.length > 0) {
          console.log('Received response from OpenAI API');
          return response.choices[0].message.content; // Message retrieval
        } else {
          console.log('No response from OpenAI API.');
          throw new Error('No response from OpenAI API');
        }
      } catch (error) {
        console.error('Failed to generate response from OpenAI API:', error.message, error.stack);
        throw error;
      }
    }
    
    module.exports = { generateResponse };