Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: OpenAIApi is not a constructor

i got error:

const openai = new OpenAIApi({ key: apiKey });
               ^

TypeError: OpenAIApi is not a constructor

when I'm trying to create an openai api using nodejs (v16.7.0). I've followed the code in documentation and installed the openai api (v4.3.1)

code I used:

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

const openai = new OpenAIApi({ key: apiKey });

How can I resolve this?

like image 268
Justine Gwapo Avatar asked Jul 26 '26 01:07

Justine Gwapo


2 Answers

Accordingly to documentation you don't have to use destructure operator on imported object.

If you ommit it, everything should run fine.

const OpenAIApi = require('openai');

const openai = new OpenAIApi({ key: apiKey });

UPD. Actually required object contains needed class, it's OpenAI.
So you have to specify the correct name:

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

const openai = new OpenAI({ key: apiKey });

UPD2. As Mr. Polywhirl mentioned in comments, there exists third approach. It's to use class that lies inside imported library object.

const OpenAIApi = require('openai');

const openai = new OpenAIApi.OpenAI({ key: apiKey });
like image 137
Jaood_xD Avatar answered Jul 28 '26 15:07

Jaood_xD


The thing is that you used version 3 code, but probably have installed the newest version (like myself), which is 4. Check the latest docs, they changed a lot of stuff: https://www.npmjs.com/package/openai/v/4.12.4

like image 33
Gishas Avatar answered Jul 28 '26 14:07

Gishas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!