我遇到错误:
const openai = new OpenAIApi({ key: apiKey });
^
TypeError: OpenAIApi is not a constructor
当我尝试使用nodejs(v16.7.0)创建openai api时。我已按照文档中的代码安装了 openai api (v4.3.1)
我使用的代码:
const { OpenAIApi } = require('openai');
const openai = new OpenAIApi({ key: apiKey });
我该如何解决这个问题?
最佳答案
据documentation您不必对导入的对象使用解构运算符。
如果您忽略它,一切都会正常运行。
const OpenAIApi = require('openai');
const openai = new OpenAIApi({ key: apiKey });
UPD。实际上所需的对象包含所需的类,它是OpenAI
。
所以你必须指定正确的名称:
const { OpenAI } = require('openai');
const openai = new OpenAI({ key: apiKey });
UPD2。如Mr. Polywhirl评论中提到,存在第三种方法。它是使用位于导入的库对象内部的类。
const OpenAIApi = require('openai');
const openai = new OpenAIApi.OpenAI({ key: apiKey });
关于javascript - 类型错误 : OpenAIApi is not a constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77008683/