TypeError: openai.Configuration is not a constructor

Issue with Implementing OpenAI API in Node.js Project

Problem Description

We are trying to implement the OpenAI API in a Node.js project but keep encountering the following error:

TypeError: Configuration is not a constructor
    at Object.<anonymous> (/path/to/index.js:3:23)
    at Module._compile (node:internal/modules/cjs/loader:1504:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1588:10)
    at Module.load (node:internal/modules/cjs/loader:1282:32)
    at Module._load (node:internal/modules/cjs/loader:1098:12)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:215:24)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:158:5)
    at node:internal/main/run_main_module:30:49

Configuration and Steps

  1. Node.js Version:

    Node.js v22.5.1
    npm v10.8.2
    
  2. Project Setup:

    mkdir project-directory
    cd project-directory
    npm init -y
    npm install openai@latest
    nano index.js
    
  3. Code in index.js:

    const { Configuration, OpenAIApi } = require("openai");
    
    const configuration = new Configuration({
        apiKey: process.env.OPENAI_API_KEY,
    });
    const openai = new OpenAIApi(configuration);
    
    async function runCompletion() {
        const completion = await openai.createCompletion({
            model: "text-davinci-003",
            prompt: "What is the status of my order?",
        });
        console.log(completion.data.choices[0].text);
    }
    
    runCompletion();
    
  4. Setting the API Key:

    export OPENAI_API_KEY="your-api-key-here"
    
  5. Running the File:

    node index.js
    

Result

The above code raises the error TypeError: Configuration is not a constructor.

Desired Solution

We need help identifying the problem and the correct way to set up and use the OpenAI API in a Node.js project so that the code works correctly and returns a response from the OpenAI model.

Any suggestions or solutions to this problem would be greatly appreciated. Thank you!

1 Like

Here’s how I do it in my project, I don’t use the Configuration object!

const openai = new OpenAI