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 follow 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 });
The error must gone.
2
Answers
Accordingly to documentation you don’t have to use destructure operator on imported object.
If you ommit it, everything should run fine.
UPD. Actually required object contains needed class, it’s
OpenAI
.So you have to specify the correct name:
UPD2. As Mr. Polywhirl mentioned in comments, there exists third approach. It’s to use class that lies inside imported library object.
All should need to do is remove the curly braces (destructuring).
Note that the official documentation advises you name the import
OpenAI
per the example usage, but you should be able to name it anything you like.If you open up
node_modules/openai/src/index.js
, you will seeexports.default = OpenAI;
as the bottom. This is exportingclass OpenAI extends Core.APIClient
as the default export. This means you can name it anything you want, when you import the library.What may seem confusing is that
index.ts
has the following exports. The class and the namespace have the same name.This compiles to the following JS, because
esModuleInterop
is set totrue
in theopenai-node
libraries tsconfig.jsonA better approach
Store your API key appropriately
dotenv
as a dependencyAPI_KEY
to your.env
file at the root of your projectAlternatively
You can use the preferred environment variable