Node.js and OpenAI API integration: Module not found error

I’m stuck trying to use the OpenAI API in my Node.js project. When I run my code, I get a Cannot find module '@openai/api' error. It’s really frustrating!

Here’s what I’ve tried so far:

  • Installing the package with npm install @openai/api (got a 404 error)
  • Updating Node.js to version 19.1.0
  • Creating a test script to check if it’s just my main project or a general issue

My test script looks like this:

const openai = require('openai');

openai.apiKey = 'my-api-key';

async function testOpenAI() {
  try {
    const response = await openai.Completion.create({
      engine: 'text-davinci-002',
      prompt: 'What\'s the weather like today?',
      max_tokens: 30
    });
    console.log(response.choices[0].text);
  } catch (error) {
    console.error(error);
  }
}

testOpenAI();

But when I run it, I still get the same error. The weird thing is, I can use the API through other tools like Postman without any issues.

Does anyone know what might be causing this problem or have any ideas on how to fix it? I’m totally lost here. Thanks for any help!

hey sarah, sounds like ur using the wrong package name. try npm install openai instead of @openai/api. then in ur code, change the import to const { Configuration, OpenAIApi } = require('openai');. that should fix it. lmk if u need more help!

I had a similar experience while working with the OpenAI API in Node.js. The key issue was a mix-up with the package name and module import. The solution was to install the correct package using ‘npm install openai’ and adjust the import statement accordingly. For example, you would use:

const { Configuration, OpenAIApi } = require(‘openai’);

Then, set up your configuration and initialize the API client. This approach resolved the module error. Also, make sure your API key is securely stored, preferably as an environment variable.