javascriptdiscorddiscord.jsbotsopenai-api

OpenAI API error: "Configuration is not a constructor"


I'm trying to build a Discord bot that generates images, but I faced a problem. I'm getting the following error:

Configuration is not a constructor

I'm following a YouTube tutorial. I have the following code:

const { SlashCommandBuilder, EmbedBuilder} = require(`discord.js`);
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: 'My Key'
});
const openai = new OpenAIApi(configuration);

Can anyone help me solve the problem?


Solution

  • Problem

    The code you have works with the OpenAI Node.js SDK <v4, but you're using >=v4.

    Solution

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

    import OpenAI from "openai";
    
    const client = new OpenAI(
      apiKey: "sk-xxxxxxxxxxxxxxxxxxxxxxxx"
    );
    

    Then you can use, for example, the Images API as follows:

    import OpenAI from "openai";
    
    const client = new OpenAI(
      apiKey: "sk-xxxxxxxxxxxxxxxxxxxxxxxx"
    );
    
    async function main() {
      const image = await client.images.generate({ model: "dall-e-3", prompt: "A cute baby sea otter" });
    
      console.log(image.data);
    }
    
    main();