gpt4 book ai didi

node.js - OpenAI API错误: "OpenAIApi is not a constructor"

转载 作者:行者123 更新时间:2023-12-02 22:47:45 24 4
gpt4 key购买 nike

我想将 ChatGPT API(即 GPT-3.5 API)集成到我的应用程序中。我尝试了很多方法,但没有找到解决我的错误的方法。

我的代码:

require("dotenv").config();

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

const readline = require("readline");

const openaiapi = new OpenAIApi(
new Configuration(
new Configuration(
{ apiKey: process.env.OPENAI_API_KEY }
)
)
);

const userInterface = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

userInterface.prompt();

userInterface.on("line", async (line) => {
const response = await openaiapi.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: line }],
});

console.log(response);
});

错误:

TypeError: OpenAIApi is not a constructor
at Object.<anonymous> (C:\Users\Kvanzi\Desktop\New folder (4)\index.js:7:19)
at Module._compile (node:internal/modules/cjs/loader:1257:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1311:10)
at Module.load (node:internal/modules/cjs/loader:1115:32)
at Module._load (node:internal/modules/cjs/loader:962:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

Node.js v20.3.1

我尝试在互联网上搜索相关信息,但没有找到任何信息。

最佳答案

问题

如果您使用的是最新的 OpenAI NodeJS SDK 版本(即 v4),则需要调整代码,因为 v4 不同v3 非常显着。您当前使用的代码适用于 v3,但不适用于 v4。请参阅下面的更改。

解决方案

初始化

改变这个...

// Old (i.e., OpenAI NodeJS SDK v3)
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

...对此。

// New (i.e., OpenAI NodeJS SDK v4)
import OpenAI from 'openai';

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

创建聊天完成

改变这个...

// Old (i.e., OpenAI NodeJS SDK v3)
const chatCompletion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{role: "user", content: "Hello world"}],
});
console.log(chatCompletion.data.choices[0].message.content);

...对此。

// New (i.e., OpenAI NodeJS SDK v4)
const chatCompletion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{"role": "user", "content": "Hello!"}],
});
console.log(chatCompletion.choices[0].message.content);

注意:SDK v4released于2023年8月16日发布,并且是对SDK的完全重写。请参阅 v3v4 migration guide .

关于node.js - OpenAI API错误: "OpenAIApi is not a constructor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76917548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com